• 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

equality of enum question -- from Phil Heller book

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public enum TrafficLight {
RED, GREEN, AMBER;
}

Suppose x and y are of type TrafficLight. What is the best way to test whether x and y refer to the same constant ?

A. if (x==y)
B. if (x.equals(y))
C. if (x.toString().equals(y.toString()))
D. if (x.hashCode() == y.hashCode())

I think the answer should be B but the author says A giving the explanation - " It is never possible to have two instances of an enum that represent the same value. So the == operator is reliable and is faster than any other method call."

I dont get this... can anyone pls explain.....
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the example, TrafficLight.RED is implemented by one and only one object. So any two references to TrafficLight.RED will always refer to the same object. That is: TrafficLight x = TrafficLight.RED; TrafficLight.RED y = TrafficLight.RED always means that x == y is true. Therefore, if z is defined by TrafficLight z = TrafficLight.BLUE then x == z and y == z are both false because TrafficLight.RED and TrafficLight.BLUE are represented by different but individually unique objects.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic