私はComparator
のJavaコレクションの機能の詳細を学ぶためのコードを書いています。私はそれぞれに3つの要素を持つ2つのセットを持っています。私は比較したい。 私は下に私のコードを掲示し、カウンタ変数の出力。誰も変数i
がこの奇妙な出力を与える理由を説明できますか?私は流れを理解できませんでした。コンパイラのカウンタ変数の奇妙な出力
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 ?
あなたはそれが奇妙に見えるではない作るためにそこに何を期待するのと同じ出力の両方comperatorsを:コメントは出力を生成したものを含めますか? – SomeJavaGuy
私はなぜそれが4の後に始まり、3の後にも0から始まるのか分からない。 – user3042916
もう一度、あなたは何を見たいと思いますか?あなたが見ているものは、あなたが見たいものとはどのように異なっていますか?ニースの詳細。 – jwpfox