JAVA----对象数组排序

1.利用Comparable接口实现(用的多)

JAVA中对象数组排序需要实现Comparable接口
该接口位于java.lang包下

public interface Comparable<T>

是一个泛型接口,包含一个方法

int compareTo(T o)
//return 负数,表示当前对象小于特定对象o
//return 0,表示当前对象等于特定对象o
//return 正数,表示当前对象大于特定对象

例如:

class Student implements Comparable<Student>{
    private int ID;
    private String name;
    public Student(int ID,String name) {
        this.ID = ID;
        this.name = name;
    }
    public int compareTo(Student o) {
        if(this.ID>o.ID) {
            return 1;
        }else if(this.ID<o.ID){
            return -1;
        }
        else if(this.ID ==o.ID){
            return 0;
        }
        return 0;
    }
    public String toString() {
        return "Student [ID=" + ID + ", name=" + name + "]\n";
    }
}

public class Run {
    public static void main(String[] args) {
        Student [] stu = new Student [] {
                new Student(123,"王老吉"),
                new Student(126,"加多宝"),
                new Student(125,"哇哈哈")};
        Arrays.sort(stu);        //对Student数组进行排序
        System.out.println(Arrays.toString(stu));//关于toString方法可以参考源码
    }   
}

输出:

[Student [ID=123, name=王老吉]
, Student [ID=125, name=哇哈哈]
, Student [ID=126, name=加多宝]
]

结果按ID升序排列,如果想按降序排列,将compareTo方法里面正负数对调即可。

2.利用Comparator接口实现(使用不多)

java.util包下的Comparator接口

@FuntionalInterface
public interface Comparator<T>

该接口有许多静态方法与普通方法
抽象方法:

int compare(T o1, T o2)

return 正数表示o1>o2,
return 负数表示o1

//比较的定义
class StudentCompare implements Comparator<Student>{
    public int compare(Student o1, Student o2) {
        if(o1.getID()>o2.getID()) {
            return 1;
        }else if(o1.getID()<o2.getID()) {
            return -1;
        }
        return 0;
    }
}
class Student {
    private int ID;
    private String name;
    public Student(int ID,String name) {
        this.ID = ID;
        this.name = name;
    }
    public int getID() {
        return this.ID;
    }
    public String toString() {
        return "Student [ID=" + ID + ", name=" + name + "]\n";
    }
}

public class Run {
    public static void main(String[] args) {
        Student [] stu = new Student [] {
                new Student(123,"王老吉"),
                new Student(126,"加多宝"),
                new Student(125,"哇哈哈")};
        //调用的还是Arrays的方法,这里也可以用Lambda表达式来写比较规则      
        Arrays.sort(stu,new StudentCompare());
        System.out.println(Arrays.toString(stu));
    }   
}

输出:

[Student [ID=123, name=王老吉]
, Student [ID=125, name=哇哈哈]
, Student [ID=126, name=加多宝]
]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值