• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Majii's Exam..Paper1 #6

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm confused by #6 Paper1 vs. #20 Paper2;
Double a = new Double(Double.NaN);
Double b = new Double(Double.Nan);
if (a.equals(b))
System.out.prinln("true");
else //here the answer is TRUE
System.out.println("false");
HOWEVER..I left out unnecessary lines
//Paper 2 #20
MyClass(int maxElements)
{ this.maxElements = maxElements;}
//in main
MyClass a = new MyClass(100);
MyClass b = new MyClass(100);
if (a.equals(b))
.....print true //here the answer is FALSE
else
print false
Why is this? Any help would be appreciated.
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The equals method is defined in the Object class, so it is included in all classes. It is defined in the Object Class as Object obj2.equals(Object obj1) will be true if and only if obj1 is the same object as obj2. This is the minimum requirement for the equals method.
However, classes override the equals method to give it a better meaning for thier class. For Double, equals is overridden so it will return true if the value of the doubles are == to each other with the exception of NAN where == will be false, but equals will return true.
So for the above question, Double.NaN.equals(Double.NaN) will return true as per the overridden method in Double. But for MyClass, if they don't override equals then it is going to return false unless the objects refer to the same objec, which in the case above they don't.
Hope that makes sense.
Bill
 
Cheryl Gray
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bill:
Thanks for the explanation. I now remember reading a little about the overriding part in Bruce Eckel's book.
reply
    Bookmark Topic Watch Topic
  • New Topic