I have a HashSet <Region>. I want to determine whether the current region belongs to what lies in the set. I do it like this:

HashSet<Region> reg = new HashSet<Region>(); Region r1 = new Region(); r1.setValue(Region.Regions.region1); Region r2 = new Region(); r2.setValue(Region.Regions.region2); reg.add(r1); reg.add(r2); Region r = new Region(); r.setValue(Region.Regions.region1); out.println(reg.contains(r)); 

For some reason it gives false. What is the problem?

This is how the Region class is implemented.

 public class Region { private Regions value; public Regions getValue() { return value; } public void setValue(Regions value) { this.value = value; } 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; } } 

}

    1 answer 1

    The Region class must override the equals () method, which inherits from the Object class. That it is used to compare objects when searching.

    Inside it objects should be compared by field values ​​or some other properties (in your case, it’s enough to compare the value, I think)

    • 2
      and hashCode () to complete the picture =) - Gorets
    • and it is worth adding that Set - by definition cannot contain duplicates - Gorets
    • in this case, hashCode is more than required - Anton Feoktistov
    • and how to override equals ()? - Stas0n
    • if you write in the eclipse, you can select the context menu item source -> override / implements (like the menu item) and select the desired method of the Object class or with pens, if you are talking about the implementation itself, check that they are of the same type, and then follow the hashcode ( which would also be better to override) - rasmisha