013
013

Reputation: 175

How to evaluate list in java equality of two object

I have a arrayList and i want use contains(Thing o) method to check equality of this two object and I override the equals() method in Thing class but this is not work when I call contains method! this is my thing class:

public class Thing{

private int id;

//getter setter

@Override
public boolean equals(Object o) {
    if(!(o instanceof Thing))
        return false;
    if(id == ((Thing)o).getId())
        return true;
    return false;
}
}

is it necessary to override the hashCode() method too? if yes how to override it?

Upvotes: 3

Views: 276

Answers (3)

Aish-Rad
Aish-Rad

Reputation: 71

Yes, it is essential to override hashCode() whenever u override equals :

  • If you do not overrode HashCode(), the default behaviour from the "Object" class is to give each object a unique hashCode.

  • This unique hashCode would mean two different object instances unless
    you override the hashCode() to give the same value.

    public int hashCode(){ return this.id; }

you dont have to write this manually when you are using Eclipse.:) RightCLick on the java file opened -->Source-->Generate HashCode() and equals()

Upvotes: 2

My-Name-Is
My-Name-Is

Reputation: 4942

In case you override equals() you should always override hashCode() too. By using Eclipse IDE you simply can generate that methods for you. Menu -> Source -> Generate hashCode() and equals()

Upvotes: 1

Joni
Joni

Reputation: 111239

You should override hashCode. The ArrayList class doesn't use the hashCode method so it's not necessary now, but if at any point you are going to use your class with HashMap, HashSet, or any other collection that does use hashCode, the program will break because hashCode and equals are not consistent.

A simple implementation of hashCode for this case could be:

public int hashCode() {
    return id;
}

Upvotes: 4

Related Questions