I recently used Java to write programs and found that these two functions are not well mastered. So I have been studying these functions for a long time.
The contains method is redefined to quickly check whether an element already exists in the set. He only looks for elements in a bucket, without having to view all elements in the set ." -- Core Java
When comparing whether a set contains an object, call the contains function, and the contains function calls hashcode to quickly narrow down the judgment scope, then, call equals to determine whether the object exists.
Note: The hashcode value only represents the location of the object in the bucket in the hash list. The hash list is implemented using the linked list array, and each linked list is in the same bucket. Therefore, if the returned value of hashcode is not set before, the object must not be set. If the returned value of hashcode exists before, it is determined by equals.
The following procedure:
Import Java. util. hashset; public class test {public static void main (string... arg) {node node1 = new node (12); node node2 = new node (12); open. add (node1); // call hashcode. If no, the new object is open. add (node2); // call hashcode and call equals before discovering it. If the returned value is the same, it is determined that the object exists before, reject adding node node3 = new node (12); system. out. println (open. contains (node3); // call hashcode and call equals before it is found. If the returned value is the same, return true to indicate that system exists. out. println (node1.equals (node3); // only call the equals method} static hashset <node> open = new hashset <node> ();} class node {public node (int) {This. A = A;} public Boolean equals (object other) {system. out. println ("equals"); node othernode = (node) Other; If (this. A = othernode. a) Return true; else return false;} public int hashcode () {system. out. println ("hashcode"); return a;} int A = 0;}/* output: * hashcode * equals * true */