Java笔记12:Java对象排序
代码:
- import java.util.Arrays;
- import java.util.Comparator;
- class Person {
- private String name;
- private int age;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return this.name;
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- }
- public class MyObjSort {
- public static void main(String[] args) {
- Person[] persons = {new Person("Zhang San",30), new Person("Chen Er",20), new Person("Liu Yi",10)};
- Arrays.sort (persons, new Comparator<Person>() {
- @Override
- public int compare(Person p1, Person p2) {
- if (p1.getAge() > p2.getAge()) {
- return 1;
- } else if (p1.getAge() < p2.getAge()) {
- return -1;
- } else {
- return 0;
- }
- }
- });
- for(int i = 0; i < persons.length; i++) {
- System.out.println(persons[i].getName() + " " + persons[i].getAge());
- }
- }
- }
运行结果:
Liu Yi 10
Chen Er 20
Zhang San 30
学习时的痛苦是暂时的 未学到的痛苦是终生的