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())
return 1;
if(((Alumno)o).age> this.getAge())
return -1;
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)
Thanks :)