What data structure is used to save a unique list with insertion order unchanged

I need to add objects to the list (with the semantics of List ), keeping all the objects in the list unique. I figured that LinkedHashSet would do, but the re-insert clause violates this:

 LinkedHashSet<String>list = new LinkedHashSet<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("a"); list.add("a"); System.out.println (list); 

The conclusion from the above: [a, b, c] , not [b, c, a] , as I would like.

Is there such a data structure in Java that handles this case?

+4
source share
3 answers

to try

  Set<String> set = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>(16, 0.75f, true)); set.add("a"); set.add("b"); set.add("c"); set.add("a"); set.add("a"); System.out.println(set); 

Output

 [b, c, a] 
+7
source

I don't think there is some data structure that does what you want, as it seems a little strange. I suggest you create a wrapper around a LinkedHashSet that scratches an element when you try to reinsert it, and then reinserts it.

+3
source

In fact, there is a boxless data structure provided by the JDK libraries. If you look at the LinkedHashMap constructor:

 /** * Constructs an empty <tt>LinkedHashMap</tt> instance with the * specified initial capacity, load factor and ordering mode. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @param accessOrder the ordering mode - <tt>true</tt> for * access-order, <tt>false</tt> for insertion-order * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder; } 

there is an additional parameter accessOrder . Based on this, the newly added object will be moved to the end of the list ( accessOrder - true ) or will remain in the same place ( accessOrder - false ).

To create a Set with these characteristics, you will need to use this factory method from java.util.Collections : newSetFromMap(LinkedHashMap(initialCapacity, loadFactor, accessOrder))

Keep in mind that the accessOrder property accessOrder responsible for all interactions with this element - if you call get on the HashMap , it will also reorder (which shouldn’t affect you, since the Set interface does not provide a get method for the wrapped HashMap , just saying )

+2
source

All Articles