Skip to content
Advertisement

How to find an object in a Set of custom objects

The code below contains a Set of CustomObjects. I am trying to search an object in it.

I’ve overridden equals() method to match it with a specific field, am not able to understand why is it not able to find it.

“XXtNot FoundtXX”

is getting printed instead of

“Found!!”

import java.util.HashSet; import java.util.Set;

public class TestEquals {

  private static Set<CustomObject> setCustomObjects;    

  public static void main(String[] args){
    setCustomObjects = new HashSet<CustomObject>();

    setCustomObjects.add(new CustomObject(2, "asas"));
    setCustomObjects.add(new CustomObject(3, "gdhdf"));
    setCustomObjects.add(new CustomObject(4, "bnbv"));
    setCustomObjects.add(new CustomObject(5, "ljhj"));

    AnotherObject anObj = new AnotherObject(3, 4);

    if(setCustomObjects.contains(anObj)){
        System.out.println("Found!!");
    }else{
        System.out.println("XXtNot FoundtXX");
    }
  }
}


class CustomObject {

  public CustomObject(int test, String name) {
    this.test = test;
    this.name = name;
  }

  private int test;
  private String name;

  @Override
  public boolean equals(Object obj) {
    if(obj instanceof AnotherObject){
        AnotherObject temp = (AnotherObject)obj;
        System.out.println("test" + temp.getOtherTest());
        return this.test == temp.getOtherTest();
    }
    return true;
  }

  @Override
  public int hashCode() {
    int hash = 22;
    hash = 32 * hash + this.test;
    return hash;
  }

}


class AnotherObject {

  public AnotherObject(int otherTest, double test2) {
    this.otherTest = otherTest;
    this.test2 = test2;
  }

  private int otherTest;
  private double test2;

  public int getOtherTest() {
    return otherTest;
  }
  public void setOtherTest(int otherTest) {
    this.otherTest = otherTest;
  }
}

Advertisement

Answer

You haven’t overridden equals and hashCode in AnotherObject. Do this and you should get what you’re expecting.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement