Collection接口和List接口
1. 集合框架概述
为了保存一些数目不确定的对象,JDK中提供了一系列特殊的类,这些类可以存储任意类型的对象,并且长度可变,统称为集合。这些类都位于java.util包中。集合类的继承体系如图所示。
2. Collection接口
Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法。
常见方法:
l add(Object o)
l remove(Object o)
l int size()
l boolean isEmpty()
l boolean contains(Object o)
l void clear()
l Iterator iterator()
l Object[] toArray()
3. 迭代器---接口描述的是以统一方式对各种集合元素进行遍历/迭代的工具
主要方法:
l boolean hasNext()
l Object next()
l void remove()
应用框架:
Iterator 迭代器变量名;//迭代器变量 声明
迭代器变量名=集合名.iterator() //迭代器变量关联集合
while(迭代器变量名.hasNext())
{
System.out.println(迭代器变量名.next());
}
例:
Collection list = new ArrayList();
//...
Iterator it = list.iterator(); // 获取Iterator对象
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
4. 列表接口List
List集合区分元素的顺序(存入顺序和取出顺序一致),且允许包含重复元素。
n ArralyList类:顺序结构,可空,可重复,线程不同步
n LindedList类:离散结构,可空,可重复,线程不同步
n Vector类:线程同步
n Stack类:后进先出常见方法---push() pop()
例1:
Collection c=new ArrayList();
c.add(12);
c.add(3.14);
c.add("hello");
//遍历1:foreach
for(Object o:c)
{
System.out.print(o+" ");
}
System.out.println("\n----------");
//遍历2:转换为数组
Object[] arr=c.toArray();
int i;
for(i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println("\n----------");
//遍历3:迭代器
//声明变量
Iterator it;
//和集合关联 集合对象 .iterator()
it=c.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
例2:
List c=new ArrayList();
c.add(12);
c.add(3.14);
c.add("hello");
int i;
//List的get()
for(i=0;i<c.size();i++)
{
System.out.println(c.get(i));
}