Is there a way to update an item in a hashset. I have a hashset of users and I would like to update the connectionId field.
Should I do the following:
The purpose of the contains method is to check if an element is present in a given HashSet. It returns true if the element is found, otherwise false. Whenever an object is passed to this method, the hash value gets calculated. Then, the corresponding bucket location gets resolved and traversed.
1 Answer. Show activity on this post. Generally, collections with some kind of internal structure don't watch for changes in their elements, and their structure will be destroyed if you modify the elements (in ways that change the property that the structure is based on). This holds for TreeSet as well.
In order to add an element to the HashSet, we can use the add() method. However, the insertion order is not retained in the HashSet. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored.
As long as you are not modifying the hash code of the item you can update the item without removing it. If your modifications change the hash code you will need to remove it and add again to keep the hash codes up to date.
The main purpose of Hashset is that: It holds a set of objects in a way that allows you to easily and quickly determine whether an object is already in the set or not.
To achieve that purpose it sacrificed some parts of the ability that allows you to manipulate its content.
You could consider using different type of collection or workaround this problem by using a Dictionary with keys and values of the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With