Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an insertion order preserving Set that also implements List?

I'm trying to find an implementation of java.util.List and java.util.Set at the same time in Java. I want this class to allow only unique elements (as Set) and preserve their order (like List). Does it exist in JDK 6?

It's important to have List<T>#add(int, T) so I can insert into a specific position.

like image 842
yegor256 Avatar asked Nov 18 '11 15:11

yegor256


People also ask

Does list preserve the insertion order?

ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.

Does list preserve insertion order Java?

List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order.

Which of these maintains insertion order a list be set?

If we want to maintain the insertion order of the elements, we are supposed to use LinkedHashSet. LinkedHashSet maintains the order in which the elements are inserted.

Which collection can be used for storing data in the same order as it was inserted?

For simple List implementations (simple value list storage), you can use the ArrayList class. For Map (key-value storage), use LinkedHashMap . Both of these implementations will preserve insertion order.


2 Answers

TreeSet is sorted by element order; LinkedHashSet retains insertion order. Hopefully one of those is what you were after.

You've specified that you want to be able to insert at an arbitrary location, I suspect you'll have to write your own - just create a class containing a HashSet<T> and an ArrayList<T>; when adding an item, check whether or not it's in the set before adding it to the list.

Alternatively Apache's commons-collections4 offers ListOrderedSet and SetUniqueList, which behave similarly and should meet the given requirements.

like image 81
Jon Skeet Avatar answered Sep 17 '22 15:09

Jon Skeet


LinkedHashSet is the answer.

Iteration ordering and uniqueness.

http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html

like image 24
Mechkov Avatar answered Sep 20 '22 15:09

Mechkov