Java中对对象进行排序

1,首先创建一个类

class Person3{
	private String name;
	private int age;
	private double score;
	
	public Person3(String name, int age, double score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}
	
	@Override
	public String toString() {
		return "Person3 [name=" + name + ", age=" + age + ", score=" + score
				+ "]";
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}

	
	
}

这个时候再产生这个类的对象,将对象存入数组里,并对这个数组进行排序

public class Test17 {
	public static void main(String[] args) {
		Person3[] array = new Person3[3];
		array[0] = new Person3("caocao",18,29);
		array[1] = new Person3("liubei",20,49);
		array[2] = new Person3("guanyu",21,77);		
		//对这个数组排序
		Arrays.sort(array);
		System.out.println(Arrays.toString(array));
	
	}
}

我们会发现运行结果出现了异常


因为你并不知道应该是依照这个对象的什么属性进行排序

因此我们需要去重写一个compareTo方法,重写这个方法的时候应该要继承一个接口Comparable。

查看这个接口的源码

public interface Comparable<T> {
    /**
     * Compares this object with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     *
     * <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
     * -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This
     * implies that <tt>x.compareTo(y)</tt> must throw an exception iff
     * <tt>y.compareTo(x)</tt> throws an exception.)
     *
     * <p>The implementor must also ensure that the relation is transitive:
     * <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies
     * <tt>x.compareTo(z)>0</tt>.
     *
     * <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
     * implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
     * all <tt>z</tt>.
     *
     * <p>It is strongly recommended, but <i>not</i> strictly required that
     * <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>.  Generally speaking, any
     * class that implements the <tt>Comparable</tt> interface and violates
     * this condition should clearly indicate this fact.  The recommended
     * language is "Note: this class has a natural ordering that is
     * inconsistent with equals."
     *
     * <p>In the foregoing description, the notation
     * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
     * <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
     * <tt>0</tt>, or <tt>1</tt> according to whether the value of
     * <i>expression</i> is negative, zero or positive.
     *
     * @param   o the object to be compared.
     * @return  a negative integer, zero, or a positive integer as this object
     *          is less than, equal to, or greater than the specified object.
     *
     * @throws NullPointerException if the specified object is null
     * @throws ClassCastException if the specified object's type prevents it
     *         from being compared to this object.
     */
    public int compareTo(T o);
}

接下来我们来重写这个方法,并使通过年龄来排序

class Person3 implements Comparable<Person3>{
	private String name;
	private int age;
	private double score;
	
	public Person3(String name, int age, double score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}
	
	@Override
	public String toString() {
		return "Person3 [name=" + name + ", age=" + age + ", score=" + score
				+ "]";
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}

	@Override
	public int compareTo(Person3 o) {
		// TODO Auto-generated method stub
		return age-o.age;
	}
}

分别通过姓名和成绩



但是这样写的话我们会发现每次想要改一下比较什么比较麻烦

于是我们改用这个方法来实现

Arrays.sort(array, new Comparator<Person3>(){
			//传入的时候由用户自己选
			@Override
			public int compare(Person3 o1, Person3 o2) {
				// TODO Auto-generated method stub
				int age1 = o1.getAge();
				int age2 = o2.getAge();
				return age1 > age2 ? age1:(age1==age2) ? 0:-1;
				
			}
		});
Comparator是一个接口,这个是使用这个接口实现了一个匿名内部类,在里面重写compare方法,来用来比较这个对象
  • 10
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
可以使用Comparator接口来对List对象的属性进行排序,具体步骤如下: 1. 定义一个实现了Comparator接口的类,重写compare方法,在方法比较两个对象的属性值,返回一个int值,表示比较结果。 例如,对一个Person类的年龄进行排序,可以定义一个AgeComparator类: ``` public class AgeComparator implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getAge() - p2.getAge(); } } ``` 2. 在需要排序的代码,调用Collections.sort方法,并将Comparator对象作为参数传入。 例如,对一个List<Person> list进行年龄排序,可以这样写: ``` Collections.sort(list, new AgeComparator()); ``` 完整示例代码: ``` import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Main { public static void main(String[] args) { List<Person> list = new ArrayList<>(); list.add(new Person("Tom", 20)); list.add(new Person("Jerry", 18)); list.add(new Person("Mike", 25)); list.add(new Person("Alice", 22)); Collections.sort(list, new AgeComparator()); for (Person p : list) { System.out.println(p.getName() + " " + p.getAge()); } } static class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } static class AgeComparator implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getAge() - p2.getAge(); } } } ``` 输出结果: ``` Jerry 18 Tom 20 Alice 22 Mike 25 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值