zoukankan      html  css  js  c++  java
  • java 18-11 Collections用于ArrayList集合中

      Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢?
        自定义对象要自己写比较器进行排序

     1 package cn.itcast_02;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Collections;
     5 import java.util.Comparator;
     6 import java.util.List;
     7 public class CollectionsDemo {
     8     public static void main(String[] args) {
     9         // 创建集合对象
    10         List<Student> list = new ArrayList<Student>();
    11 
    12         // 创建学生对象
    13         Student s1 = new Student("林青霞", 27);
    14         Student s2 = new Student("风清扬", 30);
    15         Student s3 = new Student("刘晓曲", 28);
    16         Student s4 = new Student("武鑫", 29);
    17         Student s5 = new Student("林青霞", 27);
    18 
    19         // 添加元素对象
    20         list.add(s1);
    21         list.add(s2);
    22         list.add(s3);
    23         list.add(s4);
    24         list.add(s5);
    25 
    26         // 排序
    27         // 自然排序
    28         // Collections.sort(list);
    29         // 比较器排序
    30         // 如果同时有自然排序和比较器排序,以比较器排序为主
    31         Collections.sort(list, new Comparator<Student>() {
    32             @Override
    33             public int compare(Student s1, Student s2) {
    34                 int num = s2.getAge() - s1.getAge();
    35                 int num2 = num == 0 ? s1.getName().compareTo(s2.getName())
    36                         : num;
    37                 return num2;
    38             }
    39         });
    40 
    41         // 遍历集合
    42         for (Student s : list) {
    43             System.out.println(s.getName() + "---" + s.getAge());
    44         }
    45     }
    46 }
    何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
  • 相关阅读:
    前端CSS-font属性,超链接的美化,css精灵,background综合属性
    iOS App上架流程(2016详细版)
    iOS中使用正则
    iOS开发--JS调用原生OC篇
    iOS开发--OC调用JS篇
    CocoaPods 的简单快速安装方法
    iOS开发小技巧 -- tableView-section圆角边框解决方案
    Mac合并分区
    iOS开发小技巧
    iOS开发中遇到的错误整理
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5910142.html
Copyright © 2011-2022 走看看