Map.get(Object key)不是(完全)通用的原因是什么 [英] What are the reasons why Map.get(Object key) is not (fully) generic

查看:361
本文介绍了Map.get(Object key)不是(完全)通用的原因是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

To clarify the question, the signature of the method is

V get (Object key)

而不是

V get(K key)

我想知道为什么 remove,containsKey,containsValue

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

推荐答案

正如其他人所说, get / code>等不是通用的,因为您检索的条目的键不必与您传递给 get();该方法的规范仅要求它们相等。这跟随 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.

这篇关于Map.get(Object key)不是(完全)通用的原因是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆