File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes From Effective Java. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "From Effective Java." Watch "From Effective Java." New topic

From Effective Java.

Prakash Rai
Ranch Hand

Joined: Jan 10, 2011
Posts: 106

Q. No two equals instance exist : a.equals(b) if and only if a==b. If a class make this guarantee,then its client can use == instead of the equals(Object) method which may improved performance. How?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

What exactly is your question about: (1) how a class can make sure that a.equals(b) is true if and only if a == b, or (2) how using == instead of equals() improves performance?

To answer the second one first (because it's really simple): equals() is a method. A method call and executing all the statements in the method is more work than simply comparing two values, which is what == does. So, obviously, == is a less expensive operation than calling equals(), so if you can use == instead of equals() that improves performance.

For the first question: Note what == does when you use it on variables of non-primitive types: it checks if the two references on both sides of the == refer to the exact same object. If you want to make a class for which == has the same meaning as equals(), you should make it so that it's impossible to make two separate objects of the class which are "equal". Note that for example enums have this property, therefore it's safe to compare enums with ==, you don't need to use equals().

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46367
Another version is:
Always start your equals() methods like thisUsing the short‑circuit operator || ensure the remainder of the equals method is never executed.
I agree. Here's the link:
subject: From Effective Java.
jQuery in Action, 3rd edition