Is there a LinkedHashSet / Map equivalent, with order preserved for inserted duplicates?

489 views Asked by At

I was wondering two things.

1) What does a HashSet do with an added duplicate value? I believe it replaces the value? If that is the case, what about for a LinkedHashSet? I'm pretty sure it doesn't change the order, so does it still replace the value? (Why would it?)

2) What if I wanted to use an ordered collection that doesn't allow duplicates, but does replace an existing value with it's duplicate, thus re-ordering the position? Ie. It would be like a LinkedHashSet, except duplicate values added would be replaced and their positions updated. Is there a collection that might do this? Or will I have to write my own? I don't want to have to write my own!

1

There are 1 answers

0
Dima On BEST ANSWER

1) Adding a duplicate into a Set does not do anything (it returns false immediately, and contents of the Set are not affected), regardless of particular implementation, be it a HashSet, a TreeSet or a LinkedHashSet.

2) Check out LinkedHashMap, it is, probably, the closest to what you want. It has a boolean argument to the constructor, that lets you specify whether you want it to use "insertion-order" (false) or "access-order". The former is the same as LinkedHashSet, the latter will "bump" the key up if you re-insert it, and also if you look it up:

Map<String, Integer> map = new LinkedHashMap(10, 0.75, true);
map.put("foo", 1); map.put("bar", 2);
System.out.println(map.keySet().iterator().next()); // prints "bar"
map.put("foo", 1); 
System.out.println(map.keySet().iterator().next()); // prints "foo"
map.get("bar");
System.out.println(map.keySet().iterator().next()); // prints "bar"