Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an indexable sorted list in the Java.util package?

I'm looking for a data structure in the java.util package. I need it to meet the following requirements:

  • The number of elements is (theoretically) unbounded.
  • The elements are sorted in an ascending order.
  • You can get the nth element (fast).
  • You can remove the nth element (fast).

I expected to find an indexable skip list, but I didn't. Do they have any data structure which meets the requirements I'v stated?

like image 882
snakile Avatar asked Nov 22 '10 18:11

snakile


People also ask

Is there any sorted list in Java?

Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the java. util. PriorityQueue class.

Is Java Util list ordered?

The Java List interface, java. util. List , represents an ordered sequence of objects.

Is sorted list part of Java collection framework?

The java. Collections. sort() method is also used to sort the linked list, array, queue, and other data structures. If we talk about the working of this method, then the method works on ASCII values.


1 Answers

There is no such container in the Java standard libraries.

When I need a data structure with these properties, I use a List implementation (generally an ArrayList, but it doesn't matter), and I do all the insertions using Collections.binarySearch.

If I had to encapsulate a sorted list as a reusable class, I'd implement the List interface, delegating all methods to a 'standard' List implementation (it can even be passed as a parameter to the constructor). I'd implement every insertion method (add, addAll, set, Iterator's remove) by throwing an exception (UnsupportedOperationException), so that nobody can break the 'always sorted' property. Finally, I'd provide a method insertSorted that would use Collections.binarySearch to do the insertion.

like image 141
barjak Avatar answered Oct 15 '22 13:10

barjak