• Post Reply Bookmark Topic Watch Topic
  • New Topic

How Strings behave in HashMaps vs String arrays  RSS feed

 
Omar Sharaki
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How come this prints "is there" but this:



prints "not there"? Thanks in advance!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Print out the result of s1.equals(s2) in both cases and see the difference.
 
Omar Sharaki
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well for the String arrays it says that they're not equal but for the Strings it says that they are equal. Do you know why this is?
 
Paweł Baczyński
Bartender
Posts: 2086
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because String class overrides equals method and arrays have the same implementation as Object class (comparing identity of object).

Consider this example:Class DoesNotOverrideEquals uses an implementation of equals() inherited from Object class (like arrays do). So the result of a1.equals(a2) was false.
Class OverridesEquals overrides equals() (like String does). So the result of b1.equals(b2) was true.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!