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接口。

发布了60 篇原创文章 · 获赞 703 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_41973594/article/details/104032640