为什么 Java 集合的删除方法不是通用的? [英] Why aren't Java Collections remove methods generic?

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

问题描述

为什么不是 Collection.remove(Object o) 通用吗?

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

似乎 Collection 可以有 boolean remove(E o);

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

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 在 Java Puzzlers IV:幻影参考威胁、克隆人的进攻和复仇者的复仇移位.

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) 他们试图泛化 get 方法Map、remove 方法和其他一些方法,但它根本不起作用".

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".

有太多合理的程序无法泛化,如果您只允许集合的泛型类型作为参数类型.他举的例子是一个NumberList和一个List的交集List Longs.

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 集合的删除方法不是通用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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