自定义对象中sort函数的使用——JAVA

本文详细介绍了在Java中如何对自定义对象进行排序,包括实现Comparable接口和使用Comparator接口两种方法。通过具体示例,展示了如何根据对象的多个属性进行排序,如姓名和年龄。

方法一:

在自定义对象中使用comparable接口,并且定义compareTo()方法。

返回1 <返回-1 =返回0(若需要反序则>返回-1 <返回1 =返回0)

方法二:

新建Comparator类,在该类中实现compare()方法

返回1 <返回-1 =返回0(若需要反序则>返回-1 <返回1 =返回0)
然后再sort函数中调用Comparator类

方法一样例

import java.util.Arrays;

public class Person implements Comparable<Person> {
	String name;
	int age;

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public int compareTo(Person another) {
		int i = 0;
		i = name.compareTo(another.name); // 使用字符串的比较
		if (i == 0) {
			// 如果名字一样,比较年龄, 返回比较年龄结果
			return age - another.age;
		} else {
			return i; // 名字不一样, 返回比较名字的结果.
		}
	}

	public static void main(String... a) {
		Person[] ps = new Person[3];
		ps[0] = new Person("Tom", 20);
		ps[1] = new Person("Mike", 18);
		ps[2] = new Person("Mike", 20);

		Arrays.sort(ps);
		for (Person p : ps) {
			System.out.println(p.getName() + "," + p.getAge());
		}
	}
}

方法二样例:


public class Person2 {
	private String name;
    private int age;
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}

    public Person2(String name, int age)
    {
    	this.name = name;
    	this.age = age;
    }
}

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

public class Person2Comparator  implements Comparator<Person2> {
	public int compare(Person2 one, Person2 another) {
		int i = 0;
		i = one.getName().compareTo(another.getName());
		if (i == 0) {
			// 如果名字一样,比较年龄,返回比较年龄结果
			return one.getAge() - another.getAge();
		} else {
			return i; // 名字不一样, 返回比较名字的结果.
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person2[] ps = new Person2[3];
		ps[0] = new Person2("Tom", 20);
		ps[1] = new Person2("Mike", 18);
		ps[2] = new Person2("Mike", 20);

		Arrays.sort(ps, new Person2Comparator());
		for (Person2 p : ps) {
			System.out.println(p.getName() + "," + p.getAge());
		}
	}
}

参考中国大学mooc——《java核心技术》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值