I wanted to sort an array list of objects based on one of the properties of object lets say here in my code 'name' , I searched and found out about using 'Comparator' for this option, the below class is my objects :
public class PhoneBook{
long number;
String name;
String family;
String address;
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
and I override the 'compare' method in my sort method, like this:
public void sort()
{
Collections.sort(phoneBooks, new Comparator<PhoneBook>() {
@Override
public int compare(PhoneBook o1, PhoneBook o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
}
but my problem is that I get confused why without implementing 'Comparable' in the first code like this:
public class PhoneBook implements Comparable<PhoneBook>
the sort method work well, and actually I tried the above code and it gave me error so I remove the implement part but I saw it works.