【发布时间】:2014-03-23 21:05:51
【问题描述】:
我在几个 java API 中观察到这一点,例如:TreeSet、PriorityQueue 等,没有构造函数同时采用 Collection 和 Comparator。相反,我们必须选择一个采用 Comparator 的构造函数并使用 addAll 传入 Collection
例如:
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.
TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
这只是一个不足/不灵活的 API 吗?或者这是我不知道的将它们分开的真正原因?
换句话说,我想问为什么我们没有像TreeSet(Collection<? extends E> c, Comparator<? super E> comparator) 这样的构造函数?
【问题讨论】:
-
第三个选项是
TreeSet(SortedSet<E>),它使用与源集相同的排序顺序。 -
你能澄清你在问什么。你想要一个像 TreeSet(Collection extends E> c, Comparator super E>comparator) 这样的构造函数吗??
-
你能解释一下为什么你想要这样一个构造函数吗?虽然没有人争辩说拥有一个会很方便,但如果您可以更准确地描述您的具体情况,也许我们可以建议您的代码保持清晰和干净的方法。
标签: java api sorting collections