Java中的Collections類常用語法--針對List集合

學習筆記:Collections類語法記錄
Collections是針對List集合操作的工具類,此類僅包含靜態方法。使用該類的方法時,可以類名.方法名

//Collections構造方法
private Collections() {
    }
Collections常用方法
  • public static <T> void sort(List<T> list, Comparator<? super T> c):將指定的列表按照升序排序
  • public static void reverse(List<?> list):反轉指定列表中的序列
  • public static void shuffle(List<?> list):使用默認的隨機源隨機排列指定的列表
//Collections常用方法測試
public class CollectionsDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("java");
        list.add("劉備");
        list.add("張三");
        list.add("javaee");

        System.out.println(list);

        Collections.reverse(list);
        System.out.println("list反轉後:"+ list);//[javaee, 張三, 劉備, java]
        Collections.sort(list);
        System.out.println("list排序後:"+ list);//[java, javaee, 劉備, 張三]
        Collections.shuffle(list);
        
    }
}
問題

對學生類集合排序時,重寫了Comparator方法。還看不懂

public class CollectionsDemo {
    public static void main(String[] args) {
    //創建集合對象
        ArrayList<Student> array = new ArrayList<Student>();

        //創建學生對象
        Student s1 = new Student("linqingxia",32);
        Student s2 = new Student("fengqingyang",45);
        Student s3 = new Student("liubei",20);
        Student s4 = new Student("zhangfei",27);

        //把學生添加到集合對象
        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);

        //使用collections 對集合進行排序
        //sort(list<T> list,Comparator<? super T> c>
        Collections.sort(array, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //要求:按照年齡從小到大排序,年齡相同時,按照姓名的字母進行排序
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });


        //6、遍歷集合
        for(Student s : array){
            System.out.println(s.getAge() +"," + s.getName());
        }

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