java集合深入理解(二):Collection接口的特點與理解

(一)Collection接口的特點

Collection接口沒有自己的實現類,具體的實現類都在他的子接口中,如List和Set。Collection中提供了一系列操作集合的方法,比如增加、刪除等等,對於Collection中提供的方法,可以在官方文檔中查閱(java PlatForm SE 8),

(二)Collection的常用方法

Collection提供的方法並不多,這裏介紹一下常用的幾個:

public class TestMethod {
    public static void main(String[] args) {
        //創建collection子接口的對象,這裏用ArrayList
        Collection collection=new ArrayList();
        
        //method1.add
        collection.add("zhangsan");
        collection.add(18);
        System.out.println(collection);
        
        //method2.addall
        Collection collection2=new ArrayList();
        collection2.addAll(collection);
        System.out.println(collection2);
        
        //method3.contains
        boolean contains = collection.contains(18);
        System.out.println(contains);
        
        //method4.containsAll
        boolean containsall = collection.containsAll(collection2);
        System.out.println(containsall);
        
        //method5.isEmpty
        System.out.println(collection.isEmpty());
        
        //method6.remove
        collection.remove(18);
        System.out.println(collection);
        
        //method7.size
        System.out.println(collection.size());
        
        //method8.clear
        collection.clear();
        System.out.println(collection);
    }
}

需要注意的是Collection的遍歷,Collection繼承了Iterable接口,使得它可以通過迭代器來遍歷元素。迭代器的遍歷有三步:

Collection collection=new ArrayList();
collection.add("zhangsan");
collection.add(18);
collection.add("lisi");
//1.獲取迭代器對象,此時迭代器指向集合最上面元素的上一位
Iterator iterator=collection.iterator();
//2.使用hasNext()判斷下一位還有沒有對象
while (iterator.hasNext()){
//3.使用next()遍歷
    System.out.println(iterator.next());
}

爲了簡化語法也可以用增強for遍歷集合,增強for本質上就是迭代器

for (Object o:collection){
    System.out.println(o);
}

在迭代過程中。不能通過集合的remove去刪除對象集合,不然就會報ConcurrentModificationException錯誤。如果一定要在迭代中刪除元素,建議使用迭代器自帶的remove方法刪除

(三)總結

Collection這個接口的介紹比較簡單,但是它的子接口及其實現類就很需要很好的掌握,接下來就將詳細介紹List接口。

發佈了68 篇原創文章 · 獲贊 962 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章