Java HashSet contains Object
Solution 1
In your situation, the only way to tell if a particular instance of an object is contained in the HashSet, is to iterate the contents of the HashSet, and compare the object identities ( using the == operator instead of the equals() method).
Something like:
boolean isObjectInSet(Object object, Set<? extends Object> set) {
boolean result = false;
for(Object o : set) {
if(o == object) {
result = true;
break;
}
}
return result;
}
Solution 2
The way to check if objects are the same object is by comparing them with == to see that the object references are equal.
Kind Greetings, Frank
stonar96
Updated on June 04, 2022Comments
-
stonar96 almost 2 years
I made my own class with an overridden equals method which just checks, if the names (attributes in the class) are equal. Now I store some instances of that class in a HashSet so that there are no instances with the same names in the HashSet.
My Question: How is it possible to check if the HashSet contains such an object. .contains() wont work in that case, because it works with the .equals() method. I want to check if it is really the same object.
edit:
package testprogram; import java.util.HashSet; import java.util.Set; public class Example { private static final Set<Example> set = new HashSet<Example>(); private final String name; private int example; public Example(String name, int example) { this.name = name; this.example = example; set.add(this); } public boolean isThisInList() { return set.contains(this); //will return true if this is just equal to any instance in the list //but it should not //it should return true if the object is really in the list } public boolean remove() { return set.remove(this); } //Override equals and hashCode }
Sorry, my english skills are not very well. Please feel free to ask again if you don't understand what I mean.