Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

From Effective Java.

 
Prakash Rai
Ranch Hand
Posts: 106
Eclipse IDE MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Campbell Ritchie
Sheriff
Pie
Posts: 50235
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another version is:
Always start your equals() methods like thisUsing the short‑circuit operator || ensure the remainder of the equals method is never executed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic