Sorting array of objects by field

前端 未结 5 1616
北恋
北恋 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 17:09

    Yes just implement the Comparable interface.

    Here's an example :

    class Person implements Comparable {
        public int age;
        public String name;
    
        public int compareTo(Person other){
            return this.age == other.age ? 0 : this.age > other.age ? 1 : -1;
        }
    }
    

提交回复
热议问题