Comparable和Compartor的区别
Posted i-tao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Comparable和Compartor的区别相关的知识,希望对你有一定的参考价值。
1.List对象实现Comparable接口,使对象具备可比性
package tao; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Student1 implements Comparable<Student1> { private String name; private Integer age; public Student1(String name, Integer age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int compareTo(Student1 o) { // TODO Auto-generated method stub return this.getAge().compareTo(o.getAge()); } // 测试方法 public static void main(String[] args) { List<Student1> list = new ArrayList<Student1>(); Student1 s1 = new Student1("lisi1",19); Student1 s2 = new Student1("lisi3",17); Student1 s3 = new Student1("lisi2",20); list.add(s1); list.add(s2); list.add(s3); Collections.sort(list); for(Student1 s : list){ System.out.println("name:"+s.getName()+" age:"+s.getAge()); } } }
排序结果 name:lisi3 age:17 name:lisi1 age:19 name:lisi2 age:20
2.List对象不具备可比性,或者对象本身可比性不是想要的排序规则,通过Comparator外部比较
package tao; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Student2 { private String name; private Integer age; public Student2(String name, Integer age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } // 测试方法 public static void main(String[] args) { List<Student2> list = new ArrayList<Student2>(); Student2 s1 = new Student2("lisi1",19); Student2 s2 = new Student2("lisi3",17); Student2 s3 = new Student2("lisi2",20); list.add(s1); list.add(s2); list.add(s3); Collections.sort(list,new MyCompare()); for(Student2 s : list){ System.out.println("name:"+s.getName()+" age:"+s.getAge()); } } } class MyCompare implements Comparator<Object> { @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub Student2 s1 = (Student2)o1; Student2 s2 = (Student2)o2; return s1.getAge().compareTo(s2.getAge()); } }
排序结果 name:lisi3 age:17 name:lisi1 age:19 name:lisi2 age:20
3.Comparable和Compartor的区别
a.出处不同
java.util.Comparator;
java.lang.Comparable;
b.提供方法不同
Comparator提供int compare(Object o1, Object o2)
Comparable提供int compareTo(Object o)
c.内外部区别
Comparator提供外部对比
Comparable提供对象自身对比
以上是关于Comparable和Compartor的区别的主要内容,如果未能解决你的问题,请参考以下文章
java中Comparator 和 Comparable的区别
Java中Comparable和Comparator接口区别分析