3

Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic

I have a question about the Generic java collections, specifically Map. I notice that the get, contains and similar methods that require a parameter (usually the key) take an Object as the parameter, while I would have expected them to take something of class K, e.g. rather than get(Object key) I would expect get(K key). Can anyone explain the reason for this?

Community
  • 1
  • 1
James
  • 2,483
  • 2
  • 24
  • 31
  • 1
    Think this will help http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic The awesome power of the searchbar ;) – David Sep 19 '12 at 14:03
  • I had this question already, but I didn't take any time searching for an answer. Good question. – gdfbarbosa Sep 19 '12 at 14:04
  • 1
    see http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic – yair Sep 19 '12 at 14:05

2 Answers2

2

As it says here, it is because the object you pass to get does not have to be equal to the type of the key you are trying to retrieve.

The only condition is that their equals method return true.

EDIT: As Peter Lawrey pointed out, the hashcode should be the same.

Community
  • 1
  • 1
coredump
  • 3,017
  • 6
  • 35
  • 53
0

The main problem is backward compatibility.

It was always possible to attempt to do the following, even if you "know" its not going to work

Map map = new HashMap();
map.put("hello", "world");

Object o = map.get(1); // null
boolean b = map.contain(2); // false
boolean b2 = map.remove(3); // false

As a result these methods still need to be able to take any type even though the generics implies that it will always return null or false.


Also its possible to construct a TreeMap where the keys don't need to be the same type, equals true, have the same hashCode or even compareTo() == 0

Map map = new TreeMap(new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        return String.valueOf(o1).compareTo(o2.toString());
    }
});
map.put("1", "one");
map.put(2, "two");
map.put(3L, "three");
map.put('4', "four");

for(Object o: new Object[] { 1L, '2', 3, "4"}) {
    System.out.println(o.getClass().getSimpleName()+" "+o+" => "+map.get(o));
}

prints

Long 1 => one
Character 2 => two
Integer 3 => three
String 4 => four
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130