他们是完全不同的两件事。
==比较变量包含的对象引用(如果有)。根据相等性的含义
.equals()检查两个对象是否相等。根据它们的契约,两个不同的对象实例完全有可能“相等”。还有一个小细节,因为这
equals是一个方法,所以如果你尝试在引用上调用它
null,则会得到一个
NullPointerException。
例如:
class Foo { private int data; Foo(int d) { this.data = d; } @Override public boolean equals(Object other) { if (other == null || other.getClass() != this.getClass()) {return false; } return ((Foo)other).data == this.data; } }Foo f1 = new Foo(5);Foo f2 = new Foo(5);System.out.println(f1 == f2);// outputs false, they're distinct object instancesSystem.out.println(f1.equals(f2));// outputs true, they're "equal" according to their definitionFoo f3 = null;System.out.println(f3 == null);// outputs true, `f3` doesn't have any object reference assigned to itSystem.out.println(f3.equals(null));// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anythingSystem.out.println(f1.equals(f3));// Outputs false, since `f1` is a valid instance but `f3` is null,// so one of the first checks inside the `Foo#equals` method will// disallow the equality because it sees that `other` == null


