开发者

Java equivalent of C# Sorted List [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

sorted collection in java

I was wondering if Java has its own version of Sorted List, or if I need to create my own. I want the list to automatically update itself if something is removed. For example, if I remove something from the start of the list, or even in the middle, I want everything behind it to move up 开发者_如何学Cin the list, and the remaining null value space to be removed.


If you're really after the equivalent of a .NET SortedList, which is actually a map ordered by its keys, then the closest equivalent is probably TreeMap. That's actually more like SortedDictionary than SortedList, given that it's a tree rather than just a list, but it's probably the closest available option.

However, what you've described is more like ArrayList, which is similar to .NET's List<T>.


Well, Java has quite a few list implementations that are smarter than arrays, though it doens't sound like you really want a sorted list from your description.

An ArrayList or LinkedList will do what you want as far as inserting or removing elements:

public Object remove(int index) - Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

Do you really want a sorted list, or just something higher-level than an array?


java.util.PriorityQueue

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).

This is basically a heap that allows reading from the front in order, and allows removal from the middle via Iterator.remove but the iterator does not iterate in any particular order.

If you want something that you can iterate over in order, and don't need dupes, then a TreeSet is your best bet. If you need dupes, then look at a library like Apache common's TreeBag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜