How to replace a specific element in a LinkedHashSet?

4.4k views Asked by At

With an ArrayList I would do something like

myList.set(myList.indexOf(oldItemNumber), newItemNumber);

Is there an easy way to achieve this for LinkedHashSet?

5

There are 5 answers

1
Tim B On BEST ANSWER

The question is meaningless for a Set. A new object added to the Set either equals an existing one (in which case nothing happens) or it doesn't (in which case it is added at the end).

There is no way to insert objects at specific locations without removing and re-adding everything.

You may want to look at TreeSet which allows you to keep an ordered set that will remain ordered by the provided comparator as you add and remove objects.

3
Juvanis On

Just use the put() method. It will update that specific entry.

2
Deepak On

use map.put(key ,value) if you will use same key it will replace previous value

1
Tim B On

From the documentation of LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

So you can simply put() the new value in and it will keep it's current location in the ordering. If you want to add it to the end then remove the old value and then add the new one.

0
LanDenLabs On

I solved this problem where a LinkedHashSet member object has a hash code which computes a value on only part of the object (ex its Name field). Yes this is unconventional but I also had a matching equals() method. Two different objects can have the same hash code and appear equal but internally they have some different values.

An example would be a database record which has key which has to be unique. You need to replace the record with a new set of values, so you find and replace the record with the matching key with new values.

// Rebuild Linked Hash Set in original order with new element.
ArrayList<Item> newSet = new ArrayList<>(oldSet);
newSet.add(newSet.indexOf(oldItem), newItem);
oldSet.clear();
oldSet.addAll(newSet);

The arrayList will have the old values in the same order and the new item will get added in front of the old. No need to remove the duplicate. When added to the old HashSet (LinkedHashSet) it only keeps the first occurrence of any duplicate hash codes.