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

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

问题描述

决定没有完全通用的get方法背后的原因是什么在的界面中java.util.Map.

What are the reasons behind the decision to not have a fully generic get method in the interface of 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()等之所以不泛型是因为你检索的条目的key不必与您传递给 get() 的对象具有相同的类型;该方法的规范仅要求它们相等.这遵循 equals() 方法如何接受一个对象作为参数,而不仅仅是与对象相同的类型.

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 对象都是 List 并且内容相同,则它们是相等的,即使它们是 List.所以回到这个问题中的例子,根据方法的规范可能有一个 Map 并且我可以调用 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天全站免登陆