java 重写compareTo方法实现类自定义排序

废话不多说,贴上代码!!!

package com.xxxxxx.xxxxxx.xxxxxx;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Person implements Comparable {

    private String name;
    private int age;
    private int money;


    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 int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

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

    @Override
    public String toString() {
        return name + "=" + age + "=" + money;
    }

    @Override
    public int compareTo(Person o) {
        if ((this.money + this.age) - (o.getMoney() + o.getAge()) > 0) {
            return 1;
        } else {
            return -1;
        }
    }


    public static void main(String[] args) {
        Person p1 = new Person("a", 10, 10);
        Person p2 = new Person("b", 20, 20);
        Person p3 = new Person("c", 100, 100);
        Person p4 = new Person("d", 50, 50);
        Person p5 = new Person("e", 30, 30);
        List p = new ArrayList<>();
        p.add(p1);
        p.add(p2);
        p.add(p3);
        p.add(p4);
        p.add(p5);
        Collections.sort(p);
        p.forEach(param -> {
            System.out.println(param);
        });


    }

}

效果图:

java 重写compareTo方法实现类自定义排序_第1张图片

最后我觉得还是用内部类的方式方便一点,平时简单的排序 使用lambda的排序也够用了!

你可能感兴趣的:(java,compareTo)