標籤:內容 tostring 數值 ble als order string div 不同
分析代碼:
public final class LineItemKey implements Serializable {private Integer customerOrder;private int itemId;public LineItemKey() {}public LineItemKey(Integer order, int itemId) {this.setCustomerOrder(order);this.setItemId(itemId);}@Overridepublic int hashCode() {return ((this.getCustomerOrder() == null? 0 : this.getCustomerOrder().hashCode())^ ((int) this.getItemId()));}@Overridepublic boolean equals(Object otherOb) {if (this == otherOb) {return true;}if (!(otherOb instanceof LineItemKey)) {return false;}LineItemKey other = (LineItemKey) otherOb;return ((this.getCustomerOrder() == null? other.getCustomerOrder() == null : this.getCustomerOrder().equals(other.getCustomerOrder()))&& (this.getItemId() == other.getItemId()));}@Overridepublic String toString() {return "" + getCustomerOrder() + "-" + getItemId();}/* Getters and setters */}
其中hashCode的作用是:
當我們向一個集合中添加某個元素,集合會首先調用hashCode方法,這樣就可以直接定位它所儲存的位置,若該處沒有其他元素,則直接儲存。若該處已經有元素存在,就調用equals方法來匹配這兩個元素是否相同,相同則不存,不同則散列到其他位置。這樣處理,當我們存入大量元素時就可以大大減少調用equals()方法的次數,極大地提高了效率。
所以hashCode在上面扮演的角色為尋域(尋找某個對象在集合中地區位置)。hashCode可以將集合分成若干個地區,每個對象都可以計算出他們的hash碼,可以將hash碼分組,每個分組對應著某個儲存地區,根據一個對象的hash碼就可以確定該對象所儲存地區,這樣就大大減少查詢匹配元素的數量,提高了查詢效率。這裡由於customerOrder和itemId一起組成一個複合鍵來標示一個實體,所以如果customerOrder不存在則返回0,如果存在則返回customerOrder的hash值^itemId的數值。
equal的作用:
equals動作表示的兩個變數是否是對同一個對象的引用,即堆中的內容是否相同。這裡是比較兩個對象是否相同,如果相同則返回true,如果不相同則返回false。
java第八周作業