-3

Why is the following code failing with compilation error?

class SampleClass{

}

public class DemoHashMap {

public static void main(String[] args) {
        SampleClass s1 = new SampleClass();
        SampleClass s2 = new SampleClass();

        Map<Object, Integer> counts = new HashMap<Object, Integer>();
        counts.add(s1, 1);
        counts.add(s2, 2);
    }
}

This code is not allowing me to add s1 & s2 to the hashmap. In the declaration for counts I have specified that the key can be Object.

Ashish K Agarwal
  • 1,122
  • 3
  • 17
  • 31
  • Did you mean put rather than add? – Oliver Charlesworth May 05 '15 at 04:41
  • possible duplicate of [Using an instance of an object as a key in hashmap, and then access it with exactly new object?](http://stackoverflow.com/questions/9440380/using-an-instance-of-an-object-as-a-key-in-hashmap-and-then-access-it-with-exac) – PM 77-1 May 05 '15 at 04:41
  • When you post questions about errors, include the error text. Also, this question is trivially solvable by looking at the Map API. – justhecuke May 05 '15 at 05:08

3 Answers3

3

There is no add method in Map.Use put instead.

counts.put(s1, 1);

See :- HashMap

dReAmEr
  • 6,182
  • 7
  • 34
  • 52
2

There are few corrections to be done.

First there is no add() in Map, try put() instead.

Secondly it is recommended to override hashCode() and equals() of class SampleClass when using it as key.

Also since you are using generics it is recommended to declare map as:

Map<SampleClass, Integer> counts = new HashMap<SampleClass, Integer>();

0

Try this:

Map<SampleClass, Integer> counts = new HashMap<SampleClass, Integer>();
counts.put(s1, 1)
Misch
  • 8,600
  • 4
  • 33
  • 48
Vinay S Jain
  • 111
  • 11