我试图在ConcurrentSkipListSet中维护插入顺序。要添加的项是具有value(String)和index(int)属性的自定义类类型。它实现了Comparable接口。该集的行为非常不一致,有时会添加重复项。如果项目具有相同的值,则视为重复。
// This is the Item class being added in the set.final class Item implements Comparable<Item> {
private String value;
private int index;
Item(String val, int idx) {
this.value = val;
this.index = idx;
}
@Override
public int compareTo(Item o) {
// returns zero when values are equal indicating it's a duplicate item.
return this.value.equals(o.value) ? 0 : this.index - o.index;
}
@Override
public String toString() {
return this.value;
}
}// Below is the main class.public class Test {
ConcurrentSkipListSet<Item> set;
AtomicInteger index;
public Test() {
set = new ConcurrentSkipListSet<>();
index = new AtomicInteger(0);
}
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
Test test = new Test();
test.addItems();
test.assertItems();
}
}//trying to test it for 10 times. It always fails for once or twice.
private void assertItems() {
Iterator<Item> iterator = set.iterator();
String[] values = {"yyyy", "bbbb", "aaaa"};
for (String value : values) {
if (!value.equals(iterator.next().toString())) {
System.out.println("failed for :" + set);
return;
}
}
System.out.println("passed for :" + set);
}预期:通过:[yyyy,bbbb,aaaa]
实际:失败:[yyyy,bbbb,yyyy,aaaa]
但如前所述,结果非常不一致。大多数时候,它都过去了。请告诉我这可能是什么原因。'compareTo()'方法是错误的吗?如果是这样,它应该总是失败。
理想情况下,我们也应该覆盖'equals()'方法。但是从排序集的角度来看并不重要。
感谢您的帮助。
长风秋雁
慕妹3146593
暮色呼如
随时随地看视频慕课网APP
相关分类