Java Collection和Collections的區別?

面試題,

一、 Collection

1.Collection 是一個 頂級集合是接口(如圖)

在這裏插入圖片描述

2.提供所以集合的共性方法

 * 一、共性方法:
 *      1.add():    添加對象到集合
 *      2.remove(E e):  移除對象
 *      3.size():       返回集合個數
 *      4.toArray():    放回集合轉化的數組
 *      5.isEmpty():    返回true,集合爲空
 *      6.contains(E e):   返回true ,集合包含該對象
 * 二、打印Collection時候和ArrayList一致,打印爲數組,因此重寫了toString方法

二、Collections

1.Collections是一個工具類,類。

如圖
在這裏插入圖片描述

2. 提供的靜態工具方法

在這裏插入圖片描述

3.代碼實例,使用Collections工具類的sort()方法對ArrayList集合進行排序

public class Demo {
    public static void main(String[] args) {
        ArrayList<Person> people = new ArrayList<>();
        people.add(new Person("王二麻子"));
        people.add(new Person("張三"));
        people.add(new Person("Lis"));
        people.add(new Person("李四"));
        System.out.println("-----------排序前:--------");
        System.out.println(people);
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                //名稱長度排序,o1 - o2 升序。
                return o1.name.length() - o2.name.length();
            }
        });
        System.out.println("-----------排序後:--------");
        System.out.println(people);
    }
}

class Person {
    String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.name;
    }
}

Run:
-----------排序前:--------
[王二麻子, 張三, Lis, 李四]
-----------排序後:--------
[張三, 李四, Lis, 王二麻子]

Process finished with exit code 0

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