Sorting array of objects by field

前端 未结 5 1618
北恋
北恋 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:58

    You can implement the Comparable interface to make your class comparable. Make sure to override the compareTo method then.

    public class Person implements Comparable {
        String name;
        int age;
        float gradeAverage;
    
        @Override
        public int compareTo(Person p) {
            if(this.age < p.getAge()) return -1;
            if(this.age == p.getAge()) return 0;
            //if(this.age > p.getAge()) return 1;
            else return 1;
        }
    
        //also add a getter here
    }
    

提交回复
热议问题