【发布时间】:2017-05-26 09:27:58
【问题描述】:
JDK中java.util.concurrent.ConcurrentSkipListSet的equalsimplementatin如下
public boolean equals(Object o) {
// Override AbstractSet version to avoid calling size()
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
try {
return containsAll(c) && c.containsAll(this);
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
但我认为下面的代码似乎更高效
public boolean myEquals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
if (c.size() != this.size()) {
return false;
}
Iterator ic = c.iterator();
Iterator id = iterator();
while (ic.hasNext() && id.hasNext()) {
if (!ic.next().equals(id.next())) {
return false;
}
}
return true;
}
而且一个简单的测试也可能支持第二个equals
public class Test {
public static void main(String[] args) {
ConcurrentSkipListSet<Integer> set1 = new ConcurrentSkipListSet<Integer>();
ConcurrentSkipListSet<Integer> set2 = new ConcurrentSkipListSet<Integer>();
for (int i = 0; i < 10000000; i++) {
set1.add(i);
set2.add(i);
}
long ts = System.currentTimeMillis();
System.out.println(set1.equals(set2));
System.out.println(System.currentTimeMillis() - ts);
ts = System.currentTimeMillis();
System.out.println(myset1.myEquals(myset2));
System.out.println(System.currentTimeMillis() - ts);
}
}
输出结果
true
2713
true
589
在 JDK 评论中它说,This definition ensures that the equals method works properly across different implementations of the set interface. 谁能解释一下?
【问题讨论】:
-
您的代码假定两个集合都是有序的。他们没有。
-
@EJP 实际上是
ConcurrentSkipListSet扩展NavigableSet扩展SortedSet -
请在 core-libs-dev@openjdk.java.net 邮件列表中讨论您的问题。
-
谢谢@Fairoz,我稍后再发。
-
对不起@EJP,我误解了,
this是有序的,但equals()的参数,即Object o可能没有有序。谢谢
标签: java performance collections iterator openjdk