I think you've almost got it. The static method makes the following promise, "if you request a new object that would compare .equals() to an existing object, I'll return the existing object instead". Given that guarantee, you know that a.equals(b)
means that a == b
, and you know that a == b
means that a.equals(b)
. As a result, if you want to see if a
and b
are equal, you can use the ==
operator instead of the .equals
method. That's useful because ==
is very fast and, depending on the object types, .equals
could be slow.
Here's a concrete example. Suppose we have a person class. A person is defined by their first and last name (pretend that there are no two people in the world with the same name). My class might look like this (didn't try to compile, so no guarantee of correctness):
class Person {
private final String fname;
private final String lname;
// Private constructor - must use the static method
private Person(String first, String last) {fname = first; lname = last;}
// Note that this is slow - the time it takes is proportional to the length of the
// two names
public boolean equals(Object o) {
// Should check types here, etc.
Person other = (Person) o;
if (!person.fname.equals(other.fname)) {return false;}
if (!person.lname.equals(other.lname)) {return false;}
return true;
}
// Registry of all existing people
private static Map<String, Person> registry = new TreeMap<String, Person>();
public static getPerson(String fname, String lname) {
String fullName = fname + "-" + lname;
// If we already have this person, return that object, don't construct a new one.
// This ensures that p1.equals(p2) means that p1 == p2
if (registry.containsKey(fullName)) {return registry.get(fullName);}
Person p = new Person(fname, lname);
registry.put(fullName, p);
return p;
}
}
And then you can use it like this:
public boolean isSamePerson(Person p1, Person p2) {
// Guaranteed to have the same result as "return p1.equals(p2)" but will be faster
return p1 == p2;
}