These are two completely different things. == compares the reference to the object, if any, contained in the variable. .equals() checks to see if two objects are consistent with their contract, which means equality. It is possible that two separate instances of the object will be βequalβ in accordance with their contract. And then there are small details that with equals are a method, if you try to call it in a null reference, you will get a NullPointerException .
For example:
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);
TJ Crowder Dec 21 '10 at 15:50 2010-12-21 15:50
source share