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?

3
  • 1
    Think this will help stackoverflow.com/questions/857420/… The awesome power of the searchbar ;) Commented Sep 19, 2012 at 14:03
  • I had this question already, but I didn't take any time searching for an answer. Good question. Commented Sep 19, 2012 at 14:04
  • 1
    see stackoverflow.com/questions/857420/… Commented Sep 19, 2012 at 14:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

hashCode should be the same as well.
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 

2 Comments

well, see answer on this here
I wonder why the downvote. It seems reasonable, as Map existed before generics were introduced.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.