-3

I have: - MyClass with hashCode() overwritten - I'll try to avoid adding a second instance of MyClass with the same content to an List using the contains() method of the List.

How can I achive this ? I thought this is done by just overriding the hashCode() method ?

I guess code says more then words

public class TestClass {

    public static void main(String[] args){

        MyClass myclass1 = new MyClass(2);
        MyClass myclass2 = new MyClass(2);

        List<MyClass> myclasses = new ArrayList<MyClass>();
        myclasses.add(myclass1);
        if(!myclasses.contains(myclass2)){
            myclasses.add(myclass2);
            System.out.println("I'll add ...");
        }

        System.out.println(myclasses.size());
    }
}

public class MyClass {

    int id = -1;
    String something = "";

    public MyClass(int idparam){
        this.id = idparam;
    }

    @Override
    public int hashCode() {
        return id;
    }

}

Updated Class:

public boolean equals(MyClass secondmyclass) {
    return secondmyclass.id == this.id;
}
4
  • 2
    You need equals(). Commented Nov 15, 2017 at 17:25
  • I tried that too. I just updated the code above. But still it doesn't work. Can you please review the code ? (Overriding is not possible, I just added equals without annotation @override) Commented Nov 15, 2017 at 17:30
  • equals is defined with an Object parameter. You're currently overloading the method. Commented Nov 15, 2017 at 17:33
  • Ok. I see. Thanks a lot. Always tried with the Class Type. Thanks. Commented Nov 15, 2017 at 17:36

1 Answer 1

0

You have to override equals and hashcode methods. The object is not contained in the list as is not equal to any instance in the list, even if it generates same hash code.

@Override
public boolean equals(Object obj) {
    boolean eq = false;
    if (obj != null && obj instanceof YOURCLASS) {
        eq = this.getId().equals((YOUCLASS)obj.getId());
    }
}

Equals method should look like this. YOURCLASS is the name of the bean added to the list. You have to compare the key fields after verifying the obj instance is not null and is of the same type of the original instance.

In your example YOURCLASS is MyClass and the comparison inside equals should be with == instead of equals, as you are not using int insteand of Integer for the field.

Sign up to request clarification or add additional context in comments.

1 Comment

How do I have to implement the equal mehtod ? I updated the code. Can you review, because it still doesn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.