これら 2 つのコード スニペットの違いは何ですか?
スニペット 1:
Object o = new Object();
int i = Objects.hashCode(o);
スニペット 2:
Object o = new Object();
int i = o.hashCode();
唯一の違いは、 o が null の場合Objects.hashCode(o)は 0 を返すのに対しo.hashCode()、 a をスローすることNullPointerExceptionです。
Objects.hashCode()実装方法は次のとおりです。
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
の場合oはnullをObjects.hashCode(o);返しますが0、o.hashCode()をスローしNullPointerExceptionます。
java.util.Objects {
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
}
これは、o.hashCode() の NPE セーフな代替手段です。
それ以外の違いはありません。
Object o = new Object();
int i = Objects.hashCode(o);
null 以外の引数のハッシュ コードを返し、null 引数の場合は 0 を返します。この場合は でObject参照されます。oスローしませんNullPointerException。
Object o = new Object();
int i = o.hashCode();
Objectによって参照された の hashCode() を返しますo。の場合、oがnull得られますNullPointerException。