C # Java equivalent Sorted list

Possible duplicate:
sorted collection in java

I was wondering if Java has its own version of the Sorted List, or if I need to create my own. I want the list to automatically update if something is deleted. For example, if I delete something from the very beginning of the list or even in the middle, I want everything that was behind it to move up in the list and the remaining empty space to be deleted.

+4
source share
3 answers

Well, Java has quite a few implementations of lists that are smarter than arrays, although it doesn't look like you really want a sorted list from your description.

ArrayList or LinkedList will do what you want by inserting or removing elements:

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

Do you really need a sorted list or just something higher than an array?

+3
source

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

However, what you described is more like an ArrayList , which is similar to the .NET List<T> .

+4
source

java.util.PriorityQueue

Unlimited priority queue based on priority heap. The elements of the priority queue are ordered according to their natural order or using the comparator provided during the construction of the queue, depending on which constructor is used. The priority queue does not allow null elements. A priority ordering based on natural ordering also prevents the insertion of disparate objects (this may lead to a ClassCastException).

This is basically a heap that allows you to read from the front in order and allows you to remove from the middle through Iterator.remove , but the iterator does not iterate in any particular order.

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

+3
source

Source: https://habr.com/ru/post/1347376/


All Articles