对象比较器
1.先说Arrays.sort快排常见
- 比较数字从小到大
<span style="font-size:18px;"> int[] nums = {12,32,44,5,4,65}; Arrays.sort(nums); for (int i : nums) { System.out.println(i); }</span>
- sort也可以用来排列字符型数组(按字典序排序)
String[] names = {"abc","vince","java","com","tom"}; Arrays.sort(names); for (String string : names){ System.out.println(string); }
2.如果要用sort比较自己定义的类
- 比如用自己定义的类Cat Arrays.sort(Cat);报错!
产生错误的原因差api知
Comparable没有Cat自定义类实现
代码实现:
所以Cat函数要这样写 用comparato函数比较大于返回1小于返回-1等于返回0;
<span style="font-size:18px;">package com.vince;
public class Cat implements Comparable<Cat>{
// 告诉其所要对比的对象
private String name;
private int age;
//应用快捷键shift+Alt+s或 鼠标右键-->源码
public Cat() {}
public Cat(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Cat [name=" + name + ", age=" + age + "]";
}
<span style="color:#ff0000;">//通过此方法实现对象的比较
@Override
public int compareTo(Cat o) {
if(this.age<o.age){
return -1;
}
else if (this.age>o.age){
return 1;
}
else{
return 0;
}
}</span>
}</span>
然后可以直接使用Arrays.sort(Cat)排序
//类不能被sort的接收(Cat 不能转化为Comparable接口)
Cat[] cats = {new Cat("Tom",2),new Cat("GG",4),new Cat("Wg",3),
new Cat("Bi",8),new Cat("DD",5)};
Arrays.sort(cats);
for (Cat cat : cats) {
System.out.println(cat);
}
输出结果
自定义比较类型用comparator(比较器)
假如类已经定义好了,不能再去修改它:
<span style="font-size:18px;">package com.vince;
public class Dog {
private String name;
private int age;
public Dog(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog [name=" + name + ", age=" + age + "]";
}
}</span>
Comparator可以比较灵活的比较对象中的属性
<span style="font-size:18px;">package com.vince;
import java.util.Comparator;
public class DogComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
if (o1.getAge()<o2.getAge()){
return -1;
}
else if (o1.getAge()>o2.getAge()){
return 1;
}
return 0;
}
</span>
}
所以要用sort比较时要告诉sort函数比较器
<span style="font-size:18px;"> //类不能被sort的接收(Dog 重新写comparator写比较的属性)
Dog[] dogs = {new Dog("Tom",2),new Dog("GG",4),new Dog("Wg",3),
new Dog("Bi",8),new Dog("DD",5)};
Arrays.sort(dogs,new DogComparator());//比较类内的属性用重写DogComparable
for (Dog dog : dogs) {
System.out.println(dog);
}</span>
输出结果和Cat一样