Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Item in Hashset

Tags:

c#

hashset

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.

ScreenGrab of the Hashset

Should I do the following:

  1. retrieve the item, make the necessary updates
  2. remove the item from hashset
  3. add it again
like image 722
Alvindra Dutt Avatar asked Sep 20 '16 03:09

Alvindra Dutt


People also ask

How contains method works in HashSet?

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.

Can you modify the object set in Java?

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.

How to store objects in HashSet?

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.


2 Answers

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.

like image 155
strongbutgood Avatar answered Oct 06 '22 00:10

strongbutgood


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.

like image 27
Cù Đức Hiếu Avatar answered Oct 05 '22 23:10

Cù Đức Hiếu