How important is it to implement the hashCode method in Java?

25
  • How important is it to implement the hashCode method in Java?

  • How does the hashCode method differentiate two objects?

  • asked by anonymous 31.03.2014 / 16:03

    1 answer

    25

    hashCode() is used for objects of type Collection organize your elements, for example, in an academy that has the student records separated by the first letter of the student's name, those folders A , B , C , ... inside a folder or portal, documents (okay, today is everything via systems, but everyone remembers the paper chips, do not you remember?).

    This makes it easy to find the name of a student in the middle of so many. If you want to find the student John you first pick up everyone who starts with the letter J and from there you search within the possibilities the exact name you need, the registration number, etc., rather than looking among all the students enrolled in the academy.

    Searching for the tab with the first letter of the student's name would be equivalent to the search for hashCode() , searching for the exact name of the student would be equivalent to the search for equals() .

    Here's an example, imagine the Product class below already with hashCode() and equals() implemented:

    public class Produto {
        int idProduto;
        String nomeProduto;
    
        public Produto(int idProduto, String nomeProduto) {
            super();
            this.idProduto = idProduto;
            this.nomeProduto = nomeProduto;
        }
    
        //getters and setters aqui!
    
        @Override
        public int hashCode() {
            //deve ser o mesmo resultado para um mesmo objeto, não pode ser aleatório
            return this.idProduto;
        }
    
        @Override
        public boolean equals(Object obj) {
            //se nao forem objetos da mesma classe sao objetos diferentes
            if(!(obj instanceof Produto)) return false; 
    
            //se forem o mesmo objeto, retorna true
            if(obj == this) return true;
    
            // aqui o cast é seguro por causa do teste feito acima
            Produto produto = (Produto) obj; 
    
            //aqui você compara a seu gosto, o ideal é comparar atributo por atributo
            return this.idProduto == produto.getIdProduto() &&
                    this.nomeProduto.equals(produto.getNomeProduto());
        }   
    }
    

    Now suppose we want to create a Collection object, say a HashSet<>() , and store a list of several objects of type Product:

    public class TesteCollection {
        public static void main(String[] args) {
            Set<Produto> produtos = new HashSet<>();
    
            produtos.add(new Produto(1, "Caderno 96 folhas"));
            produtos.add(new Produto(2, "Lapis 2B"));
            produtos.add(new Produto(3, "Borracha"));
            produtos.add(new Produto(4, "Estojo"));
    
            //em algum ponto do programa que você não possui mais
            //a variável de referência para o objeto que você quer
            //encontrar na lista
            Produto p = new Produto(4, "Estojo");
            System.out.println(produtos.contains(p));
        }
    }
    

    In the contains() method, the set needs to search for the product in its product collection, the method returns true or false whether or not it has been found. You call the method by passing a reference variable of type Product and ask if that product is contained in the set, however, since you had to create a new object (note the word new on the top line) this new object is NOT in the set, what you have at that point is a new object, and there may be an object within the set that has the same attributes identifiers (the attributes that you considered relevant and placed within your equals() ), usually this is the that we need, a new object with identical identifier attributes and not the actual object within the collection.

    In% with%, the list first takes all the objects within its collection that have the same contains() , then it searches of all found objects which is the same according to the implementation of hashCode() , in the example above , the return is equals() .

    EDIT

      

    HashCode groups objects according to a precondition, such as the student sheet that groups students by letter?

    Yes, collections group objects that have exactly the same true .

      

    Is it used to compare objects within collections?

    It is not used to compare, but it is used to find objects within the collection, because first look for the group to which the object belongs then look for the object by comparing objects, then if it is not possible finding the group will not be able to find the object. The comparison of objects is done through the result of the hashCode() method.

    The correct implementation of equals() is one that always returns the same value when called to the same object, according to contract hashCode () .

    In addition to implementing correctly you should always try to implement hashCode() efficiently. When implemented in an efficient way it helps collections to eliminate multiple objects that are certainly not what is being searched for, ie, it discards groups of objects that do not produce a certain hashCode() .

    An example of implementation of hashCode() inefficient:

    public int hashCode() { return 42; } //é válido, porém ineficiente
    

    It is inefficient because all objects will be in the same group, making it difficult to work collectively when searching for an object. The most efficient way to implement this is if you are able to ensure a way to generate% s of unique% s for each object, so you are ensuring that there is only one object per group of hashCode() within the collection.

        
    31.03.2014 / 16:47