Results 1 to 8 of 8
- 03-09-2011, 03:37 PM #1
how to compare Strings with compareTo?
I'm trying to understand and correctly implement the compareTo() method.
So far I've seen that you need to use the class member you choose to order your class instances.
Let's say I have a class with the members "name" (String) and "age" (integer), and I want to order the instances using the age as a comparison, I'd do something like this:
public int compareTo(Object o)
if(!(o instanceof Student))
throw new ClassCastException();
if(((Student)o).age < this.getAge())
else return 0;
But if I wanted to use the "name" member (which is a String), I can't use the < and > operators. As I've seen in my web searches, they use the name.compareTo()
My question is: if I'm using compareTo() there, it's using it from the Object class, right?
Is that correct? How does it work, if I'm using the compareTo() method inside my compareTo overridden method? It just sounds a bit wrong as a concept :D
(my friend's answer was "just use it like that and stop nagging me", but I really want to know)
- 03-09-2011, 03:49 PM #2
- 03-10-2011, 12:44 PM #3
My question was about the need to override the compareTo method (say, when you use a TreeSet). I didn't know why you would use compareTo when that's the method you're trying to replace.
That's because the compareTo method in a specific class you made will not "know" how to compare its instances, but the String class has already a well defined behavior for it, right?
Thanks again :)
- 03-10-2011, 12:47 PM #4
Pretty much, why re-invent the wheel when the smart people at sun/oracle already created a working version?
- 03-10-2011, 01:04 PM #5
Lol. That's right.
I just heard so many times that "you HAVE to override compareTo() and equals()!" that it confused me. They should have added "but only for the classes you create" :p
- 03-10-2011, 01:33 PM #6
haha yes, try to always use the built in compare to methods in your overridden compareTo method in your class. Also don't forget overriding hashCode().
- 03-10-2011, 02:16 PM #7
Oh, does hashCode() have to be overridden too when using compareTo()? Because I read that hashCode() has to be consistent with equals(), using the same fields. Does it also have to be consistent with compareTo?
- 03-10-2011, 02:20 PM #8
- By roud9 in forum New To JavaReplies: 1Last Post: 11-05-2010, 12:57 AM
- By Cylab in forum New To JavaReplies: 5Last Post: 08-19-2010, 02:42 PM
- By ChaosINC in forum New To JavaReplies: 3Last Post: 01-17-2010, 12:39 PM
- By christuart in forum NetworkingReplies: 15Last Post: 09-01-2008, 03:24 AM
- By elizabeth in forum New To JavaReplies: 7Last Post: 08-06-2007, 03:57 AM