Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate list in java equality of two object

Tags:

java

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?

like image 502
013 Avatar asked Dec 12 '25 18:12

013


2 Answers

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;
}
like image 188
Joni Avatar answered Dec 15 '25 08:12

Joni


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()

like image 38
Aish-Rad Avatar answered Dec 15 '25 06:12

Aish-Rad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!