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());
    }
}

 

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章