Sorting array of objects by field

前端 未结 5 1662
北恋
北恋 2021-01-19 16:12

I have objects

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

Is there an easy way to sort

Person[]         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-19 16:59

    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
        }
    }
    

    However implementing Comparable is the convenient way

    class Person implements Comparable {
        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 ;
        }
    }
    

    You can check Comparable documentation also

提交回复
热议问题