Ahojte,

2011/4/13 Libor Jelinek <[email protected]>:
> Studuju collection framework a mám k otázku rozhraní Map. To má uvedeno, že
> je to pár key-value <K, V>.
..
> Proč tedy metoda jako containsKey() je deklarována jako containsKey(Object
> key) a nikoli containsKey(K key)?
> Dále např. proč je V get(Object key) a nikoli V get(K key)? Poč je V
> remove(Object key) a nikoli V remove(K key)?

Copy/paste ze stackoverflow
(http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic):
As mentioned by people above, the reason why get(), etc. is not
generic because the key of the entry you are retrieving does not have
to be the same type as the object that you pass in to get(); the
specification of the method only requires that they be equal. This
follows from how the equals() method takes in an Object as parameter,
not just the same type as the object.

Although it may be commonly true that many classes have equals()
defined so that its objects can only be equal to objects of its own
class, there are many places in Java where this is not the case. For
example, the specification for List.equals() says that two List
objects are equal if they are both Lists and have the same contents,
even if they are different implementations of List. So coming back to
the example in this question, according to the specification of the
method is possible to have a Map<ArrayList, Something> and for me to
call get() with a LinkedList as argument, and it should retrieve the
key which is a list with the same contents. This would not be possible
if get() were generic and restricted its argument type.

> Díky
> Libor

-- pepa cacek

Odpovedet emailem