数组里面存person,然后按照年龄排序

 1 package com.pang.array_demo;
 2 
 3 public class Person {
 4 
 5     String name;
 6     int age;
 7     String sex;
 8     //空差构造
 9     //满参构造
10     //get/set方法
11     //toString方法    
12 }
 1 package com.pang.array_demo;
 2 
 3 import java.util.Arrays;
 4 
 5 //数组里面存放person,然后按照年龄排序
 6 public class Test {
 7     public static void main(String[] args) {
 8 
 9         Person[] arr = new Person[4];
10         arr[0] = new Person("张三", 12, "男");
11         arr[1] = new Person("李四", 4, "男");
12         arr[2] = new Person("王五", 34, "男");
13         arr[3] = new Person("赵六", 22, "男");
14         ageSort(arr);
15     }
16 
17     // 选择排序
18     public static void ageSort(Person[] arr) {
19         for (int i = 0; i < arr.length - 1; i++) {
20             for (int j = i + 1; j < arr.length; j++) {
21                 if (arr[i].getAge() > arr[j].getAge()) {
22                     Person p = arr[i];
23                     arr[i] = arr[j];
24                     arr[j] = p;
25                 }
26             }
27         }
28         System.out.println(Arrays.toString(arr));
29     }
30 }

 

[Person [name=李四, age=4, sex=男], Person [name=张三, age=12, sex=男], Person [name=赵六, age=22, sex=男], Person [name=王五, age=34, sex=男]]

posted @ 2017-06-16 17:28  更好遇见你  阅读(653)  评论(0编辑  收藏  举报