
Mix加上@Override註解,確定正確地覆寫hashCode(),因為已經覆寫了equals(),所以計算hash code要取id值,最後記得呼叫toHashCode()取傳回值。
package org.openyu.java.commons.lang; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * The Class Book. */ public class Book { /** The id. */ private long id; /** The name. */ private String name; /** * The Constructor. */ public Book() { } /** * Gets the id. * * @return the id */ public long getId() { return id; } /** * Sets the id. * * @param id * the id */ public void setId(long id) { this.id = id; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name * the name */ public void setName(String name) { this.name = name; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof Book)) { return false; } Book other = (Book) obj; return new EqualsBuilder() .append(getId(), other.getId()) .isEquals(); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return new HashCodeBuilder() .append(getId()) .toHashCode(); } }
Mix撰寫一些測試程式碼,來檢查看看,是否符合預期,當book與book2相等時,兩者的hashCode也需相等。
package org.openyu.java.commons.lang; import static org.junit.Assert.*; import org.junit.Test; /** * The Class BookTest. */ public class BookTest { /** * HashCodez. */ @Test public void hashCodez() { Book book = new Book(); book.setId(1); // Book book2 = new Book(); book2.setId(1); // boolean result = book.equals(book2); System.out.println("book.equals(book2) = " + result); assertTrue(result); int hashCode = book.hashCode(); int hashCode2 = book2.hashCode(); System.out.println("book.hashCode() = " + book.hashCode()); System.out.println("book2.hashCode() = " + book2.hashCode()); assertTrue(hashCode == hashCode2); } }
測試成功了,符合Mix的預期。
console查看其結果。
book.equals(book2) = true book.hashCode() = 630 book2.hashCode() = 630
沒有留言:
張貼留言