按字段排序对象数组 [英] Sorting array of objects by field

查看:92
本文介绍了按字段排序对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有东西

Person{
    String name;  
    int age;
    float gradeAverage;
    }

是否有一种简便的方法

Person[] ArrayOfPersons

按年龄?

我必须使用Comparable或Comparator吗?我不完全了解他们.

Do I have to use Comparable or Comparator? I don't fully understand them.

推荐答案

您可以在循环中使用吸气剂检查年龄

You can check for age using a getter in your loop

for (int i = 0 ; i < persons.length - 1; i++) {
    Person p = persons[i];
    Person next =  persons[i+1];
    if(p.getAge() > next.getAge()) {
        // Swap
    }
}

但是实现Comparable是便捷的方法

However implementing Comparable is the convenient way

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

    public int compareTo(Person other) {
        if(this.getAge() > other.getAge())
            return 1;
        else if (this.getAge() == other.getAge())
            return 0 ;
        return -1 ;
    }

    public int getAge() {
        return this.age ;
    }
}

您可以检查 Comparable 文档也

You can check Comparable documentation also

这篇关于按字段排序对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆