Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

an equals question from a mock exam

 
donald rieck
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just don't get it ( how come the equals doesn't find them equal?):

1: class MyClass
2: {
3: static int maxElements;
4:
5: MyClass(int maxElements)
6: {
7: this.maxElements = maxElements;
8: }
9:
10: }
11:
12: public class Q19
13: {
14: public static void main(String[] args)
15: {
16:
17: MyClass a = new MyClass(100);
18: MyClass b = new MyClass(100);
19:
20: if(a.equals(b))
21: System.out.println("Objects have the same values");
22: else
23: System.out.println("Objects have different values");
24: }
25: }


Prints: "Objects have different values"
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you don't override the equals method from Object, the only check that is made when you call .equals is if the two object references refer to the same object.
 
donald rieck
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doh!!

Thank you so much!!
 
donald rieck
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes, is does the " == " operator on the reference values.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic