本节讨论两个问题:
- 字符串数组的排序
- 自定义类的排序
1.实现字符串数组的排序
public class TestSort1 { public static void main(String[] args) { String[] strs=new String[] {"zhangsan","lisi","wangwu","zhaosi"}; Arrays.sort(strs); System.out.print(Arrays.toString(strs)); } }
输出结果:按照首字母的字典顺序排序。
[lisi, wangwu, zhangsan, zhaosi
2.实现自定义类的排序
创建自定义类:
public class Employee1{ private String name; private double salary; public Employee1(String name,Double salary) { this.name=name; this.salary=salary; } public String getName() { return name; } public double getSalary() { return salary; } public void raiseSalary(double byPercent){ double raise=salary*byPercent/100; salary+=raise; } @Override public String toString() { return "Employee1 [name=" + name + ", salary=" + salary + "]"; } }
测试:
public class TestSort { public static void main(String[] args) { Employee1[] e1=new Employee1[3]; e1[0]=new Employee1("zhangsan",5000.0); e1[1]=new Employee1("lisi",6000.0); e1[2]=new Employee1("wangwu",7500.0); Arrays.sort(e1); System.out.print(Arrays.toString(e1)); } }
这样写完代码,编译器没有报错,但是一运行:
java.lang.ClassCastException
改进操作:
自定义的类要去implements Comparable接口,并定义接口中的方法
public class Employee1 implements Comparable<Employee1>{ //为泛型Comparable提供参数 private String name; private double salary; public Employee1(String name,Double salary) { this.name=name; this.salary=salary; } public String getName() { return name; } public double getSalary() { return salary; } public void raiseSalary(double byPercent){ double raise=salary*byPercent/100; salary+=raise; } @Override public String toString() { return "Employee1 [name=" + name + ", salary=" + salary + "]"; } @Override public int compareTo(Employee1 o) { return Double.compare(o.salary,salary); } }
结果:
[Employee1 [name=wangwu, salary=7500.0], Employee1 [name=lisi, salary=6000.0], Employee1 [name=zhangsan, salary=5000.0]] 按照salary从高到低排布。
结论:要想使用Arrays.sort(),定义的类要去implements Comparable接口,实际上String类也都 implements Comparable接口。