Collection集合
Collection 层次结构 中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。JDK 不提供此接口的任何直接 实现:它提供更具体的子接口(如 Set 和 List)实现。此接口通常用来传递 collection,并在需要最大普遍性的地方操作这些 collection。
基本功能测试
-
基本功能演示
boolean add(E e)
boolean remove(Object o)
void clear()
boolean contains(Object o)
boolean isEmpty()
int size()
基本功能较简单,不再详述。
集合的遍历
A.转化成数组再进行遍历
- 使用toArray
代码演示
//先建立一个Student类
Collection coll = new ArrayList();
coll.add(new Student("张三",20));
coll.add(new Student("李四",21));
coll.add(new Student("王五",22));
coll.add(new Student("赵六",23));
Object[] arr = coll.toArray();//将集合转换成数组
System.out.println(arr);
for (int i= 0;i<arr.length;i++){
Student s=(Student) arr[i];
System.out.println(s.getName()+","+s.getAge());
}
B.迭代器遍历
*代码演示:
Collection coll = new ArrayList();
coll.add(new Student("张三",20));
coll.add(new Student("李四",21));
coll.add(new Student("王五",22));
coll.add(new Student("赵六",23));
Iterator it = coll.iterator();
while (it.hasNext()){
Student s = (Student) it.next();
System.out.println(s.getName()+","+s.getAge());
}
迭代器的原理及源码解析
迭代器是集合常用的遍历方法,所以我来看看它的源代码
迭代器是将这样的方法向上抽取出接口,然后在每个类的内部,定义自己迭代方式,这样做的好处有二,第一规定了整个集合体系的遍历方式都是hasNext()和next()方法,第二,代码有底层内部实现,使用者不用管怎么实现的,会用即可。简而言之,迭代器的人实现是通过内部类。
- 1,在IDEA找到ArrayList类
- 2,ctrl+F12查找iterator()方法
- 3,查看返回值类型是new Itr(),说明Itr这个类实现Iterator接口
- 4,查找Itr这个内部类,发现重写了Iterator中的所有抽象方法
Collection接口没有任何直接实现:它提供更具体的子接口(如 Set 和 List)。其子接口会有些新特性出现,如:是否有序,可否重复等,但是基本方法仍可以使用。