集合知识回顾
集合类的特点:提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变
Collection集合概述和使用
Collection集合概述:
-
是单列集合的顶层接口,它表示一组对象,这些对象也成为Collection的元素
-
JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现
创建Collection集合的对象:
-
多态的方式
-
具体的实现类,如:ArrayList
public class CollectionDemo01 { public static void main(String[] args) { //创建Collection集合对象 Collection<String> c = new ArrayList<String>(); //添加元素:boolean add(E e) c.add("hello"); c.add("world"); //输出集合内容 System.out.println(c); } }
Collection集合常用方法
Collection集合的遍历
Iterator:迭代器,集合的专用遍历方式
-
Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
-
迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
Iterator中的常用方法:
-
E next():返回迭代中的下一个元素
-
boolean hasNext():如果迭代具有更多元素,则返回true
public class IteratorDemo { public static void main(String[] args) { Collection<String> c = new ArrayList<String>(); c.add("hello"); c.add("world"); Iterator<String> i = c.iterator(); while(i.hasNext()){ System.out.println(i.next()); } } }