最近用Java寫程式,發現這兩個函數掌握的不好,所以專門看書研究了好久。
“contains方法被重新定義,用來快速查看是否某個元素已經出現在集中。他只在某個桶中尋找元素,而不必查看集合中的所有元素。”——《Core Java》
當比較一個集合(Set)中是否含有一個對象的時候,調用contains函數,而contains函數又會調用hashCode快速縮小判斷範圍,然後再調用equals判斷是否含有該對象。
注意:hashCode的值僅代表該對象在散列表中桶的位置,散列表用鏈表數組實現,每個鏈表都在一個相同的桶中。所以說,如果hashCode傳回值之前沒有,那麼該對象一定不再集合中,如果hashCode返回之前存在,那再根據equals判斷。
如下程式:
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);//調用hashCode,發現之前沒有,新對象open.add(node2);//調用hashCode,發現之前有,再調用equals,發現傳回值一樣,故判斷該對像之前存在,拒絕加入Node node3 = new Node(12);System.out.println(open.contains(node3));//調用hashCode,發現之前有,再調用equals,發現傳回值一樣,故返回true表示存在System.out.println(node1.equals(node3));//僅僅調用equals方法}static HashSet<Node> open = new HashSet<Node>();}class Node{public Node(int a){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;}/*輸出: * hashCode * hashCode * equals * hashCode * equals * true * equals * true */