Comparable and comparator in Java
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
To help you understand this, we use two examples.
Comparable
import java.util.Arrays;
public class User implements Comparable<Object> {
private String id;
private int age;
public User(String id, int age) {
this.id = id;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int compareTo(Object o) {
return this.age - ((User) o).getAge();
}
/**
* Test method
*/
public static void main(String[] args) {
User[] users = new User[] { new User("a", 30), new User("b", 20) };
Arrays.sort(users);
for (int i = 0; i < users.length; i++) {
User user = users[i];
System.out.println(user.getId() + " " + user.getAge());
}
}
}
Comparator
import java.util.Arrays;
import java.util.Comparator;
public class MyComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
return toInt(o1) - toInt(o2);
}
private int toInt(Object o) {
String str = (String) o;
str = str.replaceAll("One", "1");
str = str.replaceAll("Two", "2");
str = str.replaceAll("Three", "3");
return Integer.parseInt(str);
}
/**
* Test method
*/
public static void main(String[] args) {
String[] array = new String[] { "One", "Three", "Two" };
Arrays.sort(array, new MyComparator());
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Reference : http://zhanghu198901.iteye.com/blog/1575164
RELATED
0 COMMENT
No comment for this article.
PROGRAMMER HUMOR
![]() |
Where blue screen appears on a wedding |
"Blue screen" has become one notorious symbol of Windows. Maybe you have seen the Windows blue screen in a few occasions. But have you see it on a wedding? The above is what happens on a wedding. What if Bill Gates attends a wedding and see this famous scene?
The image source is dedicated to Sina We |
SUPPORT US
If you find this article helpful, please consider supporting our work.
DONATE