I need to implement a HashSet<Region>
. If you simply add 2 identical objects of the Region
class to the hashset (with the same value of the value
), then the hashset will contain both objects, and not one. How to avoid it? How to make it so that no objects are added that are identical in the value
field. And how in such a set to establish the presence or absence of another instance of the class? ( сontain
does not roll).
Here is the Region
class
public class Region { private Regions value; public Regions getValue() { return value; } public void setValue(Regions value) { this.value = value; } @Override public boolean equals(Object obj) { Region otherRegion = (Region) obj; return this.value.equals(otherRegion.getValue()); } static enum Regions { region1("region - 1"), region2("region - 2"), region3("region - 3"), region4("region - 4"); private String value; Regions(String value) { this.value = value; } public String toString() { return value; } }
}
===============================================
HashSet<Region> q = new HashSet<Region>(); Region qwe1 = new Region(); qwe1.setValue(Region.Regions.region1); Region qwe2 = new Region(); qwe2.setValue(Region.Regions.region1); q.add(qwe1); q.add(qwe2); Region qwe3 = new Region(); qwe3.setValue(Region.Regions.region2); out.println(qwe1.equals(qwe2)); out.println(q.size()); out.println(q.contains(qwe3));
And here is your own result:
true 2 false