这是代码:
Score alpha = new Score(1,91);
Score beta = new Score(1,81);
Score gamma = new Score(5,85);
NavigableSet<Score> set = new ConcurrentSkipListSet<>(new ScoreComparator());
set.add(beta); set.add(gamma);
assertThat(set.size(),is(equalTo(2)));
assertThat(set.ceiling(alpha), is(equalTo(beta)));
由于以下错误而失败:
Expected: is <Score{userId=1, score=81}>
got: <Score{userId=5, score=85}>
这是比较器:
if(o2.equals(o1)) return 0;
else return o2.getScore() - o1.getScore();
Score 使用 userId
来表示 equals 和 hashCode(hashCode 只是 return userId;
)
我正在做一些错误的假设,我不知道是否使用上限来实现我想要做的事情:检索具有相同 userId 的集合中已经存在的元素(当它存在时)。
最佳答案
Comparator如果 o1 < o2,则应返回负整数。
Returns:
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
因此您应该颠倒顺序:
if (o2.equals(o1))
return 0;
else
return o1.getScore() - o2.getScore();
关于java - NavigableSet 的方法上限不返回带有比较器的预期元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25516294/