1,错误用法
a.equals(b) //a 是null, 抛出NullPointException异常
2,正确用法
Objects.equals(a, b) //这种方法对null值进行了条件判断
分析源码
public final class Objects { private Objects() { throw new AssertionError("No java.util.Objects instances for you!"); } public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); //null值先通过地址判断 }
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }