gpt4 book ai didi

java - 为什么 Java 的 TreeSet remove(Object) 不带 E

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:12 26 4
gpt4 key购买 nike

来自 Java 6 TreeSet<E> 文档:

boolean remove(Object o):
Removes the specified element from this set if it is present.

为什么它接受一个对象而不是泛型类型 E?唯一可以添加的对象是 E 类型,因此唯一可移动的类型应该是 E 类型。

最佳答案

从发布的第一条评论中获取答案:

神话:

A popular myth is that it is stupid and evil, but it was necessary because of backward compatibility. But the compatibility argument is irrelevant; the API is correct whether you consider compatibility or not.

真实原因:

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.

在这里阅读更多:Why does Set.contains() take an Object, not an E?

关于java - 为什么 Java 的 TreeSet<E> remove(Object) 不带 E,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8015720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com