Map.get(Object key)不是(完全)泛型的原因是什么?

Map.get(Object key)不是(完全)泛型的原因是什么?

问题描述:

的原因是什么? /util/Map.html#get(java.lang.Object)rel =noreferrer> java.util.Map< K,V>

为了澄清问题,方法的签名是

To clarify the question, the signature of the method is

V get对象键)

而不是

V get (K键)

我想知道为什么(同样的东西为 remove,containsKey,containsValue $

and I'm wondering why (same thing for remove, containsKey, containsValue).

如其他人所提到的,为什么 get()等不是通用的,因为您检索的条目的键不必与传入 get()$ c $的对象的类型相同C>;该方法的规范只要求它们相等。这是从 equals()方法如何将Object作为参数,而不仅仅是与对象相同的类型。

As mentioned by others, 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.

尽管很多类都有 equals()定义,因此它的对象只能等于其自己的类的对象,但是很多地方Java不是这样的。例如, List.equals()的规范说,如果两个List对象都是列表,并且具有相同的内容,即使它们是不同的列表。所以回到这个问题的例子,根据该方法的规范可能有一个 Map< ArrayList,Something> ,而且我可以调用 get() LinkedList 作为参数,它应该检索具有相同内容的列表的密钥。如果 get()是通用的并限制其参数类型,则不可能。

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.