How to set the equality comparison between two objects present in an ArrayList?

6

How can I set the equality comparison behavior between two objects whose class is defined by me that are stored in an object of type ArrayList?

ColorName

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

    
asked by anonymous 03.04.2017 / 02:55

3 answers

7

The comparison between two objects of the same class is done by inheriting from the Object class, which performs a comparison by reference to the positions in memory, so verde1 is different from verde2 when compared. For a more accurate comparison, you will need to override the .equal(Object objecto) method of the parent class Object to define the comparison process.

ColorName

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 be displayed:

There is equality

There is equality

There is equality

    
05.04.2017 / 15:03
2

Comparing objects in Java

Note that we are talking about comparing whether two objects are the same or not!

For this there exist two fundamental methods called equals (...) and hashCode () that are declared in class java.lang.Object by default and are part from the core Java library.

You should implement these two methods in your classes that need to be compared !

The equals() method is used to compare if one object is the same as the other.

The hashCode() method is used to generate an ID number corresponding to the object.

Most of the standard Java language classes use these methods to insert and capture objects in a list, as well as to avoid duplication of objects such as HashSet.

The default implementation within the java.lang.Object object uses the equals method to compare the memory address between objects, and the method returns "true" if both objects refer to / 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  Overwrite these methods to compare its contents, to return "true" if two objects have the same string.

Some rules are recommended in implementation

  • Reflection : Objects must be equal to themselves; o.equals(o) == true

  • If the object "a" is equal to the object "b" (a.equals(b)); Then "b" must equal "a".

    li>
  • Transition : If a.equals(b) == true and b.equals(c) == true then c.equals(a) should be true.

  • Consistency
  • Comparison with Null : Comparison with a null object (null) numca should return equals() and should be treated as false; a.equals (null) == false

Relationship contract between equals () and hashCode ()

  • If two objects are equal by the NullPointerException method then the result of the equals() method should be the same.

  • If two objects are not equal by the hashCode() method then the result of equals() can be the same or not.

Step-by-step to override the equals () method

  • Validate using hashCode() , if equal return true

  • Validate if null, if null return false

  • Validate if the object is of the same type using this , if not, return false

  • Try casting the object

  • Compare object attributes starting with numeric values. If they are not the same return false

  • OBS: Do not confuse this comparison with the comparison of magnitude of the values of an object; if one value is smaller or larger than the other, for example, in this case we would have to address the implementation of the Comparable and Comparator interfaces of 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

    06.04.2017 / 23:29
    0

    First you should understand how java does comparison between two variables.

    For primitive type variables such as short, int, float, double, long, char, byte, (basically all types that begin with lowercase letters) one must use == to compare two variables.

    For variables of class types like Object, String, or any class you create or some API you should use the equals () method, as good programming practice all class created must have the equals () When using == for these type the java will compare if the two variables are in the same place in memory or referencing the same object in memory.

    But classes like Integer, Float, Double, Long, 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
    

    But if the variable of n1 was null, java would throw a NullPointerException with the expression n1 == n3.

    For your code to work correctly follow the example below.

    ColorName

    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");
        }
    

    Further reading.

    link

    link

    link

        
    05.04.2017 / 22:07