在Java中有SortedSet和SortedMap接口。两者都属于Java Collections框架,并提供了一种访问元素的排序方式。
然而,在我的理解中,Java中没有SortedList。您可以使用java.util.Collections.sort()对列表进行排序。
知道它为什么是这样设计的吗?
在Java中有SortedSet和SortedMap接口。两者都属于Java Collections框架,并提供了一种访问元素的排序方式。
然而,在我的理解中,Java中没有SortedList。您可以使用java.util.Collections.sort()对列表进行排序。
知道它为什么是这样设计的吗?
当前回答
因为List的概念与自动排序集合的概念是不兼容的。List的意义在于调用List之后。添加(7,elem),调用list.get(7)将返回elem。在自动排序的列表中,元素可以位于任意位置。
其他回答
List API中的第一行表示它是一个有序集合(也称为序列)。如果您对列表进行排序,则无法维护该顺序,因此Java中没有TreeList。 正如API所说,Java列表的灵感来自序列,并查看序列属性http://en.wikipedia.org/wiki/Sequence_(mathematics)
这并不意味着您不能对列表进行排序,但是Java严格遵守了他的定义,并且默认情况下不提供列表的排序版本。
JavaFX 排序列表
虽然花了一些时间,但Java 8确实有一个排序的List。 http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html
正如您在javadocs中所看到的,它是JavaFX集合的一部分,旨在提供一个ObservableList上的排序视图。
更新:注意,在Java 11中,JavaFX工具包已经移到JDK之外,现在是一个独立的库。JavaFX 11可以作为可下载的SDK或从MavenCentral获得。参见https://openjfx.io
如果你正在寻找一种方法来排序元素,但也能够以一种有效的方式通过索引访问它们,你可以做以下事情:
使用随机访问列表进行存储(例如ArrayList) 确保它总是有序的
然后,要添加或删除元素,可以使用集合。binarySearch获取插入/删除索引。因为您的列表实现了随机访问,所以您可以使用确定的索引有效地修改列表。
例子:
/**
* @deprecated
* Only for demonstration purposes. Implementation is incomplete and does not
* handle invalid arguments.
*/
@Deprecated
public class SortingList<E extends Comparable<E>> {
private ArrayList<E> delegate;
public SortingList() {
delegate = new ArrayList<>();
}
public void add(E e) {
int insertionIndex = Collections.binarySearch(delegate, e);
// < 0 if element is not in the list, see Collections.binarySearch
if (insertionIndex < 0) {
insertionIndex = -(insertionIndex + 1);
}
else {
// Insertion index is index of existing element, to add new element
// behind it increase index
insertionIndex++;
}
delegate.add(insertionIndex, e);
}
public void remove(E e) {
int index = Collections.binarySearch(delegate, e);
delegate.remove(index);
}
public E get(int index) {
return delegate.get(index);
}
}
(在这个答案中可以看到更完整的实现)
因为所有列表都已经按照条目的添加顺序(FIFO顺序)“排序”了,所以可以使用java.util.Collections.sort()使用另一种顺序“使用”它们,包括元素的自然顺序。
编辑:
列表作为数据结构的基础是有趣的是插入项的顺序。
集合没有这个信息。
如果您想通过添加时间来排序,请使用List。如果您想按其他标准排序,请使用SortedSet。
对于任何新手来说,从2015年4月开始,Android现在在支持库中有一个SortedList类,专门用于与RecyclerView一起工作。这是关于它的博客文章。