2

I'm trying to compare the names of objects of my own class Person so I can sort an ArrayList. I followed what my teacher did but can't seem to get why it doesn't work.

import java.util.*;

public class SortName implements Comparable<Person>{
    public int compare(Person p1, Person p2){
        return p1.getName().compareTo(p2.getName());
    }
}
JozzWhers
  • 81
  • 1
  • 4

4 Answers4

3

It should be Comparator interface. Comparator interface has compare() method not Comparable.

public class SortName implements Comparator<Person>
ProgrammerBoy
  • 876
  • 6
  • 19
2

The compare() method is correct, BUT you’re using the wrong interface. Implement Comparator, not Comparable. They’re easy to mix up.

import java.util.*;

public class SortName implements Comparator<Person>{
    public int compare(Person p1, Person p2){
        return p1.getName().compareTo(p2.getName());
    }
}
Oskarzito
  • 458
  • 2
  • 13
1

You can try it with compareTo() method:

import java.util.*;

public class SortName implements Comparable<Person>{
    public int compareTo(Person p2){
        return this.getName().compareTo(p2.getName());
    }
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
strash
  • 1,291
  • 2
  • 15
  • 29
1

Referring to What is the difference between compare() and compareTo()?

Comparator interface let you override its int compare(Object o1, Object o2) method.
Implementing this interface helps you to sort your inbuilt data structure or even a custom defined data data structure.

Comparable interface lets you override its int compareTo(Object o) method.
Example: (x.compareTo(y)==0) == (x.equals(y))

Community
  • 1
  • 1
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27