• Post Reply Bookmark Topic Watch Topic
  • New Topic

comparing objects?  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys I'm wondering if its possible to compare objects to each other in java?? and if so how would this be possible and why thanks =) heres my ode which obviously does not work I tried the == which will just see if both objects point to the same location in memory which I knew would return false then I tried the .equals but it still returned false and I'm wondering is this true because there was also an object being passed in(composition) instead of a string.any advice would be much appreciated thanks guys.

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the section about equals() in the Java Tutorials
 
Victor Bogo
Greenhorn
Posts: 25
AngularJS Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can implement your own version of equals() in your class using override. Once done you can use your way to say if those objects are equals or not
 
Liutauras Vilda
Sheriff
Posts: 4930
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adam,

From the previous thread you learned the lesson, that objects equality suppose to be checked with "equals" method rather than "==", and your attempt was logical step to do so.
But the problem, that implementation of "equals" method in Object class differs from your used "equals" method from String class, in fact, String class overrides this method. So you need to override this method in the way you want too.
How to do that, you could find in Junilu's suggested link, specifically in "The equals() Method" paragraph.

regards,
LV
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Beware: writing equals methods is notoriously difficult. I usually quote 3 references which you will find in this old thread. There used to be a pdf sample chapter with those pages from Bloch available free but I am not sure where you will find it. You can probably find it if you search hard enough.


[Edit:] more links in this thread. you should find Bloch there.[/edit]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!