-
是单例集合的顶层接口
-
JDK不提供该接口的任何直接实现,它提供更为具体的子接口(Set与List)实现
创建collection 集合方式:多态
具体实现类:ArrayList
使用方法public class construct {
public static void main(String[] args) {
Collection c = new ArrayList(); //多态,编译看左,执行看右
//添加元素: boolean add(E e) e元素类型和<>中相同
c.add("hello");
c.add("world");
c.add("java");
//输出集合对象:一个对象按理说应该输出带@的地址值,但是
System.out.println(c); //[hello, world, java] 输出的是集合的元素形式,说明重写了 toString方法
}
}
常用方法
boolean add(E e){} //添加元素,永远返回true
boolean remove(Object o){} //从集合中移除指定元素,该元素不存在时,返回false
void clear() //清空集合中的元素
boolean contains(Object o) //判断元素中是否存在指定的元素
boolean isEmpty() //判断集合是否为空
int size() //集合的长度,也就是集合中的元素个数
Collection 集合的遍历
Iterator : 迭代器,集合的专用遍历方式
在Collection接口中:
public Iteratorinterator(){} //返回集合中的元素的迭代器
在Iterator接口中:
Iterator 也是一个接口 interface Iterator //常用方法 E next() //返回集合中的下一个元素 boolean hasNext() //有更多元素
//Iteratoriterator():返回集合中的元素的迭代器 Iterator it = c.iterator(); //在执行的时候,是调用的实现类(ArrayList)的方法 //相当于:Iterator it = new Itr(); //接口多态 System.out.println(it.hasNext()); System.out.println(it.next()); System.out.println(it.next()); System.out.println(it.next()); System.out.println(it.hasNext()); System.out.println(it.next());//NoSuchElementException:被各种访问器方法抛出,表示被请求的元素不 存在 //更好的改进方案 while(it.hasNext()){ //E e = it.next(); //用新的变量接收元素,本例中采用: String s = it.next(); //可以接下来对s操作 System.out.println(s); }



