重寫hashCode方法

hashCode方法在Object類中定義如下:
public native int hashCode();
說明是一個本地方法,其實現和本地機器相關。我們可以在自己的類中覆蓋hashCode方法。
下面String類中重寫的hashCode方法:
public int hashCode() { 
    int h = hash; 
    if (h == 0) { 
        int off = offset; 
        char val[] = value; 
        int len = count; 

        for (int i = 0; i < len; i++) { 
             h = 31*h + val[off++]; 
        } 
        hash = h; 
    } 
    return h; 


下面是重寫hashCode方法的例子:
public class Action
{
     private String deviceMacAddr;
     private String attribute;
     private String operation;
     private String value;

@Override
     public int hashCode()
     {
         final int prime = 31;
         int result = 1;
         result = prime * result + ((attribute == null) ? 0 : attribute.hashCode());
         result = prime * result + ((deviceMacAddr == null) ? 0 : deviceMacAddr.hashCode());
         result = prime * result + ((operation == null) ? 0 : operation.hashCode());
         result = prime * result + ((value == null) ? 0 : value.hashCode());
         return result;
    }
}
幾點說明:
1. equals()相等的兩個對象,hashcode()一定相等; 
2. equals()不相等的兩個對象,卻並不能證明他們的hashcode()不相等。換句話說,equals()方法不相等的兩個對象,hashcode()有可能相等。 
3. hashcode()不等,一定能推出equals()也不等;hashcode()相等,equals()可能相等,也可能不等。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章