为什么我们有 contains(Object o) 而不是 contains(E e)?

发布于 2024-09-04 20:22:03 字数 180 浏览 8 评论 0原文

是为了保持与旧版(非通用化)Collection 版本的向后兼容性吗?还是我遗漏了更微妙的细节?我在 remove 中也看到了这种模式 (remove(Object o)),但 add 被泛化为 add(E e)

Is it to maintain backwards compatibility with older (un-genericized) versions of Collection? Or is there a more subtle detail that I am missing? I see this pattern repeated in remove also (remove(Object o)), but add is genericized as add(E e).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

撩心不撩汉 2024-09-11 20:22:03

contains() 接受一个 Object,因为它匹配的对象不必与您传递给 contains() 的对象类型相同>;它只要求它们是平等的。根据 contains() 的规范,如果存在对象 e 使得 (o== null ? e==null : o.equals(e)) 为真。请注意,没有任何要求 oe 为相同类型。这是因为 equals() 方法接受 Object 作为参数,而不仅仅是与对象相同的类型。

尽管许多类都定义了 equals() ,因此其对象只能等于其自己类的对象,但情况并非总是如此。例如,List.equals() 的规范规定,如果两个 List 对象都是 List 并且具有相同的内容,则它们相等,即使它们是 List 的不同实现。因此,回到这个问题中的示例,可以有一个 Collection 并且我可以使用 LinkedList 调用 contains() code> 作为参数,如果存在具有相同内容的列表,则可能返回 true。如果 contains() 是通用的并将其参数类型限制为 E,则这是不可能的。

事实上,contains() 将任何对象作为参数,这一事实允许您进行有趣的使用,您可以使用它来测试集合中是否存在满足特定属性的对象:

Collection<Integer> integers;
boolean oddNumberExists = integers.contains(new Object() {
    public boolean equals(Object e) {
        Integer i = (Integer)e;
        if (i % 2 != 0) return true;
        else return false;
    }
});

contains() takes an Object because the object it matches does not have to be the same type as the object that you pass in to contains(); it only requires that they be equal. From the specification of contains(), contains(o) returns true if there is an object e such that (o==null ? e==null : o.equals(e)) is true. Note that there is nothing requiring o and e to be the same type. This follows from the fact that the equals() method takes in an Object as parameter, not just the same type as the object.

Although it may be commonly true that many classes have equals() defined so that its objects can only be equal to objects of its own class, that is certainly not always the case. For example, the specification for List.equals() says that two List objects are equal if they are both Lists and have the same contents, even if they are different implementations of List. So coming back to the example in this question, it is possible to have a Collection<ArrayList> and for me to call contains() with a LinkedList as argument, and it might return true if there is a list with the same contents. This would not be possible if contains() were generic and restricted its argument type to E.

In fact, the fact that contains() takes any object as an argument allows an interesting use where you can to use it to test for the existence of an object in the collection that satisfies a certain property:

Collection<Integer> integers;
boolean oddNumberExists = integers.contains(new Object() {
    public boolean equals(Object e) {
        Integer i = (Integer)e;
        if (i % 2 != 0) return true;
        else return false;
    }
});
谁的年少不轻狂 2024-09-11 20:22:03

在此回答。
为什么 Java 集合删除方法不是通用的?
简而言之,他们希望最大化向后兼容性,因为集合早在泛型之前就已被引入。

我补充一下:他提到的视频值得一看。
http://www.youtube.com/watch?v=wDN_EYUvUq0

更新
澄清一下,(在视频中)说这句话的人是更新 java 地图和集合以使用泛型的人之一。如果他不知道,那又是谁。

Answered here.
Why aren't Java Collections remove methods generic?
In short, they wanted to maximize backwards compatibility, because collections have been introduced long before generics.

And to add from me: the video he's referring is worth watching.
http://www.youtube.com/watch?v=wDN_EYUvUq0

update
To clarify, the man who said that (in the video) was one of the people who updated java maps and collections to use generics. If he doesn't know, then who.

囚我心虐我身 2024-09-11 20:22:03

这是因为 contains 函数利用了 equals 函数,而 equals 函数是在 Object 基类中定义的,其签名为 equals(Object o) 而不是 equals(E e) (因为并非所有类都是通用的)。与 remove 函数的情况相同 - 它使用接受 Object 参数的 equals 函数遍历集合。

然而,这并不能直接解释这个决定,因为他们仍然可以使用类型 E 并允许它在调用 equals 时自动转换为 Object 类型;但我想他们希望允许在其他对象类型上调用该函数。拥有一个 Collection并没有什么问题。 c; 然后调用 c.contains(somethingOfTypeBar) - 它总是返回 false,因此不需要强制转换为 Foo 类型(可能会引发异常),或者,为了防止异常,typeof 调用。因此,您可以想象,如果您要迭代具有混合类型的内容并对每个元素调用contains,则可以简单地对所有元素使用contains 函数,而不需要防护。

当你这样看时,它实际上让人想起“较新的”松散类型语言......

It is because the contains function utilizes the equals function, and the equals function is defined in the base Object class with a signature of equals(Object o) rather than equals(E e) (since not all classes are generic). Same case with the remove function - it traverses the collection using the equals function which takes an Object argument.

This doesn't directly explain the decision however, as they could've still used type E and allowed it to be automatically cast to type Object on the call to equals; but I imagine they wanted to allow the function to be called on other Object types. There's nothing wrong with having a Collection<Foo> c; and then calling c.contains(somethingOfTypeBar) - it will always return false, and so it eliminates the need for a cast to type Foo (which can throw an exception) or, to protect from the exception, a typeof call. So you can imagine if you're iterating over something with mixed types and calling contains on each of the elements, you can simply use the contains function on all of them rather than needing guards.

It's actually reminiscent of the "newer" loosely-typed languages, when you look at it that way...

抚你发端 2024-09-11 20:22:03

因为否则它只能与参数类型的精确匹配进行比较,特别是通配符集合将停止工作,例如

class Base
{
}

class Derived
  extends Base
{
}

Collection< ? extends Base > c = ...;

Derived d = ...;

Base base_ref = d;

c.contains( d ); // Would have produced compile error

c.contains( base_ref ); // Would have produced compile error

编辑
对于认为这不是原因之一的怀疑者,这里是一个修改后的数组列表,其中包含一个将被泛化的 contains 方法

class MyCollection< E > extends ArrayList< E >
{
    public boolean myContains( E e )
    {
        return false;
    }
}

MyCollecttion< ? extends Base > c2 = ...;

c2.myContains( d ); // does not compile
c2.myContains( base_ref ); // does not compile

基本上 contains( Object o ) 是一个让这个非常常见的用例可以使用的 hack Java 泛型。

Because otherwise it could have only be compared to the exact match of parameter type, specifically wildcarded collections would have stopped working, e.g.

class Base
{
}

class Derived
  extends Base
{
}

Collection< ? extends Base > c = ...;

Derived d = ...;

Base base_ref = d;

c.contains( d ); // Would have produced compile error

c.contains( base_ref ); // Would have produced compile error

EDIT
For doubters who think that's not one of the reasons, here is a modified array list with a would be generified contains method

class MyCollection< E > extends ArrayList< E >
{
    public boolean myContains( E e )
    {
        return false;
    }
}

MyCollecttion< ? extends Base > c2 = ...;

c2.myContains( d ); // does not compile
c2.myContains( base_ref ); // does not compile

Basically contains( Object o ) is a hack to make this very common use case to work with Java Generics.

注定孤独终老 2024-09-11 20:22:03

“那篮子苹果里有这个橙子吗?”

显然无法给出正确的答案。但这仍然留下了太多的可能性:

  1. 答案是错误的。
  2. 该问题格式不正确,不应通过编译。

集合 api 选择了第一个。但第二个选择也很有意义。像这样的问题99.99%都是废话,所以别问!

"does that basket of apples contain this orange?"

clearly a TRUE answer cannot be given. but that still leaves too possibilities:

  1. the answer is FALSE.
  2. the question is not well formed, it should not pass compile.

the collection api chose the 1st one. but the 2nd choice would also make perfect sense. a question like that is a bullshit question 99.99% of times, so don't even ask!

回忆凄美了谁 2024-09-11 20:22:03

Java 集合泛型类做出了合理的假设,即任何采用类型参数的方法都可以。因为输入被视为可变方法。并且在泛型方法的实现中禁止调用此类方法。但是 contains() 方法需要被视为不可变方法,并且它的调用应该在泛型方法的实现中成为可能。这就是为什么 contains() 方法接受 Object 作为输入而不是输入的原因。作为输入。

Java collections generic classes make a reasonable assumption that any method that takes parameter of type <E> as input is considered as mutable method. And the call to such methods is prohibited within the implementation of generic methods. But contains() method needs to be treated as immutable method and its call should be made possible within the implementation of generic methods. This is why contains() method accepts Object as input and not type <E> as input.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文