2011/03/06

==演算子とjava.lang.Object#equals(Object)メソッド

public class Equals {
    public static final void main(String[] args) {
        final String aaa0 = "aaa";
        final String aaa1 = "aaa";
        System.out.println("aaa0 == aaa1 : " + (aaa0 == aaa1));// -> true
        final String aaa2 = new String("aaa");
        final String aaa3 = new String("aaa");
        System.out.println("aaa2 == aaa3 : " + (aaa2 == aaa3));// -> false
        System.out.println("aaa2 equals aaa3 : " + (aaa2.equals(aaa3)));// -> true
        
        final Integer one0 = 1;
        final Integer one1 = 1;
        System.out.println("one0 == one1 : " + (one0 == one1));// -> true
        final Integer one2 = new Integer(1);
        final Integer one3 = new Integer(1);
        System.out.println("one2 == one3 : " + (one2 == one3));// -> false
        System.out.println("one2 equals one3 : " + (one2.equals(one3)));// -> true
        
        final Hoge hoge0 = new Hoge(0);
        final Hoge hoge1 = new Hoge(0);
        System.out.println("hoge0 == hoge1 : " + (hoge0 == hoge1));// -> false
        System.out.println("hoge0 equals hoge1 : " + (hoge0.equals(hoge1)));// -> true
    }
}
class Hoge {
    private int i;
    public Hoge(int i) {
        this.i = i;
    }
    public int getI() {
        return i;
    }
    @Override public boolean equals(Object obj) {
        return obj instanceof Hoge ? ((Hoge) obj).getI() == i : false;
    }
    @Override public int hashCode() {
        return i;
    }
}
see also: Javaプログラマであるかを見分ける10の質問 「==演算子とequalsメソッドの違いは何か?」

0 件のコメント :

コメントを投稿