• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

From Effective Java.

 
Ranch Hand
Posts: 107
MyEclipse IDE Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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().
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic