Reputation: 11
I have a HashSet and a HashMap of Class. How to modify the class variable? so I have a class Data, then I create HashSet of Data and HashMap of Data then do population. later, I would like to modify the value name and number.
class Data {
private String name;
private int number;
public Data(String name, int number) {
this.name = name;
this.number = number;
}
public String toString() {
return name + ":" + number;
}
public void modifyNumber (int i) {
this.number+=i;
} }
public class Main {
public static void main(String[] args) {
Set<Data> dataSet = new LinkedHashSet<Data>();
Map<String, Data> map = new LinkedHashMap<String, Data>();
// I do the dataSet and map population, then do something else
//now I want to modify the value of name and number for HashSet and HashMap of Class
}}
Upvotes: 0
Views: 288
Reputation: 2006
To work inside a HashSet
, the Data
class should override equals
and hashcode
methods.
Otherwise the set will not operate as expected.
In your implementation you failed to override those methods.
But when you do that, you cannot change the attribute values which are used in equals
and hashcode
. This may cause the object to be in the wrong hash bucket for its new value.
You can change the other attributes.
hashset.iterator.next().setXXX();
Upvotes: 1
Reputation: 8849
create the getter
and setter
method for Data
class
then get the object and change it
public void setName(String name){
this.name=name;
}
map.get("id").setName("newname");
map.get("id").modifyNumber(number);
Upvotes: 1