views:

6458

answers:

6

I'm a beginner in Java. Please suggest which collection(s) can/should be used for maintaining a sorted list in Java. I have tried Map and Set but they weren't what I was looking for.

+10  A: 

TreeMap and TreeSet will give you an iteration over the contents in sorted order. Or you could use an ArrayList and use Collections.sort() to sort it. All those classes are in java.util

Michael Borgwardt
+4  A: 

You want the SortedSet implementations, namely TreeSet.

cletus
Not necessarily; sets cannot have duplicate values. It depends on the OP's requirements.
Zach Langley
+6  A: 

There are a few options. I'd suggest TreeSet if you don't want duplicates and the objects you're inserting are comparable.

You can also use the static methods of the Collections class to do this.

See http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort(java.util.List) and http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeSet.html for more info.

BenM
+5  A: 

If you just want to sort a list, use any kind of List and use Collections.sort(). If you want to make sure elements in the list are unique and always sorted, use a SortedSet.

Guillaume
+4  A: 

If you want to maintain a sorted list which you will frequently modify (i.e. a structure which, in addition to being sorted, allows duplicates and whose elements can be efficiently referenced by index), then use an ArrayList but when you need to insert an element, always use Collections.binarySearch() to determine the index at which you add a given element. The latter method tells you the index you need to insert at to keep your list in sorted order.

Neil Coffey
n inserts will be O(n^2). A TreeSet will give you cleaner code and O(n log n). OTOH, for *infrequent* modification binary search of an array will be faster and use less memory (so less GC overhead).
Tom Hawtin - tackline
To keep the code clean and still allow for duplicates it would be easy enough to create a SortedList class that inserts values in sorted order.
Mr. Shiny and New
+10  A: 

This comes very late, but there is a class in the JDK just for the purpose of having a sorted list. It is named (somewhat out of order with the other Sorted* interfaces) "java.util.PriorityQueue". It can sort either Comparable<?>s or using a Comparator.

The difference with a List sorted using Collections.sort(...) is that this will maintain order at all times, and have good insertion performance by using a heap data structure, where inserting in a sorted ArrayList will be O(n) (i.e., using binary search and move).

Martin Probst
imo this answer deserves more upvotes since it points out the only Collection that has the capability in JDK
nimcap
But unlike a List, there is no random access, right?
Thilo
@Thilo: Right, but since the elements' indexes change with every modification, it is probably not needed anyway
nimcap