• Java笔记12:Java对象排序


    代码:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. import java.util.Arrays;  
    2. import java.util.Comparator;  
    3.   
    4. class Person {  
    5.     private String name;  
    6.     private int age;  
    7.       
    8.     public int getAge() {  
    9.         return age;  
    10.     }  
    11.   
    12.     public void setAge(int age) {  
    13.         this.age = age;  
    14.     }  
    15.   
    16.     public void setName(String name) {  
    17.         this.name = name;  
    18.     }  
    19.       
    20.     public String getName() {  
    21.         return this.name;  
    22.     }  
    23.       
    24.     public Person(String name, int age) {  
    25.         this.name = name;  
    26.         this.age = age;  
    27.     }  
    28. }  
    29.   
    30. public class MyObjSort {  
    31.     public static void main(String[] args) {  
    32.         Person[] persons = {new Person("Zhang San",30), new Person("Chen Er",20), new Person("Liu Yi",10)};  
    33.         Arrays.sort (persons, new Comparator<Person>() {   
    34.             @Override   
    35.             public int compare(Person p1, Person p2) {   
    36.                 if (p1.getAge() > p2.getAge()) {   
    37.                     return 1;   
    38.                 } else if (p1.getAge() < p2.getAge()) {   
    39.                     return -1;   
    40.                 } else {   
    41.                     return 0;   
    42.                 }   
    43.             }   
    44.         });   
    45.           
    46.         for(int i = 0; i < persons.length; i++) {  
    47.             System.out.println(persons[i].getName() + " " + persons[i].getAge());  
    48.         }  
    49.     }  
    50. }  

    运行结果:

    Liu Yi 10

    Chen Er 20

    Zhang San 30

  • 相关阅读:
    通用权限管理设计 之 数据库结构设计 [转载]
    RBAC权限管理模型(转)
    C# ReportViewer报表 详解
    人生两支笔
    用C#编写ActiveX控件(一)
    SQL操作全集
    用C#编写ActiveX控件(二)
    Attribute在.NET编程中的应用(三)
    Attribute在.NET编程中的应用(四)
    winform自动升级
  • 原文地址:https://www.cnblogs.com/grimm/p/6732464.html
Copyright © 2020-2023  润新知