How to define the comparison of equality between two objects present in an Arraylist?

Asked

Viewed 1,428 times

6

How can I define the equality comparison behavior between two objects whose class is defined by me that are stored in an Arraylist object?

Java nomecor.

public class NomeCor {
  private String nome;

  public String obterNome() { return nome; }

  public NomeCor(String nome) { this.nome = nome; }

}

In the main method:

    NomeCor verde1 = new NomeCor("verde");
    NomeCor verde2 = new NomeCor("verde");
    ArrayList<NomeCor> lista = new ArrayList<NomeCor>();
    lista.add(verde1);
    lista.add(verde2);
    if (lista.get(0) == lista.get(1)) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }
    if (lista.get(0) == verde1) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }
    if (lista.get(0) == verde2) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }

Console Log:

There is no equality

There is equality

There is no equality

  • I did not understand what the question is.. how the arraylist determines the equality of which objects exactly?

  • 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.

  • @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.

  • @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 :)

  • @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?

  • @Pedroferreira you can enter the chat main to ask more questions with us :)

  • @Pedroferreira, that’s right! I’m learning to ask more efficient questions, Wallacemaxters is helping me a lot.

  • I would like to leave an addendum with this reply. I believe I can help you understand the question.

Show 3 more comments

3 answers

8

The comparison between two objects of the same class is made by inheritance of the Object class, which makes a comparison by reference of the positions in the memory, hence verde1 be different from verde2 when compared. For a more accurate comparison, override the method .equal(Object objecto) of the Object parent class to define the comparison process.

Java nomecor.

public class NomeCor {

  private String nome;

  public String obterNome() { return nome; }

  public NomeCor(String nome) { this.nome = nome; }

  @Override
  public boolean equals(Object objecto) {
    if (objecto == null) return false;
    if (objecto.getClass() != getClass()) return false;
    NomeCor aComparar = (NomeCor) objecto;
    if (!this.nome.equals(aComparar.obterNome()))
        return false;
    else
        return true;  
    }
}

In the main method:

    NomeCor verde1 = new NomeCor("verde");
    NomeCor verde2 = new NomeCor("verde");
    ArrayList<NomeCor> lista = new ArrayList<NomeCor>();
    lista.add(verde1);
    lista.add(verde2);
    if (lista.get(0).equals(lista.get(1))) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }
    if (lista.get(0).equals(verde1)) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }
    if (lista.get(0).equals(verde2)) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }

In the console log, the desired result will appear:

There is equality

There is equality

There is equality

  • I would like to leave an addendum with this reply. I believe I can help in understanding your answer.

2

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

  1. Valide using this, if even return true

  2. Validade if null, if null returns false

  3. Validate if the object is of the same type using instanceof, if it is not, return false

  4. Try to cast the object

  5. 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

  • would like to leave an addendum with this reply. I believe it can help in understanding your answer. The interesting thing about your answer is the addition and contrast with the hashcode method().

  • It would be interesting if you presented a possible implementation of it. That would contribute a lot to the community! And putting a reference would be good.

  • Thanks for the answers! The criterion I considered was to be more complete addressing hashcode(), putting example of code and reference.

1

First you should understand how java compares narrowly two variables.

For primitive type variables such as short, int, float, double, long, char, byte (Basically all types starting with minuscule letter) use == to compare two variables.

For class type variables like Object, String, or any class you create or any API you should use the equals() method, as a good programming practice all class created should have the equals() method superscript, when using == for these type java will compare whether the two variables are in the same place in memory or whether it references the same object in memory.

However Classes like Integer, Float, Double, Long, one can use == to make comparison since one of the variables is of primitive type, for example.

Integer n1 = 1;
Integer n2 = 1;
int n3 = 0;

System.out.println(n1 == n2);//false
System.out.println(n1 == n3);//true
System.out.println(n1.equals(n2));//true

However if the n1 variable were null java would launch a Nullpointerexception with the expression n1 == N3.

For your code to work properly follow the example below.

Java nomecor.

public class NomeCor {

  private String nome;

  public String obterNome() { return nome; }

  public NomeCor(String nome) { this.nome = nome; }

  @Override
  public boolean equals(Object objecto) {
    if (objecto == null) return false;
    if (objecto.getClass() != getClass()) return false;
    NomeCor aComparar = (NomeCor) objecto;

    if(this.nome == null && aComparar.obterNome() != null){
        return false;

    return this.nome.equals(aComparar.obterNome());
}

In the main method:

    NomeCor verde1 = new NomeCor("verde");
    NomeCor verde2 = new NomeCor("verde");
    ArrayList<NomeCor> lista = new ArrayList<NomeCor>();
    lista.add(verde1);
    lista.add(verde2);
    if (lista.get(0).equals(lista.get(1))) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }
    if (lista.get(0).equals(verde1)) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }
    if (lista.get(0).equals(verde2)) {
        System.out.println("Existe igualdade");
    } else {
        System.out.println("Não existe igualdade");
    }

Additional reading.

http://www.devmedia.com.br/forum/comparar-variaveis-ou-equals/564747

https://sergiotaborda.wordpress.com/desenvolvimento-de-software/java/igualdade-em-java/

http://java-i9se.blogspot.com.br/2009/04/equale-em-java-equals-e-hashcode.html

  • 1

    would like to leave an addendum with this reply. I believe I can help you understand your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.