【Java】对象数组按照某属性排序

本文介绍了如何使用Java的Comparable接口和Comparator匿名内部类对对象数组按属性进行排序,包括实现Comparable接口的步骤和Comparator的使用实例,适用于自定义类的排序需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候需要对对象列表或数组进行排序,下面提供两种简单方式:

方法一、将要排序的对象类实现< Comparable >接口。

要排序就要有比较的方法, 因为是自定义的类, 系统不知道怎么做两个自定义类的比较,

所以我们要自己在类内写两个类的比较的方法,也就是告诉按照那个属性或者那种方式来给对象数组排序

自定义比较算法也就是实现Comparable接口:(会自动生成需要自己写的方法如下图)

public class Good implements Comparable<Good>
{
	String name;
	int price;
	public Good(String name,int price) 
	{
		this.name=name;
		this.price=price;
	}
	@Override
	public int compareTo(Good good) {
		// TODO Auto-generated method stub
		return this.price-good.price;
	}
	
}

调用Collections.sort();

public static void main(String[] args) 
	{
		 ArrayList<Good> goods = new ArrayList<Good>();
		 goods.add(new Good("二", 2));
		 goods.add(new Good("三", 3));
		 goods.add(new Good("一", 1));
		 
		 System.out.println("排序前:");
	     for (Good good : goods)
	         System.out.println("姓名:"+good.name+" 价格:"+good.price);
	     
	     Collections.sort(goods);
	     
	     System.out.println("排序后:");
	     for (Good good : goods)
	         System.out.println("姓名:"+good.name+" 价格:"+good.price);
	}

方法二:使用Comparator匿名内部类实现。

class Student {

    String name;
    int age;
    int score;

    public Student(String name, int age,int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
}
public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("大铭", 19, 89));
        students.add(new Student("来福", 26, 90));
        students.add(new Student("仓颉", 23, 70));
        students.add(new Student("王磊", 18, 80));

        System.out.println("排序前:");
        for (Student student : students) {
            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
        }

        Collections.sort(students,new Comparator<Student>() {

            @Override
            public int compare(Student o1, Student o2) {
                // TODO Auto-generated method stub
                return o1.age-o2.age;
            }
        });

        System.out.println("排序后:");
        for (Student student : students) {
            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);
        }
    }
}

本文参考:
Java对对象按照其属性排序的两种方法

Java对象数组按照其属性排序的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值