在Java中有SortedSet和SortedMap接口。两者都属于Java Collections框架,并提供了一种访问元素的排序方式。
然而,在我的理解中,Java中没有SortedList。您可以使用java.util.Collections.sort()对列表进行排序。
知道它为什么是这样设计的吗?
在Java中有SortedSet和SortedMap接口。两者都属于Java Collections框架,并提供了一种访问元素的排序方式。
然而,在我的理解中,Java中没有SortedList。您可以使用java.util.Collections.sort()对列表进行排序。
知道它为什么是这样设计的吗?
当前回答
如果你正在寻找一种方法来排序元素,但也能够以一种有效的方式通过索引访问它们,你可以做以下事情:
使用随机访问列表进行存储(例如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);
}
}
(在这个答案中可以看到更完整的实现)
其他回答
因为List的概念与自动排序集合的概念是不兼容的。List的意义在于调用List之后。添加(7,elem),调用list.get(7)将返回elem。在自动排序的列表中,元素可以位于任意位置。
我们有Collections.sort(arr)方法,它可以帮助对ArrayList arr进行排序。要以desc方式排序,我们可以使用集合。排序(arr Collections.reverseOrder ())
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
可以这样想:List接口有add(int index, E element), set(int index, E element)这样的方法。约定是,一旦你在X位置添加了一个元素,你就会在那里找到它,除非你在它之前添加或删除元素。
如果任何列表实现都以某种顺序存储元素,而不是基于索引,那么上述列表方法就没有意义了。
对于任何新手来说,从2015年4月开始,Android现在在支持库中有一个SortedList类,专门用于与RecyclerView一起工作。这是关于它的博客文章。