Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic classes taking Object parameters - Java [duplicate]

Tags:

java

generics

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?

like image 388
James Avatar asked Apr 28 '26 15:04

James


1 Answers

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.

like image 126
coredump Avatar answered May 01 '26 06:05

coredump