Win a copy of Java by Comparison (eBook) this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Array and .equals() vs ==  RSS feed

 
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!



 
author
Sheriff
Posts: 23383
128
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!!
 
Sheriff
Posts: 57798
178
  • 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().
 
You didn't tell me he was so big. Unlike this tiny ad:
Thread Boost - a very different sort of advertising
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!