A Comparator
for aTreeSet
用于排序,而不是用于抛出 CCE。由于您的比较器旨在返回1
所有内容,这意味着排序不正确。
这就是您的输出未排序的原因。
请务必阅读TreeSet
.
/**
* Constructs a new, empty tree set, sorted according to the specified
* comparator. All elements inserted into the set must be <i>mutually
* comparable</i> by the specified comparator: {@code comparator.compare(e1,
* e2)} must not throw a {@code ClassCastException} for any elements
* {@code e1} and {@code e2} in the set. If the user attempts to add
* an element to the set that violates this constraint, the
* {@code add} call will throw a {@code ClassCastException}.
*
* @param comparator the comparator that will be used to order this set.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the elements will be used.
*/
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
它明确指出,如果您尝试添加除Comparator
设计对象之外的任何其他元素,它会抛出ClassCastException
. 如果您不使用泛型,则可以通过尝试添加String
. 但是,如果您确实使用泛型,这将只是一个编译时问题。
同时,您应该始终如一地使用泛型。
class NumberComparator<C> implements Comparator<C> {
public int compare(C o1, C o2) {
return 1; // change this logic
}
}
Set<Number> set = new TreeSet<>(new NumberComparator<Number>());