Comparable | Comparator | |
1 | this interface allows the object to compare itself with another object while sorting the list of such type objects. | This interface provide the provision to compare two different objects. |
2 | The objects those implements Comparable interface are sorted automatically without specifying any other comparator. | Comparator is passed as arguments to the method who need to sort some objects. |
3 | less flexible | more flexible |
4 | uses compareTo(object2) method | it has compare(object1,object2) method |
5 | this interface is not a part of collection API. It belongs to java.lang Packages | this interface belongs to java.util package. |
Using Comparable
package collection.examples;
import java.util.ArrayList;
import java.util.Collections;
class Contact implements Comparable<Contact>{
String name;
String email;
int phone;
public Contact(String name, String email, int phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
public int compareTo(Contact otherContact) {
return this.name.compareTo(otherContact.name);
}
@Override
public String toString() {
return "Contact{" + "name=" + name + ", email=" + email + ", phone=" + phone + '}';
}
}
public class UsingComparable {
public static void main(String[] args) {
Contact c1=new Contact("rbc","mail1@gmail.com",2424342);
Contact c2=new Contact("tbc","mail2@gmail.com",2424342);
Contact c3=new Contact("bcc","mail3@gmail.com",2424342);
ArrayList<Contact> al=new ArrayList<Contact>();
al.add(c1);
al.add(c2);
al.add(c3);
Collections.sort(al);
for (Contact contact : al) {
System.out.println(contact);
}
}
}
Using Comparator
package collection.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Contact1 {
String name;
String email;
int phone;
public Contact1(String name, String email, int phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
@Override
public String toString() {
return "Contact1{" + "name=" + name + ", email=" + email + ", phone=" + phone + '}';
}
}
class MyComparator implements Comparator<Contact1>{
public int compare(Contact1 o1, Contact1 o2) {
//comparing name from both objects
return o1.name.compareTo(o2.name);
}
}
public class UsingComparator {
public static void main(String[] args) {
Contact1 c1=new Contact1("zzz","mail1@gmail.com",2424342);
Contact1 c2=new Contact1("bbb","mail2@gmail.com",2424342);
Contact1 c3=new Contact1("ccc","mail3@gmail.com",2424342);
ArrayList<Contact1> al=new ArrayList<Contact1>();
al.add(c1);
al.add(c2);
al.add(c3);
Collections.sort(al, new MyComparator());
for (Contact1 contact : al) {
System.out.println(contact);
}
}
}
Comments
Source: How to use Comparator and Comparable in Java