Search code examples
javastringinterfacecomparablecompareto

How do I compare Strings in Java without using compareTo?


I need to compare two Objects by a string attribute, how can I do this without using the compareTo() method?

My code looks something like this :

public int compareTo(className b){
if (b instanceof className){
        className a = (ClassName ) b;
    if (this.stringName==a.stringName) return 0;   
    if (this.stringName > a.stringName) return 1;   // <- How can I know if it this bigger or smaller? Can't use < > operators on strings.
       else 
            return -1;
}

Solution

  • First, don't use the == operator to compare for equality. This operator is for object identity. But it is possible to have two different objects representing the same string. Use the String.equals() method instead.

    The String.compareTo() method is the method of choice to compare strings. It's meant exactly for that.

    If you want to implement your own compareTo() method, then you can iterate over the individual characters (each of type char, see method String.charAt()). char is a primitive type, so you can use the operators ==, < and > to compare two characters. I will not post the whole solution, because you want to learn by trying it by yourself.