我试图使用TreeMap计算一个简单的String Pair对象。
我尝试过在树形图中使用这个比较器,但它仍然给出了错误的输出,就像它将对象对象本身进行比较一样:
static class Comp implements Comparator<Pair>
{
public int compare(Pair s1, Pair s2)
{
boolean c1 = s1.word1.equals(s2.word1),
c2 = s1.word2.equals(s2.word2),
c3 = s1.word1.equals(s2.word2),
c4 = s1.word2.equals(s2.word1);
if(c1 && c2 || c3 && c4)
return 0;
else if((!c1 && !c2) || (!c3 && !c4))
return s1.word1.compareTo(s2.word1);
if(!c1)
return s1.word1.compareTo(s2.word1);
else if(!c2)
return s1.word2.compareTo(s2.word2);
else if(!c3)
return s1.word1.compareTo(s2.word2);
else if(!c4)
return s1.word2.compareTo(s2.word1);
else
return s1.word1.compareTo(s2.word1);
}
}
示例输入为:
<"red", "blue"> , <"blue", "red">, <"red", "red">, <"gray","purple">, <"purple","gray">
应输出:
<"gray", "purple", 2>, <"red", "blue", 2> <"red", "red", 1>
相反,我得到:
<"gray", "purple", 1><"red", "blue", 2> <"red", "red", 1><"purple", "gray", 1>
答案 0 :(得分:0)
我不确定您是如何对计数进行编码的,但排序的效果与预期的代码一样。我在下面的代码与您的代码之间看到的唯一区别是Comp
类在我的代码中不是静态的。
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class ComparatorTest {
public ComparatorTest() {
Map<Pair, String> x = new TreeMap<>(new Comp());
x.put(new Pair("red", "blue"), "one");
x.put(new Pair("blue", "red"), "two");
x.put(new Pair("red", "red"), "three");
x.put(new Pair("gray", "purple"), "four");
x.put(new Pair("purple", "gray"), "five");
System.out.println(String.format("Print out Map - %s", x.toString()));
for (Pair pair : x.keySet()) {
System.out.println(String.format("Key value <%s, %s, %s>", pair.word1, pair.word2, x.get(pair)));
}
}
public static void main(String[] args) {
new ComparatorTest();
}
}
class Pair {
String word1 = null;
String word2 = null;
public Pair(String word1, String word2) {
this.word1 = word1;
this.word2 = word2;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair)) { return false; }
Pair that = (Pair)obj;
return ((this.word1.equals(that.word1) && this.word2.equals(that.word2)) || (this.word1.equals(that.word2) && this.word2.equals(that.word1)));
}
@Override
public String toString() {
return String.format("<%s, %s>", word1, word2);
}
}
class Comp implements Comparator<Pair> {
public int compare(Pair s1, Pair s2) {
boolean c1 = s1.word1.equals(s2.word1),
c2 = s1.word2.equals(s2.word2),
c3 = s1.word1.equals(s2.word2),
c4 = s1.word2.equals(s2.word1);
if(c1 && c2 || c3 && c4)
return 0;
else if((!c1 && !c2) || (!c3 && !c4))
return s1.word1.compareTo(s2.word1);
if(!c1)
return s1.word1.compareTo(s2.word1);
else if(!c2)
return s1.word2.compareTo(s2.word2);
else if(!c3)
return s1.word1.compareTo(s2.word2);
else if(!c4)
return s1.word2.compareTo(s2.word1);
else
return s1.word1.compareTo(s2.word1);
}
}
输出
Print out Map - {<gray, purple>=five, <red, blue>=two, <red, red>=three}
Key value <gray, purple, five>
Key value <red, blue, two>
Key value <red, red, three>