How to efficiently implement hashCode () for a single linked node list in Java?

Eclipse implements a function hashCode()for a single Node class as follows:

class Node{
    int val;
    Node next;

    public Node(int val){
        this.val = val;
        next = null;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((next == null) ? 0 : next.hashCode());
        result = prime * result + val;
        return result;
    }
}

Now hashCode()for Node it depends on the hash code of subsequent nodes.

Thus, each call hashCode()will take a weighted linear time in the length of the linked list. Thus, use HashSet<Node>will become impracticable.

One way around this is to cache the value hashCodein the variable (call the hash) so that it is evaluated only once. But even in this case, the hash will become invalid after changing any Node value. And again, linear time is required to change the hashCodenodes that follow the current node.

, Node?

+4
2

, : LinkedList do? , , LinkedList.Node hashCode() equals() ( ).

? , , . - , -. .

:

, HashSet<Node> .

, . . ( ), HashSet.

LinkedList.Node . - , ( ), , LinkedList - . AbstractList ( ).

OpenJDK, , Oracle JDKs

+3

, . , , . , , 5 . , . , , , , 1, - , . int, . , , .

, (, ) . , , , .; -)

: java.util.HashSet( , HashMap, ) , . , , HashSet, , , .

+1

Source: https://habr.com/ru/post/1536458/


All Articles