How to use the Comparable CompareTo on Strings in Java

后端 未结 5 1840
甜味超标
甜味超标 2020-12-29 22:33

I can use it to sort by emp id but I\'m not sure if it is possible to compare strings. I get an error the operator is undefined for strings.

public int compa         


        
5条回答
  •  暖寄归人
    2020-12-29 22:54

    Java String already implements Comparable. So you could simply write your method as

    public int compareTo(Emp emp) {
       return this.getName().compareTo(emp.getName());
    }
    

    (ofcourse make sure you add proper validations such as null checks etc)

    Also in your code, do not try to compare Strings using '=='. Use 'equals' method instead. '==' only compare string references while equals semantically compares two strings.

提交回复
热议问题