- 在对象list或者对象数组需要排序的时候会用到这两种接口,对象list排序使用Collections.sort(),对象数组排序使用Arrays.sort()
- Comparable实例
package com.yixun.cn;
public class Person implements Comparable<Person> {
private Integer id;
private Integer age;
private String name;
public Person(Integer id, Integer age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
}
@Override
public int compareTo(Person o) {
// 先按照年龄排序,年龄相等则按照id排序
if (this.age == o.getAge()) {
return this.id - o.getId();
} else {
return this.age - o.getAge();
}
}
}
package com.yixun.cn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestDemo {
public static void main(String[] args) {
List<Person> li = new ArrayList<Person>();
li.add(new Person(1, 21, "张三"));
li.add(new Person(2, 22, "李四"));
li.add(new Person(3, 23, "王五"));
li.add(new Person(4, 24, "麻六"));
li.add(new Person(7, 25, "赵七"));
li.add(new Person(6, 25, "马八"));
Collections.sort(li);
for (Person person : li) {
System.out.println(person);
}
}
}
3. Comparator实例
package com.yixun.cn;
public class Person1 {
private Integer id;
private Integer age;
private String name;
public Person1(Integer id, Integer age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
}
}
package com.yixun.cn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestDemo1 {
public static void main(String[] args) {
List<Person1> li = new ArrayList<Person1>();
li.add(new Person1(1, 21, "张三"));
li.add(new Person1(2, 22, "李四"));
li.add(new Person1(3, 23, "王五"));
li.add(new Person1(4, 24, "麻六"));
li.add(new Person1(7, 25, "赵七"));
li.add(new Person1(6, 25, "马八"));
Collections.sort(li, new Comparator<Person1>() {
@Override
public int compare(Person1 o1, Person1 o2) {
if (o1.getAge() == o2.getAge()) {
return o1.getId() - o2.getId();
} else {
return o1.getAge() - o2.getAge();
}
}
});
for (Person1 person1 : li) {
System.out.println(person1);
}
}
}
4. 两者区别
Comparable是内部比较器,Comparator是外部比较器,两者的适用场景有区别。如果是对自定义的类进行排序,这两个比较器都可以使用;如果是引入的第三方的jar中的类,由于这样的类不能被修改,要想对这样的类进行排序,那么必须使用Comparator接口来实现。