JDK中的equals
implementatin的java.util.concurrent.ConcurrentSkipListSet
是如下JDK java.util.concurrent.ConcurrentSkipListSet.equals(對象o)執行效率
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
@EJP實際上'ConcurrentSkipListSet'擴展了'NavigableSet',它擴展了'SortedSet' –
請在[email protected]郵件列表中討論你的問題。 – Fairoz