1. java.util.Comparator的声明:
public interface Comparator<T>
{
public abstract boolean equals(Object obj);
public abstract int compare(T cobj1, T cobj2);
}
public interface Comparator<T>
{
public abstract boolean equals(Object obj);
public abstract int compare(T cobj1, T cobj2);
}2. 比较器Comparator主要用于自己定义一种比较方式,如创建一个Student的数组,那它排序时是按年龄还是姓名呢。
import java.io.*;
import java.util.*;
class CompareName implements Comparator <Student>{
public int compare(Student arg0, Student arg1) {
return arg0.name.compareTo(arg1.name);//调用String的compareTo()
}
}
class CompareAge implements Comparator <Student>{
public int compare(Student arg0, Student arg1) {
return arg0.age>arg1.age?1:-1;
}
}
class Student{
String name;
int age;
Student(String name, int age)
{
this.name =name;
this.age = age;
}
}
public class Test{
public static void main(String[] args)
{
Student std[] ={new Student("a",33),new Student("b",20)};
Arrays.sort(std, new CompareAge()); //按年龄排序
//Arrays.sort(std, new CompareName()); //按姓名排序
System.out.println(std[0].name+" "+std[1].name);
}
}
import java.io.*;
import java.util.*;
class CompareName implements Comparator <Student>{
public int compare(Student arg0, Student arg1) {
return arg0.name.compareTo(arg1.name);//调用String的compareTo()
}
}
class CompareAge implements Comparator <Student>{
public int compare(Student arg0, Student arg1) {
return arg0.age>arg1.age?1:-1;
}
}
class Student{
String name;
int age;
Student(String name, int age)
{
this.name =name;
this.age = age;
}
}
public class Test{
public static void main(String[] args)
{
Student std[] ={new Student("a",33),new Student("b",20)};
Arrays.sort(std, new CompareAge()); //按年龄排序
//Arrays.sort(std, new CompareName()); //按姓名排序
System.out.println(std[0].name+" "+std[1].name);
}
}3. 按年龄排序结果为 a b
按年龄排序结果为 b a
4. comparable 接口用于在定义类时就直接定义了比较该类的方法(compareTo())。
class Student implements Comparable<Student>{
String name;
int age;
Student(String name, int age)
{
this.name =name;
this.age = age;
}
public int compareTo(Student st) {
return this.age>st.age?1:(this.age==st.age?0:-1);
}
}
public class Test{
public static void main(String[] args)
{
Student std[] ={new Student("a",33),new Student("b",20)};
Arrays.sort(std); //按年龄排序
System.out.println(std[0].name+" "+std[1].name);
}
}输出:b a
使用Arrays 的sort()方法排序,默认升序
本文介绍了Java中使用Comparator接口和Comparable接口进行自定义排序的方法。通过示例代码展示了如何实现按姓名或年龄对Student对象数组进行排序,以及如何在类定义时实现比较方法。
1079

被折叠的 条评论
为什么被折叠?



