JAVA基础补充(Comparable排序接口的实现)
- Comparable接口的实现:
- 没有实现Comparable接口时,取出来的值无法排序
- 如果进行排序:
- 实现接口进行排序:
- Controller层的实现
- 实体类的实现
- 复习时间:
- 2023/08/12
Comparable接口的实现:
今天项目用到进行金额排序,之前学过的java基础有点忘记,补充一下
没有实现Comparable接口时,取出来的值无法排序
public static void main(String[] args) {
Good1[] arr1 = new Good1[5];
arr1[0] = new Good1("大哥",10.0);
arr1[1] = new Good1("二弟",40.0);
arr1[2] = new Good1("三弟",200.0);
arr1[3] = new Good1("四弟",900.0);
arr1[4] = new Good1("五弟",60.0);
System.out.println("====没有实现实现Comparab接口时输出====");
System.out.println(Arrays.asList(arr1));
}
运行得到的结果:
如果进行排序:
Good1[] arr1 = new Good1[5];
arr1[0] = new Good1("大哥",10.0);
arr1[1] = new Good1("二弟",40.0);
arr1[2] = new Good1("三弟",200.0);
arr1[3] = new Good1("四弟",900.0);
arr1[4] = new Good1("五弟",60.0);
Arrays.sort(arr1);
System.out.println("====没有实现实现Comparab接口时输出====");
System.out.println(Arrays.asList(arr1));
报错
实现接口进行排序:
Controller层的实现
public static void main(String[] args) {
Good[] arr = new Good[5];
arr[0] = new Good("大哥",10.0);
arr[1] = new Good("二弟",40.0);
arr[2] = new Good("三弟",200.0);
arr[3] = new Good("四弟",900.0);
arr[4] = new Good("五弟",60.0);
Arrays.sort(arr);
System.out.println("====实现Comparab接口时输出====");
System.out.println(Arrays.asList(arr));
}
实体类的实现
@Data
public class Good implements Comparable<Good>{
private String name;
private Double price;
public Good(String name, Double price) {
this.name = name;
this.price = price;
}
//重写比较方法
//如果当前对象大于形参对象,返回1
//如果当前对象小于形参对象。返回-1
//如果相等,返回0
@Override
public int compareTo(Good o) {
if (this.price>o.price)
return 1;
else if (this.price<o.price)
return -1;
else
return 0;
}
}
成功实现: