Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashSet contains Object

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.

like image 724
stonar96 Avatar asked Aug 12 '26 19:08

stonar96


2 Answers

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;
}
like image 166
GreyBeardedGeek Avatar answered Aug 15 '26 09:08

GreyBeardedGeek


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

like image 36
Frank Avatar answered Aug 15 '26 09:08

Frank