地球ウォーカー2

Scala, Python の勉強日記

equalsとhashcodeを実装する(Eclipseで)

今日発見して感動したのでメモ。
EclipseでequalsメソッドとhashCodeを簡単に実装できる。

手順

public class Book {
    /** ISBN */
    private String isbn = "";

    /** タイトル */
    private String title = "";

    /** 著者 */
    private String author = "";

}

↑このクラスに対する実装するとして・・・。

private String author = "";

の次の行にカーソルを移動し、「ファイルメニュー > ソース > hashCode() および equals()の生成」をクリック。
出てきたダイアログで、equalsとhashCodeに使用するフィールドを選択する。
f:id:hysa:20101108223536p:image

たったこれだけで、equals()とhashCode()が実装される。

public class Book {
    /** ISBN */
    private String isbn = "";

    /** タイトル */
    private String title = "";

    /** 著者 */
    private String author = "";

    /* (非 Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((author == null) ? 0 : author.hashCode());
        result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }

    /* (非 Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Book)) {
            return false;
        }
        Book other = (Book) obj;
        if (author == null) {
            if (other.author != null) {
                return false;
            }
        } else if (!author.equals(other.author)) {
            return false;
        }
        if (isbn == null) {
            if (other.isbn != null) {
                return false;
            }
        } else if (!isbn.equals(other.isbn)) {
            return false;
        }
        if (title == null) {
            if (other.title != null) {
                return false;
            }
        } else if (!title.equals(other.title)) {
            return false;
        }
        return true;
    }
}

いかにも自動生成しましたって感じのソースだけど(特にequalsメソッド)、十分実用に耐えうると思う。