gpt4 book ai didi

java - 为通用集合编写 contains()

转载 作者:搜寻专家 更新时间:2023-11-01 01:19:10 25 4
gpt4 key购买 nike

我正在用 Java 编写一个跳过列表类作为练习。我写了一个类 SkipListInternal<E>其中包含实际的跳过列表。我还制作了一个名为 SkipListSet<E> 的包装类实现SortedSet<E>接口(interface)并包含 SkipListInternal<E> 的实例.

除其他外,SkipListInternal<E>包含一个方法 E find(E e)返回等于 e 的元素如果它存在,否则返回 null。

boolean contains(Object o) 时(继承自 Collection<E> 通过 SortedSet<E> )方法我注意到它的参数是一个对象而不是一个 E。我打算做这样的事情,但由于类型删除而不可能:

public class SkipListSet<E> implements SortedSet<E>{
private SkipListInternal<E> skiplist;

...

public boolean contains(Object o){
if (!(o instanceof E)) return false;
return skiplist.find((E) o) != null;
}

...

}

既然这样不行,那我该怎么办呢?

最佳答案

严格来说这样的实现是错误的。

这样做的原因是,即使对象不是 E 类型,它仍然可以在 equals() 上返回 true打电话。

假设你有一个这样的类:

public class FakeString {
private final String value;

public FakeString(String value) {
if (value == null) {
throw new IllegalArgumentException();
}
this.value = value;
}

public int hashCode() {
return value.hashCode();
}

public boolean equals(Object o) {
return value.equals(o);
}
}

然后这段代码会打印true:

List<String> strings = Arrays.asList("foo", "bar", "baz");
System.out.println(strings.contains(new FakeString("bar")));

澄清一下:这种行为是有意的,也是 contains() 采用 Object 而不是 E 的原因。顺便说一句,remove() 也是如此。

关于java - 为通用集合编写 contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4992047/

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