Java泛型:为什么Map.get()忽略类型? [英] Java Generics: Why Does Map.get() Ignore Type?

查看:87
本文介绍了Java泛型:为什么Map.get()忽略类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,Map接口被定义为,

  public interface Map< K,V> {
...
V get(Object key);
...
}

为什么不能?

  V get(K key); 

我只是碰到了一个讨厌的bug,因为使用了错误的类型键。我认为泛型的目的是在编译期间尽早捕获类型错误。这样做是否能达到目的?

凯文布瑞尔恩博客关于这个前一段时间。简介:


统一地,Java
Collections Framework(以及Google
Collections Library)的方法从不
限制其参数
的类型,除非有必要防止
集合被破坏。



<我个人并不喜欢这种方法,但考虑到也采取了差异方法,它确实有一定意义。


In Java, the Map interface is defined as,

public interface Map<K,V> {
    ...
    V get(Object key);
    ...
}

Why not?

V get(K key);

I just bumped into a nasty bug because wrong type key is used. I thought the purpose of the generics is to catch type error early during compiling. Does this defeat that purpose?

解决方案

Kevin Bourrillion blogged about this a while ago. Summary:

Uniformly, methods of the Java Collections Framework (and the Google Collections Library too) never restrict the types of their parameters except when it's necessary to prevent the collection from getting broken.

Personally I'm not a fan of that approach, but it does make some sense given the variance approach which has also been taken.

这篇关于Java泛型:为什么Map.get()忽略类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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