深入浅出了解java比较器 区分Comparable与Comparator的差异以及对象数组的排序
程序员文章站
2022-05-24 18:14:45
...
比较器:
进行大小关系确定判断;
对象数组排序:
String的对象数组排序:
自定义类排序
Comparable对象接口
import java.util.Arrays;
class person implements Comparable<person>{
String name;
int age;
public person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "名字:"+this.name+"年龄:"+this.age;
}
@Override
public int compareTo(person o) {
// if(this.age<o.age) {
// return -1;
// }else if(this.age>o.age) {
// return 1;
// }
// return 0;
return this.age-o.age;
}
}
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
person data[]=new person[] {
new person("张一",2),
new person("张二",23),
new person("张三",14),
};
Arrays.sort(data);
// System.out.println(Arrays.toString(data));
for(person a:data) {
System.out.println(a);
}
}
}
基于comparator的比较器:
import java.util.Arrays;
import java.util.Comparator;
class PersonComparator implements Comparator<Person>{
@Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return o1.getAge()-o2.getAge();
}
}
class Person {
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "名字:"+this.name+"年龄:"+this.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;
}
}
public class test2 {
public static void main(String[] args) {
Person data[]=new Person[] {
new Person("张一",2),
new Person("张二",23),
new Person("张三",14),
};
Arrays.sort(data,new PersonComparator());
// System.out.println(Arrays.toString(data));
for(Person a:data) {
System.out.println(a);
}
}
}
挽救排序;
Comparable与comparator的区别:
Java.lang.Comparable是在类定义的时候实现的父接口,里面只有一个compareTo的方法;
Java.util.Comparator是挽救的比较器操作,需要单独的比较器规则类实现排序,里面有compare()方法