java对象排序

对象类

package com.lf.java.basic.interfaces;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Student implements Comparable<Student>,Cloneable{
    private String name;
    private int age;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student s) {
        return Integer.compare(s.getAge(),age);
    }

}

排序测试

package com.lf.java.basic.interfaces;

import java.util.Arrays;
import java.util.Comparator;

public class StudentArrayDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Student[] students = new Student[10];

        int i = 0;
        while (i < 10) {
            Student student = new Student();
//            Object clone = student.clone();
//            if(clone instanceof Student){
//                Student cloneStudent = (Student)clone;
//            }
            student.setAge(i);
            student.setName("张" + i);
            students[i] = student;
            i++;
        }
        Arrays.sort(students);//基于Comparable接口排序
        Arrays.sort(students,(o1, o2) -> o2.getAge()-o1.getAge());//逆序
        Arrays.sort(students, Comparator.comparingInt(Student::getAge));//顺序
        for (Student s : students) {
            System.out.println(s.toString());

        }
    }
}

输出

Student{name=‘张0’, age=0}
Student{name=‘张1’, age=1}
Student{name=‘张2’, age=2}
Student{name=‘张3’, age=3}
Student{name=‘张4’, age=4}
Student{name=‘张5’, age=5}
Student{name=‘张6’, age=6}
Student{name=‘张7’, age=7}
Student{name=‘张8’, age=8}
Student{name=‘张9’, age=9}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值