With the code above, I have the following questions :-
The above code prints (as expected):-
Name =
FRUIT, Sweetness = 0
Name = APPLE, Sweetness = 1
Name = GALAAPPLE, Sweetness = 3
Name = MACAPPLE, Sweetness = 5
1. Now when I comment out the entire equals(), I still get the same output as above, i.e.,
Name = FRUIT, Sweetness = 0
Name = APPLE, Sweetness = 1
Name = GALAAPPLE, Sweetness = 3
Name = MACAPPLE, Sweetness = 5
If you note above, I am adding two new apple objects to TreeSet. Since I dont have my own equals(), the equals() of the parent Object class will be used which only checks for == operator, but I added two new apple objects, so why doesnot my collection have 5 objects as I added?
2. Now If I comment out the contents of the compareTo() and let it return 0 all the time, the output now becomes :-
Name = MACAPPLE, Sweetness = 5
I understand this since when you add the second element, the compareTo() will return 0 which means the object is already present and so it wont be added.
However if I let it return -1, then the output becomes :-
Name = APPLE, Sweetness = 1
Name = GALAAPPLE, Sweetness = 3
Name = FRUIT, Sweetness = 0
Name = APPLE, Sweetness = 1
Name = MACAPPLE, Sweetness = 5
And when it returns +1, when the output becomes :-
Name = MACAPPLE, Sweetness = 5
Name = APPLE, Sweetness = 1
Name = FRUIT, Sweetness = 0
Name = GALAAPPLE, Sweetness = 3
Name = APPLE, Sweetness = 1
How do we explain this behavior ? What order is being used here ?
Also notice that my collection now show 5 elements. If I revert the compareTo() to its original good logic, then the size drops to 4 elements..
pls enlighten me on whats going on here....
[ July 13, 2005: Message edited by: Barry Gaunt ]