Sorting array of objects by field

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

    import java.util.Arrays;
    
    public class PersonCompare {
    
    public static void main(String[] args) {
        Person p1 = new Person("Test1",10);
        Person p2 = new Person("Test2",12);
        Person p3 = new Person("Test3",4);
        Person p4 = new Person("Test4",7);
    
        Person[] ArrayOfPersons = {p1,p2,p3,p4};
        Arrays.sort(ArrayOfPersons);
    
        for(Person p: ArrayOfPersons) {
            System.out.println(p.getName()+"--"+p.getAge());
        }
    }
    }
    
    
    class Person implements Comparable {
    String name;
    int age;
    
    Person(String name, int age){
        this.name=name; this.age=age;
    
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    
    @Override
    public int compareTo(Person other) {
        if(this.getAge() > other.getAge())
            return 1;
        else if (this.getAge() == other.getAge())
            return 0 ;
        return -1 ;
    }
    }
    

提交回复
热议问题