| Author |
overriding compareTo
|
kevinn lee
Ranch Hand
Joined: Feb 15, 2010
Posts: 87
|
|
How to get rid of this error and what causes it?
thanks
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9191
|
|
How to get rid of this error and what causes it?
What error?? Can you post the error that you are getting...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
kevinn lee
Ranch Hand
Joined: Feb 15, 2010
Posts: 87
|
|
|
|
 |
Prithvi Sehgal
Ranch Hand
Joined: Oct 13, 2009
Posts: 771
|
|
Dear Kevin,
One hint for you. Do you think that compareTo() method is defined for integers?
What you are trying to do is year.compareTo(), and nothing like compareTo exists
for integers.
Do you think, it might help you?
Hope this helps you,
|
Prithvi/Beenish,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
|
 |
Dejan Miler
Ranch Hand
Joined: Nov 14, 2009
Posts: 56
|
|
# int cannot be dereferenced
# return year.compareTo(b.year);
year is primitive data type so it do not have compareTo method
Dejan
|
SCJP 1.6 in progress ....
|
 |
kevinn lee
Ranch Hand
Joined: Feb 15, 2010
Posts: 87
|
|
hello Prithivi
using a wrapper class is the solution then.is it?
thanks
|
 |
kevinn lee
Ranch Hand
Joined: Feb 15, 2010
Posts: 87
|
|
Dejan Miler wrote:
# int cannot be dereferenced
# return year.compareTo(b.year);
year is primitive data type so it do not have compareTo method
Dejan
thanks
|
 |
Moguluri Ravi Kiran
Ranch Hand
Joined: Apr 16, 2010
Posts: 60
|
|
Dear Kevin Lee,
I dont know the way you want your Book class to work....
but i am telling the way how to use the compareTo()
& your error is simple , all our friends already explained.
you need here two things
1) how to use equals()
2) intention of compareTo()
for equals() go through Thinking in Java ed.4...
now for the CompareTo() the implementation must be as follows.
let b1 & b2 are your book instances
1) if b1.equals(b2) is true then b1.compareTo(b2)==0 must be true...
2) if b1.equals(b2) is false then b1.compareTo(b2) must return a non-zero...
3) any_book_obj.compareTo(null) must throw NullPointerException.
4) for incompatiable class it must throw ClassCastException.
Click Here for More
your modified program is
|
 |
kevinn lee
Ranch Hand
Joined: Feb 15, 2010
Posts: 87
|
|
thank you ravi
I wanted to sort the Book objects according to the year.Thats why I used compareTo in Book claas.After making year an Integer instead of a primitive the code worked.
Is there any other means of getting it done that is better?(to be used with sort())
thanks again
|
 |
 |
|
|
subject: overriding compareTo
|
|
|