为什么Map.containsKey()使用Object参数而不是专用类型? [英] Why Map.containsKey() takes an Object parameter instead of a speciallized type?

查看:74
本文介绍了为什么Map.containsKey()使用Object参数而不是专用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
>为什么使用Map.get的原因是什么(对象密钥)不是(完全)通用
Java泛型:为什么Map.get()会忽略类型?

Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic
Java Generics: Why Does Map.get() Ignore Type?

Java

Java Map interface is declared like this:

Interface Map<K,V>

它具有这样的方法:

boolean containsKey(Object key)

为什么不 boolean containsKey(K key)?

相反,

On the contrary, the List interface has add method that takes parameter of generic type instead of Object:

boolean add(E e).

推荐答案

这是您不能向List<? extends E>添加任何内容的相同原因,因为编译器无法保证类型安全(并且类型擦除使运行时成为可能)检查不可能).

It's the same reason why you can't add anything to a List<? extends E> because the compiler can't guarantee the type safety (and type erasure makes a runtime check impossible).

这意味着当您获得Map<? extends K,V>时,将无法对其调用contains(K).但是contains足够通用,以至于将随机Object传递给它不会损坏接口(但会使一些错误更难识别).

This means that when you get a Map<? extends K,V> you wouldn't be able to call contains(K) on it. however contains is general enough that passing random Objects to it won't damage the interface (but makes some errors harder to pick up).

这篇关于为什么Map.containsKey()使用Object参数而不是专用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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