接口之Comparable
Posted liu-chen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了接口之Comparable相关的知识,希望对你有一定的参考价值。
本节讨论两个问题:
- 字符串数组的排序
- 自定义类的排序
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接口。
以上是关于接口之Comparable的主要内容,如果未能解决你的问题,请参考以下文章
Collection集合之六大接口(CollectionSetListMapIterator和Comparable)
Java基础之Comparable接口, Collections类,Iterator接口,泛型(Generic)
Collection集合之六大接口(CollectionSetListMapIterator和Comparable)
Java之集合初探Iterator(迭代器),collections,打包/解包(装箱拆箱),泛型(Generic),comparable接口