欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Comparator 与 Comparable之间的差别

程序员文章站 2024-01-13 22:38:22
...
以前一直都用Comparable接口来排序直到最近才只知道还有Comparator接口。
2个接口的区别在于一个是在类的内部实现,另外一个是通过外部类来实现
简单通过代码来写下区别
1、Comparator 模式
A、被比较的类

public class User {

private String name;

private int age;

public String getName() {
return name;
}

public void setName(final String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(final int age) {
this.age = age;
}

}


B、比较的实现

import java.util.Comparator;

public class UserCompare implements Comparator<User> {

@Override
public int compare(final User user1, final User user2) {
if (user1.getAge() > user2.getAge()) {
return 1;
} else if (user1.getAge() < user2.getAge()) {
return -1;
} else {
return 0;
}
}
}



2、Comparable模式

public class UserVo implements Comparable<UserVo> {

private String name;

private int age;

public String getName() {
return name;
}

public void setName(final String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(final int age) {
this.age = age;
}

@Override
public int compareTo(final UserVo user) {
if (this.age > user.getAge()) {
return 1;
} else if (this.age < user.getAge()) {
return -1;
} else {
return 0;
}
}

}


3、Main方法

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(final String args[]) {
User user1 = new User();
user1.setName("1");
user1.setAge(1);
User user2 = new User();
user2.setName("2");
user2.setAge(2);
UserCompare uc = new UserCompare();
List<User> array = new ArrayList<User>();
array.add(user1);
array.add(user2);
Collections.sort(array, uc);
System.out.println("==============Comparator==============");
for (User user : array) {
System.out.println(user.getName());
}
UserVo userVo1 = new UserVo();
userVo1.setName("1");
userVo1.setAge(2);
UserVo userVo2 = new UserVo();
userVo2.setName("2");
userVo2.setAge(1);
List<UserVo> array1 = new ArrayList<UserVo>();
array1.add(userVo1);
array1.add(userVo2);
Collections.sort(array1);
System.out.println("==============Comparable==============");
for (UserVo user : array1) {
System.out.println(user.getName());
}
}
}


4、结果
==============Comparator==============
1
2
==============Comparable==============
2
1
相关标签: java 比较