Я написал фрагмент кода, чтобы узнать больше о функции java collection для Comparator
. У меня есть два набора, каждый из которых имеет по 3 элемента. и я хочу сравнить. Я отправляю свой код ниже и вывод переменной счетчика. Может ли кто-нибудь объяснить, почему переменная i
дает этот странный результат? Я не мог понять поток.Странный вывод переменной счетчика в компараторе java
public class TestProductBundle {
public static void main(String args[]) {
TestProductBundle productBundle = new TestProductBundle();
Set<ClassA> hashSetA = new HashSet<ClassA>() {
{
add(new ClassA("name", 1, "desc"));
add(new ClassA("name", 2, "desc"));
add(new ClassA("name", 3, "desc"));
}
};
Set<ClassA> hashSetB = new HashSet<ClassA>() {
{
add(new ClassA("name1", 2, "desc1")); //"name" & "desc" are different than previous
add(new ClassA("name2", 1, "desc2"));
add(new ClassA("name3", 3, "desc3"));
}
};
if (productBundle.compareCollection(hashSetA, hashSetB)) {
System.out.println("Equal set of tree");
} else {
System.out.println("Unequal set of tree");
}
}
@SuppressWarnings("serial")
public boolean compareCollection(Set<ClassA> collection1, Set<ClassA> collection2) {
TreeSet<ClassA> treeSetA = new TreeSet<ClassA>(new CompareID()) {
{
addAll(collection1);
}
};
TreeSet<ClassA> treeSetB = new TreeSet<ClassA>(new CompareID()) {
{
addAll(collection2);
}
};
if (treeSetA.containsAll(treeSetB) && treeSetB.containsAll(treeSetA))
return true;
else
return false;
}
}
код для ClassA и класса, который реализует компаратор.
class ClassA {
String name;
int id;
String desc;
public ClassA(String name, int id, String desc) {
this.name = name;
this.id = id;
this.desc = desc;
}
int getId() {
return id;
}
}
&
class CompareID implements Comparator<ClassA> {
int i = 0;
@Override
public int compare(ClassA o1, ClassA o2) {
System.out.println(i++); // Counter variable
if (o1.getId() > o2.getId())
return 1;
else if (o1.getId() < o2.getId())
return -1;
else
return 0;
}
}
выход (кросс проверяется в отладчик также)
0
1
2
3
0 // why started from 0 again ?
1
2
3
4
5
6
7
8
4 // What the hell !!!
5
6
7
8
Equal set of tree // is that correct output ?
, что вы ожидали бы там, чтобы сделать это не выглядеть странно? – SomeJavaGuy
У меня нет подсказки, почему он начинается с 4 после 8, также 0 после 3. – user3042916
Опять же, что вы ожидаете увидеть? Как то, что вы видите, отличается от того, что вы ожидаете увидеть? Хорошие детали. – jwpfox