TreeSet(Collection<? extends E> c)构造函数定义为:
Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.
是否可以在语法上强制 E
在Collection<? extends E>
实现Comparable
?在上面的 JavaDoc 中,此检查推迟到执行时间...
最佳答案
是的,但不适用于构造函数;您必须公开一个工厂方法,该方法可以对集合类型施加超出整个类施加的约束。例如,他们可以写
public class TreeSet<E> { ...
public static <E extends Comparable<? super E>> TreeSet<E>
create(Collection<? extends E> collection) {
TreeSet<E> set = new TreeSet<E>();
set.addAll(collection);
return set;
}
...
}
关于java - 可以通过 Java 泛型类型系统强制执行自然排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41773635/