Comparison of objects in Java
Note that we are talking between comparing whether two objects are equal or not!
For this there is in the Java language two fundamental methods called equals(...) and hashcode() which are declared in the class java.lang.Object
by default and are part of the Java main library (core).
You should implement these two methods in your classes that need to be compared!
The method equals()
is used to compare if one object is equal to another.
The method hashCode()
is used to generate an identification number corresponding to the object.
A lot of the standard Java language classes use these methods to insert and capture objects in a list, also to avoid duplicate objects like the Hashset case for example.
The default implementation within the object java.lang.Object
uses the equals method to compare the memory address between objects, and the method returns "true" if both objects reference/point to the same memory address.
But the language recommends that these methods be rewritten (override) so that they define some logical or business way to compare the object. For example the class java.lang.String
override these methods to compare
its contents, to return "true" if two objects have the same character string.
Some rules are recommended in the implementation
Reflection: Objects must be equal to themselves; o.equals(o) == true
Symmetry: If object "a" is equal to object "b" (a.equals(b));
So "b" must equal "a".
Transition: If a.equals(b) == true
and b.equals(c) == true
then c.equals(a)
must be true.
Consistency: Multiple consecutive method calls equals()
should always return the same result while no object property is not modified.
Comparison with Null: Comparison with a null object (null) numca must return NullPointerException
and should be treated as false; a.equals(null) == false
Equals() and hashcode relationship agreement()
If two objects are equal by the method equals()
then the result of the method hashCode()
must be the same.
If two objects are not equal by the method equals()
then the result of hashCode()
may or may not be the same.
Step-by-Step to overwrite the equals method()
Valide using this
, if even return true
Validade if null, if null returns false
Validate if the object is of the same type using instanceof
, if it is not, return false
Try to cast the object
Compare object attributes starting with numeric values. If they are not equal return false
NOTE: Do not confuse this comparison with the comparison of the values of an object; if one value is smaller or greater than the other, for example, in this case we would have to address the implementation of the interfaces Comparable and Comparator java.
Example
import java.util.List;
import java.util.ArrayList;
public class Carro {
private String modelo;
private String cor;
private int ano;
public Carro(String modelo, String cor, int ano) {
this.modelo = modelo;
this.cor = cor;
this.ano = ano;
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
Carro c = (Carro) o;
if(ano != c.ano) return false;
if(!modelo.equals(c.modelo)) return false;
return cor.equals(c.cor);
}
@Override
public int hashCode() {
int result = (modelo != null ? modelo.hashCode() : 0);
result = 31 * result + (cor != null ? cor.hashCode() : 0);
result = 31 * result + ano;
return result;
}
@Override
public String toString() {
return modelo + "," + cor + "," + ano;
}
public static void main(String args) {
List<Carro> listaCarros = new ArrayList<Carro>();
listaCarros.add(new Carro("Ford","Azul",2017))
listaCarros.add(new Carro("Honda","Preto",2016))
listaCarros.add(new Carro("Toyota","Branco",2015))
Carro meuCarro = new Carro("Honda","Preto",2016);
for(Carro carro : listaCarros) {
if(carro.equals(meuCarro)) {
System.out.println("O Carro "+carro+" é iqual ao meu!");
}
}
}
}
References
I did not understand what the question is.. how the arraylist determines the equality of which objects exactly?
– Math
I think it would be totally valid if the question were only this and nothing else: "How the Arraylist class determined the equality of objects". If you want, I can try to edit the question for example didactic, to better guide you how to adapt a question to the scope of the site.
– Wallace Maxters
@Wallacemaxters, ready! I just put a context! And I would like to record and reinforce: Java Class Modeling (Class Java Design) is very relevant and the language features should be well publicized and discussed. Thank you for your attention! Our goal is to contribute effectively.
– pss1suporte
@pss1support yes, but this is not a "discussion". To be in the scope of the site, the question must be well defined (a problem well described so that a well described answer may arise). The way it was put, I can not understand the real purpose of the question. Another tip: I think your question does not need references :)
– Wallace Maxters
@pss1support so the real question is how can I define the matching behavior between two objects whose class is defined by me that are stored in an Arraylist object?
– Pedro Ferreira
@Pedroferreira you can enter the chat main to ask more questions with us :)
– Wallace Maxters
@Pedroferreira, that’s right! I’m learning to ask more efficient questions, Wallacemaxters is helping me a lot.
– pss1suporte
I would like to leave an addendum with this reply. I believe I can help you understand the question.
– pss1suporte