Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

not able to add elements to TreeSet, but able to add same element to HashSet

 
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator




Output:

S1.hashCode() = 1386288267
S2.hashCode() = 1394331837
s1.equals(s2) = false
treeset.size()=1
hashset.size()=2

Why it is not allowing me to add into treeset, while it is allowing me to add to HashSet.

Can somebody explain?

here is my understanding, and why i am surprised at the behavior..

Both the objects have different hashCode... That means, definitely the objects are different.
Now, if the objects are different, then i should be able to add them to tree set also................but I am not...........while I am able to add them to HashSet....
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What does your class SlidingState look like; especially the hashCode() and equals() methods of that class?
 
author
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesper de Jong wrote:What does your class SlidingState look like; especially the hashCode() and equals() methods of that class?



Also the compareTo() method -- since TreeSet uses the Comparable (or optionally, Comparator) interface, instead of the hashCode() and equals() methods.

Henry
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesper de Jong wrote:What does your class SlidingState look like; especially the hashCode() and equals() methods of that class?



Ideally you need not look, how hashCode/equals is implemented... as long as the output is correct....

When the System out statements are making sure, that hashCode of both the objects are different...

The most interesting thing here to note is,..............I am able to add the same two States to HashSet..........but not to TreeSet

Even if you are still interested.. I will post the code for you..

 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Henry Wong wrote:

Jesper de Jong wrote:What does your class SlidingState look like; especially the hashCode() and equals() methods of that class?



Also the compareTo() method -- since TreeSet uses the Comparable (or optionally, Comparator) interface, instead of the hashCode() and equals() methods.

Henry



You seem to be right....

s1.compareTo(s2) = 0

This is written in TreeSet Implementation.

/**
* Constructs a new, empty tree set, sorted according to the
* natural ordering of its elements. All elements inserted into
* the set must implement the {@link Comparable} interface.
* Furthermore, all such elements must be mutually
* comparable
: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set. If the user attempts to add an element
* to the set that violates this constraint (for example, the user
* attempts to add a string element to a set whose elements are
* integers), the {@code add} call will throw a
* {@code ClassCastException}.



 
Henry Wong
author
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:
Ideally you need not look, how hashCode/equals is implemented... as long as the output is correct....

When the System out statements are making sure, that hashCode of both the objects are different...

The most interesting thing here to note is,..............I am able to add the same two States to HashSet..........but not to TreeSet



Unfortunately, it is not ideal... TreeSet doesn't use hashCode/equals, so it doesn't matter if the output is correct. How about running the two objects via compareTo() and see if the output is also correct. That method should return zero of the two objects are equal.

[EDIT: It looks like you figure it out ... great]

Henry
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:Ideally you need not look, how hashCode/equals is implemented... as long as the output is correct....


Erm...but clearly it ISN'T.

Also, your statement: "Both the objects have different hashCode... That means, definitely the objects are different."
is WRONG.

Different objects CAN have the same hashCode() (indeed, it's impossible to prevent). The only - I'll say again: ONLY - requirement is that equal objects have the same hashcode.

The only thing that a GOOD hashcode will do is allow you to assume that objects with different hashcode are probably not equal().

This, however, is a perfectly legal (and correct) hashCode() method;Does that help?

Winston
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Henry Wong wrote:

Yogesh Gandhi wrote:
Ideally you need not look, how hashCode/equals is implemented... as long as the output is correct....

When the System out statements are making sure, that hashCode of both the objects are different...

The most interesting thing here to note is,..............I am able to add the same two States to HashSet..........but not to TreeSet



Unfortunately, it is not ideal... TreeSet doesn't use hashCode/equals, so it doesn't matter if the output is correct. How about running the two objects via compareTo() and see if the output is also correct. That method should return zero of the two objects are equal.

[EDIT: It looks like you figure it out ... great]

Henry




Thank you so much Henry for the pointer. It was a new thing for me to know....
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:

Yogesh Gandhi wrote:Ideally you need not look, how hashCode/equals is implemented... as long as the output is correct....


Erm...but clearly it ISN'T.

Also, your statement: "Both the objects have different hashCode... That means, definitely the objects are different."
is absolutely WRONG.

Different objects CAN have the same hashCode() (indeed, it's impossible to prevent). The only (I'll say again: ONLY) requirement is that equal objects have the same hashcode.

The only thing that a GOOD hashcode will do is allow you to assume that objects with different hashcode are probably not equal().

Does that help?

Winston



There is a equal-hashcode contract...

1) Equal objets will have equal Hashcode...

So, you can read it like this also...

If hashcodes are not equal, that means objects are not equal.....

I was correct in assuming that objects are not equal..........


But the real problem lied in the way, it is added to TreeSet before added....
TreeSet uses the method compareTo and it doesn't rely on hashCode/equals to identify that objects are equal or not....

That was the real problem............In my case, I had overridden, both compareTo and hashCode...

 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:There is a equal-hashcode contract...
1) Equal objets will have equal Hashcode...
So, you can read it like this also...
If hashcodes are not equal, that means objects are not equal.....


No you CAN'T.

I suspect you'll need to think about it, but those two statements are not universal negatives.

It's akin (but not quite I suspect; I'm not an expert in semiotics) to saying "All daffodils are yellow, therefore anything that is not yellow is not a daffoldil".

Winston
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:

Yogesh Gandhi wrote:There is a equal-hashcode contract...
1) Equal objets will have equal Hashcode...
So, you can read it like this also...
If hashcodes are not equal, that means objects are not equal.....


No you CAN'T.

I suspect you'll need to think about it, but those two statements are not universal negatives.

It's akin (but not quite; but I'm not an expert in semiotics) to saying "All daffodils are yellow, therefore all things that are yellow are daffoldils."

Winston



Lets read it this way..


A and B are two objects having different hashcodes....

Now, as the hashcodes are different, we can say objects are different...because same objects cannot produce different Hashcodes........

HashSet works in this manner only, by checking the hashCodes.....if it finds different hashCodes for two objects, it treats two objects as different and will allow you to add it to a set...

 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:A and B are two objects having different hashcodes....
Now, as the hashcodes are different, we can say objects are different...


No you can't. (I've corrected my post, BTW; it was wrong - always get confused when I start converting logic to language )

The statement "equal objects must have equal hashcodes" does NOT preclude the possibility that non-equal objects ALSO have equal hashcodes. I wish the docs put the contrary side (and the one that most people get wrong) in bold, because then it might sink in a bit better.

A hashcode does NOT tell you if two objects are the same; it tells you if they're different. Indeed, there are so many possibilities for a hashcode that it cannot possibly tell you if two objects are the same. It can only tell you if they are probably the same - and in order to do that, it has to be well thought out.

Winston
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

A hashcode does NOT tell you if two objects are the same; it tells you if they're different.



I agree. This was exactly what I was trying to say... !!

If hashcodes are different, that means objects are different.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:If hashcodes are different, that means objects are different.


But that's NOT the same as saying that if they are the same, then the two objects are equal. Like I say, you have to think about it. Hashcodes are designed for a very specific purpose - to store objects in hashed collections - and they rely on difference, not similarity.

Winston
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:

Yogesh Gandhi wrote:If hashcodes are different, that means objects are different.


But that's NOT the same as saying that if they are the same, then the two objects are equal. Like I say, you have to think about it. Hashcodes are designed for a very specific purpose - to store objects in hashed collections - and they rely on difference, not similarity.

Winston



I repeat.

If hashcodes are different, that means objects are different

if hashcodes are equal....then object may or may not be equal.
 
Henry Wong
author
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston, Yogesh,

I think that both of you are saying the same thing -- just interpreting it differently in a subtle way.


Winston is correct, you can't use the hashcode to confirm that two objects are definitely different -- it will sometimes fail to work. However, Yogesh is also correct -- in the example. the objects are confirmed to be different (assuming that the contract is adhered to) as this is not a case where the technique failed to work. Also, the point of the example about the HashSet and TreeSet, which means that the context is about the fact that the objects are different, and not about checking if the objects are different.

Henry
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Henry Wong wrote:
you can't use the hashcode to confirm that two objects are definitely different -- it will sometimes fail to work.



I disagree.. Please prove with example. (I am assuming contract is adhered).

Equal objects cannot produce distinct hashcodes.... (so if hashcodes are different, that means objects are different...........NO EXCEPTIONS......it will always hold true)...


As you said, it may sometime fail........can you help us with an example?
 
Henry Wong
author
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:

Henry Wong wrote:
you can't use the hashcode to confirm that two objects are definitely different -- it will sometimes fail to work.



I disagree.. Please prove with example. (I am assuming contract is adhered).

Equal objects cannot produce distinct hashcodes.... (so if hashcodes are different, that means objects are different...........NO EXCEPTIONS......it will always hold true)...


As you said, it may sometime fail........can you help us with an example?




Check my wording -- I was very exact about it (because this is a subtle discussion). Or perhaps I should add "just" to make it clearer. You can't just use the hashcode to confirm that two objects are different.

Simple example. I have two different objects with the exact same hashcode. This is valid according to the contract. In this case, just using the hashcode test will fail -- you will need to follow up with the equals() method to confirm that they are different.

Henry
 
Saloon Keeper
Posts: 13427
303
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have to agree with Yogesh here. The discussion stemmed from the fact that he noticed the hashes of the two objects were different, and stated this meant that the objects were unequal. This observation is correct.

Equal objects have equal hash codes. So unless your implementation of equals()/hashCode() is wrong, unequal hash codes *always* imply unequal objects.

You can't use hash codes as a general test to see if two objects are equal or not, because equal hash codes are not conclusive. Unequal hash codes on the other hand are very telling.
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Henry Wong wrote:

Yogesh Gandhi wrote:

Henry Wong wrote:
you can't use the hashcode to confirm that two objects are definitely different -- it will sometimes fail to work.



I disagree.. Please prove with example. (I am assuming contract is adhered).

Equal objects cannot produce distinct hashcodes.... (so if hashcodes are different, that means objects are different...........NO EXCEPTIONS......it will always hold true)...


As you said, it may sometime fail........can you help us with an example?




Check my wording -- I was very exact about it (because this is a subtle discussion). Or perhaps I should add "just" to make it clearer. You can't just use the hashcode to confirm that two objects are different.

Simple example. I have two different objects with the exact same hashcode. This is valid according to the contract. In this case, just using the hashcode test will fail -- you will need to follow up with the equals() method to confirm that they are different.

Henry



Dear Henry,

The scenario you are considering is of equal hashCodes... where as I am considering is of unequal hashCodes...

EDIT : TreeSet will use compareTo because it needs to store elements in sorted order and unique also.......and if compareTo returns 0, it treats them as equal, and as Set has a property of distinct elements, so it doesn't add them to TreeSet....

HashCode is sufficient enough to tell us if objects are different (Please note, I did not saying anything about equality of objects, i rather talked about inequality of objects)

If hashcodes are equal, they tell you nothing...... neither it says, objects are equal, nor it says objects are unequal. ...You have to rely on equal method for equality check.....


Equal objects have equal hashCode.....
Unequal objects may or may not have unequal hashcode......


Guys !!! is there still any confusion left to anyone?
 
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, let us create a bad class that doesn't keep the equals and hashCode contract.



Now let us test this MyBadclass...



We all know what the output would be.

Obviously an object has one hashCode. So we can't test why different hashCodes may not imply different objects by just invoking the hashCode method. Let us not know in advance that we have one object only. Let us put this object in a collection and then use hashCode to see if the hashCode alone can tell us if two objects are different.
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Heena Agarwal wrote:
We all know what the output would be.



Actually, no. We all know what the output could be should be the right thing to say.
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh my, there's a lot of confusion here.

Let's go back to the original problem. You didn't give us your complete code, but enough so that I could recreate my problem in my IDE and check what's wrong.

There's something wrong with the implementation of your compareTo() method. Because when I do this:

the result is two times: 0

In other words, according to your compareTo() method implementation, s1 and s2 are equal. But their hash codes are different. That isn't right - if two objects are equal, then they must have the same hash code.

So, TreeSet gets confused, and you get unpredictable results.

You need to debug and fix your compareTo() method - find out why it thinks s1 and s2 are equal.

I also printed the result of getCost() on both s1 and s2. They both have a cost of 13. According to your compareTo() method, two SlidingStates are equal if their cost is the same. But your hashCode() and equals() methods disagree - they only regard two SlidingStates equal if their data is exactly the same.
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does a TreeSet even use the hashCode and equals methods? I remember my TreeSet implementations would work without them.

I thought a TreeSet only used compareTo/compare method to place objects into the Set.

Edit : But I understand that the contract of compareTo must be kept.
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Heena: I don't know if TreeSet uses equals / hashCode. HashSet certainly does. So:

s1 and s2 are different according to his equals and hashCode method => you see that the HashSet contains two objects
s1 and s2 are equal according to his compareTo method => you see that the TreeSet contains only one object
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes Jesper, I get what you are saying. His compareTo method isn't consistent with his equals and hashCode methods, which, like you said is the root cause of the problem. :-)

The OP needs to fix that.

 
Henry Wong
author
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Heena Agarwal wrote:Yes Jesper, I get what you are saying. His compareTo method isn't consistent with his equals and hashCode methods, which, like you said is the root cause of the problem. :-)

The OP needs to fix that.



Technically, it is the TreeSet class (usage of) that is in violation of the contract. The State class is fine with the HashSet class.

The HashSet class requires that the equals()/hashCode() method are following contract, and they are.

The TreeSet class only requires the compareTo() method, which it is... but... the TreeSet class IS-A Set, and Set requires the equals() method to be consistent (to determine duplicates), and in this case of the State class, it isn't. So, it is in violation when used with a TreeSet, even though the equals() method is not even used by TreeSet.

Henry
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:Guys !!! is there still any confusion left to anyone?


No. And my apology if I was the cause. However, you have two forms of "equality": equal by content and equal by order, and the two are NOT the same. "Tree" structures are only concerned with the latter, and I believe the TreeSet docs do state that it overrides the normal requirements of a Set.

The simplest example I know is +0.0 and -0.0. They are distinct Double, but not double values. So, whereas -0.0 == 0.0,
Double.valueOf(-0.0).equals(Double.valueOf(0.0))
returns false.
The docs for Double say that this is purely for consistency between equals() and compareTo() - which, as we've seen, is important; but it's a major difference between double and Double, two types that ostensibly define the same thing.

You can also imagine a similar sort of decision required for a Fraction class:
Is 1/2 "equal" to 2/4?
As a value, the answer is clearly yes; but for order? There are almost unlimited ways to write 1/2 as a Fraction, and if they are all simply "lumped together" then unstable sorts may well re-order them. If that's unacceptable, then the only recourse is to say that 1/2 is NOT equal() to 2/4, which makes for a very odd equals() method.

Just to add to the confusion...

Winston
 
Bartender
Posts: 4709
183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It all goes to show that sometimes you need more than just one 'compareTo' and/or 'equals' method, to be used in different circumstances.
While it may seem obvious that '1/2' 'equals' '2/4', it makes sense to define them to be unequal. In that way you can
define a matching compareTo method, so that you can safely use these Fractions in a TreeSet.
However, to get the result that '1/2' DOES equal '2/4', define a special method 'equalsInValue' and possibly also
'comparesToInValue'. It is then up to the user to decide which to use.

I had a similar problem a couple of moons ago, when working on a ProjectEuler problem, which was about to
compare two poker hands, according to the normal poker rules.
So I defined a Card class, with the obvious equals method, when two cards were equal if and only if
both cards had the same suit and value. However, sometimes comparing two pokerhands involves comparing
two Cards. Now, in poker, two cards are 'equal' if they have the same value, no matter what suit. But I couldn't
use that as my 'compareTo' definition, since it would violate the 'equals' contract (two cards compare equal, while
'equal' would say not, since the suits are different). Besides, it would also mean that in my TreeSet that I used
for a pokerhand, I could only have say one '7', which would be desastrous.

So, after some long thinking and a lot of confusion, I went for the double 'compareTo' option. The normal
'compareTo' included the suit and was so in line with 'equals' and safe for a TreeSet, but in comparing two
poker cards, I used the special method 'compareToPoker', in a 'PokerCard' subclass of 'Card'.

Fascinating subject, isn't it?
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Heena Agarwal wrote:
We all know what the output would be.

Obviously an object has one hashCode. So we can't test why different hashCodes may not imply different objects by just invoking the hashCode method. Let us not know in advance that we have one object only. Let us put this object in a collection and then use hashCode to see if the hashCode alone can tell us if two objects are different.



No... I was able to add the two objects to the hashset.. See the following code and output





Output:

true
41
true
51
2



It clearly shows, that hashcode has been changed after adding it to set............Hence the objects are different, and hence it is allowed to add to the set...






 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Heena Agarwal wrote:Yes Jesper, I get what you are saying. His compareTo method isn't consistent with his equals and hashCode methods, which, like you said is the root cause of the problem. :-)

The OP needs to fix that.



Correct version of compareTo method..



Output

S1.hashCode() = 1386288267
S2.hashCode() = 1394331837
s1.equals(s2) = false
s1.compareTo(s2) = -1
treeset.size()=2
hashset.size()=2
 
Yogesh Gandhi
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:No. And my apology if I was the cause



No No... please don't apologize... it was you due to whom, we all got to learn so much....

It was heartening to see such a good response on this topic.............


So the bottom line is.........

Be cautious when you override, compareTo.............it must stick with the contract of equals and hashcode..........Would that be a right conclusion?
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yogesh Gandhi wrote:So the bottom line is.........
Be cautious when you override, compareTo.............it must stick with the contract of equals and hashcode..........Would that be a right conclusion?


I think "must" is a bit strong.

I rather like the wording in java.lang.Comparable:
"It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals."

It also goes on to say that one SDK class that breaks this contract is BigDecimal, which is why you should always use compareTo() rather than equals() if you want to compare them for numeric equality. TBH, I think I would have just made them consistent, and added an extra matches() method that works like equals() does now, but I'm sure Josh (Bloch; the author) had his reasons for not doing so.

I think my wording would be something like: "make equals() and compareTo() consistent, or clearly document that fact that they aren't and the reasons why".

Winston
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic