Java集合学习之ArrayList排序
前言
最近大补java基础部分,大致可以分为几个,多线程、集合、Io流、异常等部分。刚好复习到集合里面的一个点:ArrayList,在这里面有一个面试官会问的比较多的几个点是:ArrayList和LinkedList、ArrayList和Vector的区别等等。但是今天说的不是这几个问题,今天来说一下比较偏的问题:ArrayList里面的元素如何实现排序。
思路
将需要排序的自定义类实现java.util.comparator接口,并且重写compare()方法,传入自己需要排序的参数字段,之后调用java.util.collections类的sotr()方法,传入自定义的排序类即可按照自定义规则进行排序。
例子
package com.ydy.test; import java.util.*; /** * ArrayList排序 * * @Author: yaodengyan */ public class ArrayListCompareTest { public static void main(String[] args) { Student zs= new Student("张三", 21); Student ls= new Student("李四", 22); Student ww= new Student("王五 ", 19); List<Student> studentList = new ArrayList<Student>(); studentList.add(zs); studentList.add(ls); studentList.add(ww); System.out.println("排序前:"); for (Student student : studentList) { System.out.println(student.getName() + " / " + student.getAge()); } System.out.println(); System.out.println("按年龄升序:"); // 调用排序方法,传入自定义类 Collections.sort(studentList, new SortByAge()); for (Student student : studentList) { System.out.println(student.getName() + " / " + student.getAge()); } System.out.println(); System.out.println("按姓名排序:"); // 调用排序方法,传入自定义类 Collections.sort(studentList, new SortByName()); for (Student student : studentList) { System.out.println(student.getName() + " / " + student.getAge()); } } } // 定义需要排序的类 class Student{ // 有参构造,用于创建对象 public Student(String name, int age) { this.name = name; this.age = age; } private String name; private int 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; } } // 根据年龄排序类 class SortByAge implements Comparator { @Override public int compare(Object o1, Object o2) { Student student1 = (Student) o1; Student student2 = (Student) o2; if (student1.getAge() > student2.getAge()){ return 1; }else { return -1; } } } // 根据姓名排序 class SortByName implements Comparator{ @Override public int compare(Object o1, Object o2) { Student student1 = (Student) o1; Student student2 = (Student) o2; return student1.getName().compareTo(student2.getName()); } }