System.identityHashcode・・・オブジェクトとしてのhashCode
hashcode・・・オーバーライド可能なhashcode
Stringのhashcodeはメモリ上は別のものを指していても、値が同じ場合同じ値を返す
identityHashcodeは別の値を返す
mutable/immutableのstudyに使用できる
下記の例ではaaaを途中でnew Stringしているのでidentityhashcodeは変更、
値は同じためhashcodeは同じ。
class A{
int i;
A(int i) {
this.i = i;
}
}
public class SampleProject {
public static void main(String[] args) {
String s = "aaa";
String s1 = "aaa";
String s2 = "aa2";
method("s",s);
method("s1",s1);
method("s2",s2);
s = new String("aaa");
method("s",s);
A a = new A(1);
A a2 = new A(1);
method("a",a);
method("a2",a2);
}
static void method(String varName, Object o) {
System.out.println(varName + " identityHashCode:" + System.identityHashCode(o) + " " + o.toString());
System.out.println(varName + " HashCode:" + o.hashCode() + " " + o.toString());
}
}
s identityHashCode:249515771 aaa
s HashCode:96321 aaa
s1 identityHashCode:249515771 aaa
s1 HashCode:96321 aaa
s2 identityHashCode:748658608 aa2
s2 HashCode:96274 aa2
s identityHashCode:546718765 aaa
s HashCode:96321 aaa
a identityHashCode:592179046 sampleproject.A@234bef66
a HashCode:592179046 sampleproject.A@234bef66
a2 identityHashCode:1937348256 sampleproject.A@737996a0
a2 HashCode:1937348256 sampleproject.A@737996a0