为什么没有Java集合删除方法generic? [英] Why aren't Java Collections remove methods generic?

查看:147
本文介绍了为什么没有Java集合删除方法generic?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Collection.remove(Object o) generic?

Why isn't Collection.remove(Object o) generic?

看起来像 Collection< E> 可以有 boolean remove(E o);

然后,当您不小心尝试删除(例如) Set< String> 而不是 Collection< String> 中的每个单独的字符串,这将是一个编译时错误,而不是以后的调试问题。

Then, when you accidentally try to remove (for example) Set<String> instead of each individual String from a Collection<String>, it would be a compile time error instead of a debugging problem later.

推荐答案

Josh Bloch和Bill Pugh在

Josh Bloch and Bill Pugh refer to this issue in Java Puzzlers IV: The Phantom Reference Menace, Attack of the Clone, and Revenge of The Shift.

Josh Bloch说(6:41)他们试图生成Map,remove方法和其他方法的get方法
,但是它根本不工作。

Josh Bloch says (6:41) that they attempted to generify the get method of Map, remove method and some other, but "it simply didn't work".

有太多合理的程序无法生成,如果
只允许集合的通用类型作为参数类型。
他给出的例子是 List Number s和
的交集 列表。

There are too many reasonable programs that could not be generified if you only allow the generic type of the collection as parameter type. The example given by him is an intersection of a List of Numbers and a List of Longs.

这篇关于为什么没有Java集合删除方法generic?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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