作者简介: zoro-1,目前大一,正在学习Java,数据结构等
作者主页: zoro-1的主页
欢迎大家点赞 收藏 ⭐ 加关注哦!
通过类实现Comparable<泛型>接口,重写compareTo方法,来进行比较
import java.util.Arrays;
class Car implements Comparable<Car>{
public int size=1;
public String name="pika";
public Car(int size, String name) {
this.size = size;
this.name = name;
}
@Override
public int compareTo(Car o) {
return this.size -o.size;
}
@Override
public String toString() {
return "Car{" +
"size=" + size +
", name='" + name + '\'' +
'}';
}
}
public class Text3 {
public static void compar(Car[] cars){
for(int i=0;i<cars.length;i++){
for(int j=0;j<cars.length-i-1;j++){
if(cars[j].compareTo(cars[j+1])>0){
Car temp=cars[j];
cars[j]=cars[j+1];
cars[j+1]=temp;
}
}
}
}
public static void main(String[] args) {
Car[] cars=new Car[3];
Car car = new Car(2, "aodi");
cars[0]=car;
Car car1 = new Car(3, "benchi");
cars[1]=car1;
Car car2=new Car(1,"fala");
cars[2]=car2;
compar(cars);
System.out.println(Arrays.toString(cars));
}
}
代码解读:
Car类继承Comparable<泛型>,泛型就是要进行比较的类,
重写compareTo方法,方法的参数是要和当前引用的对象比较的对象,
返回this.size -o.size,本类中的size减去比较的对象的size,大于返回正数,小于返回负数,相等返回0;
在类外创一个新的类实现Comparator<泛型>接口,重写compare方法,来进行比较
import java.util.Arrays;
import java.util.Comparator;
class Car implements Comparable<Car>{
public int size=1;
public String name="pika";
public Car(int size, String name) {
this.size = size;
this.name = name;
}
@Override
public int compareTo(Car o) {
return this.size -o.size;
}
@Override
public String toString() {
return "Car{" +
"size=" + size +
", name='" + name + '\'' +
'}';
}
}
class sizecompare implements Comparator<Car>{
@Override
public int compare(Car o1, Car o2) {
return o1.size-o2.size;
}
}
class namecompare implements Comparator<Car>{
@Override
public int compare(Car o1, Car o2) {
return o2.name.compareTo(o1.name);
}
}
public class Text3 {
public static void main(String[] args) {
Car[] cars=new Car[3];
Car car = new Car(2, "aodi");
cars[0]=car;
Car car1 = new Car(3, "benchi");
cars[1]=car1;
Car car2=new Car(1,"fala");
cars[2]=car2;
//sizecompare sizecompare=new sizecompare();
//Arrays.sort(cars,sizecompare);
namecompare namecompare=new namecompare();
Arrays.sort(cars,namecompare);
System.out.println(Arrays.toString(cars));
}
}
代码解读:
在类外面创建两个比较器类sizecompare,namecompare,一个比较size,一个比较name,实现Comparator,重写compare方法,他的两个参数是连着的两个对象,返回值如果是前一个减后一个是升序,后一个减前一个是降序,然后将比较器实例化,当做参数传入Arrays类的第二个参数,形参用Comparator<泛型>来接收,发生了向下转型