Comparator
–外部比较器
–配合Collections工具类的sort(Listlist,Comparator c)方法使用。
–当集合中的对象不支持自比较或者自比较的功能不能满足需求时使用
和内部比较器相比,其可重用性好
package compare;
public class Student {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "学号为:"+id+"~~~姓名为:"+name;
}
}
package compare;
import java.util.Comparator;
public class IdComparator implements Comparator<Student>{
@Override
public int compare(Student student1, Student student2) {
return student1.id - student2.id;
}
}
package compare;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class ComparatorTest {
public static void main(String[] args) {
List<Student> studentList = new LinkedList<Student>();
studentList.add(new Student(1,"张三"));
studentList.add(new Student(2,"李四"));
studentList.add(new Student(3,"王五"));
Collections.sort(studentList, new IdComparator());
for(Student student : studentList){
System.out.println(student);
}
}
}
Comparable接口
–String和各种包装类已经实现了Comparable接口
–TreeSet集合内默认是按照自然顺序排序的
–在集合内元素之间的比较,由该类的compareTo(Objecto)方法来完成,因为这种比较是在类内部实现,所以将Comparable称为内部比较器
package compare;
import java.util.LinkedList;
import java.util.List;
public class Teacher implements Comparable<Teacher> {
int id;
String name;
public Teacher(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "工号为:"+id+"~~~姓名为:"+name;
}
@Override
public int compareTo(Teacher teacher) {
if(this.id<teacher.id){
return -1;
}else if(this.id==teacher.id){
return 0;
}else{
return 1;
}
}
public static void main(String[] args) {
List<Teacher> teacherList = new LinkedList<Teacher>();
teacherList.add(new Teacher(1,"三三"));
teacherList.add(new Teacher(2,"四四"));
teacherList.add(new Teacher(3,"五五"));
System.out.println(new Teacher(1,"三三").compareTo(new Teacher(1,"三三")));
}
}