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 compareTo(Emp i) {
if (this.getName() == ((Emp ) i).getName())
return 0;
else if ((this.getName()) > ((Emp ) i).getName())
return 1;
else
return -1;
What you need to use is the
compareTo()
method of Strings.That should do what you want.
Usually when implementing the
Comparable
interface, you will just aggregate the results of using otherComparable
members of the class.Below is a pretty typical implementation of a
compareTo()
method:You don't need to cast i to Emp, it's already an Emp:
Java String already implements Comparable. So you could simply write your method as
(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.
Shouldn't
if (this.getName() == ((Emp ) i).getName())
be
if (this.getName().equals(i.getName()))
Pretty sure your code can just be written like this: