• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array and .equals() vs ==  RSS feed

 
AngelinaJeana Brown
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am reading about Array equality on page 121 of the OCA book. I want to make sure I understand equals() vs ==. Are both equals() and == comparing the objects that the variables are pointing to rather than their contents ("a", "b", "c")?
I entered this into Eclipse:


Result:
true
true

      
Result:
false
false


Thanks!



 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Array classes, by default, do not override the equals() method. Instead these classes inherit the equals() method from the Object class, which does the comparison by reference (and not by content).

Henry
 
AngelinaJeana Brown
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!!
 
Campbell Ritchie
Marshal
Posts: 55793
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's all in the Java® Language Specification (but that can be difficult to read). The clone() method is overridden, there is a length field, and everything else is inherited directly from Object. There is therefore, as Henry has told you, no difference between == and equals in this instance, and you cannot change that behaviour. If you want better equality comparisons, look at Arrays#equals().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!