目录

一、Collection集合概述和使用

二、Collection集合常用方法

三、Collection集合的遍历


一、Collection集合概述和使用

1、Collection集合是单例集合,它是一组对象,这些对象也称为Collection的元素

2、JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

创建Collection集合的对象:

1、多态的方式

2、具体的实现类ArrayList

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo01 {
    public static void main(String[] args) {
        //创建Collection集合的对象
        Collection<String> c = new ArrayList<>();

        //添加元素,boolean add(E e)
        c.add("hello");
        c.add("world");
        c.add("java");

        //输出集合对象
        System.out.println(c);
    }
}

输出结果:

二、Collection集合常用方法

方法名说明
boolean add(E e)添加元素
boolean remove(Object o)从集合中移除指定的元素
void clear()清空集合中的元素
boolean contains(Object o)判断集合中是否存在指定的元素
boolean isEmpty()判断集合是否为空
int size()集合的长度,也就是集合中元素的个数

三、Collection集合的遍历

Iterator:迭代器,集合的专用遍历方式

1、Iterator<E>iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到

2、迭代器的通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的

Iterator中常用的方法

1、E next():返回迭代中的下一个元素

2、boolean hasNext():如果迭代具有更多元素,则返回ture

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CollectionDemo01 {
    public static void main(String[] args) {
        //创建集合的对象
        Collection<String> c = new ArrayList<>();

        //添加元素
        c.add("hello");
        c.add("world");
        c.add("java");

        //Iterator<E> iterator(),返回此集合中元素的迭代器,通过集合的iterator()方法得到
        Iterator<String> it = c.iterator();
        //迭代器方式遍历
        while(it.hasNext()){
            String next = it.next();
            System.out.println(next);
        }
    }
}

运行结果:

 

更多推荐

Java中Collection的具体用法