集合比较器:
java的比较器有两类,分别是Comparable接口和Comparator接口。Comparable是排序接口,若一个类实现了Comparable接口,就意味着
该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。
让需要进行排序的对象实现Comparable接口,重写其中的compareTo(To)方法,在其中定义排序规则,那么就可以直接调用
java.util.Arrays.sort()来排序对象数组
应用:
为字符串、对象等无法直接比较大小排序的对象提供比较逻辑,进而实现排序。或者按自己需要的逻辑进行排序。
示例:
输入学生学号,姓名,性别,并按学号排序
首先创建Student类:
/**
* 调用一个接口,接口的对象是对Student进行比较,
* 比较是比较code,而不是其他的东西,所以要调用。
*/
public class Student implements Comparable{
private int Code;
private String Name;
private String Sex;
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
@Override
public String toString() {
return "Student{" +
"Code=" + Code +
", Name='" + Name + '\'' +
", Sex='" + Sex + '\'' +
'}';
}
public Student(int code , String name, String sex) {
this.Code = code;
this.Name = name;
this.Sex = sex;
}
/**
*
*
*这是一个接口,对应于Comparable,也就是方法的接口,Student要进行比较是
*比较它的code,所以要调用这个接口来比较。
*
* */
public int compareTo(Object o){
if(o instanceof Student){
Student s = (Student) o;
if(this.getCode () > s.getCode ()) return 1;
else if(this.getCode () < s.getCode ()) return -1;
return 0;
}
throw new RuntimeException("类型不对,无法匹配");
}
}
接下来运用比较器进行比较:
import java.util.*;
public class TestColections {
public static void main(String[] args) {
LinkedHashSet a = new LinkedHashSet();
List s = new ArrayList ();
s.add (new Student (1001, "路飞", "M"));
s.add (new Student (1030, "明哥", "M"));
s.add (new Student (1002, "娜美", "W"));
s.add (new Student (1010, "卡二", "M"));
s.add (new Student (1008, "女帝", "W"));
System.out.println ("原顺序");
System.out.println (s);
class Rule implements Comparator {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Student && o2 instanceof Student) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if (s1.getCode () > s2.getCode ()) return 1;
if (s1.getCode () < s2.getCode ()) return -1;
return 0;
}
throw new RuntimeException ("必须是Student类型");
}
}
Rule r = new Rule ();
System.out.println ("排序列:");
Collections.sort (s, new Rule ());
System.out.println (s);
}
}
在上面的程序中,实现了Comparable接口,并重写了compareTo方法。
输出:
原顺序
[Student{Code=1001, Name='路飞', Sex='M'}, Student{Code=1030, Name='明哥', Sex='M'}, Student{Code=1002, Name='娜美', Sex='W'}, Student{Code=1010, Name='卡二', Sex='M'}, Student{Code=1008, Name='女帝', Sex='W'}]
排序列:
[Student{Code=1001, Name='路飞', Sex='M'}, Student{Code=1002, Name='娜美', Sex='W'}, Student{Code=1008, Name='女帝', Sex='W'}, Student{Code=1010, Name='卡二', Sex='M'}, Student{Code=1030, Name='明哥', Sex='M'}]