I have objects
Person{
String name;
int age;
float gradeAverage;
}
Is there an easy way to sort
Person[]
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 ;
}
}