java第八周作業

來源:互聯網
上載者:User

標籤:內容   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第八周作業

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.