2020-04-14

2020-04-14  本文已影响0人  甜甜圈李

Collection集合的高级功能测试

带All的功能

boolean addAll(Collection c)

boolean removeAll(Collection c)

boolean containsAll(Collection c)

boolean retainAll(Collection c)

集合的遍历之迭代器遍历

迭代器概述

集合是用来存储元素,存储的元素需要查看,那么就需要迭代(遍历) 

迭代器的使用

Collection c = new ArrayList();

c.add("a");

c.add("b");

c.add("c");

c.add("d");

Iterator it = c.iterator(); //获取迭代器的引用

while(it.hasNext()) { //集合中的迭代方法(遍历)

System.out.println(it.next());

}

Collection存储自定义对象并遍历

Collection存储自定义对象并用迭代器遍历

Collection c = new ArrayList();

c.add(new Student("张三",23));

c.add(new Student("李四",24));

c.add(new Student("王五",25));

c.add(new Student("赵六",26));

c.add(new Student("赵六",26));

for(Iterator it = c.iterator();it.hasNext();) {

Student s = (Student)it.next(); //向下转型

System.out.println(s.getName() + "," + s.getAge()); //获取对象中的姓名和年龄

}

System.out.println("------------------------------");

Iterator it = c.iterator(); //获取迭代器

while(it.hasNext()) { //判断集合中是否有元素

//System.out.println(((Student)(it.next())).getName() + "," + ((Student)(it.next())).getAge());

Student s = (Student)it.next(); //向下转型

System.out.println(s.getName() + "," + s.getAge()); //获取对象中的姓名和年龄

}

迭代器原理

迭代器原理:迭代器是对集合进行遍历,而每一个集合内部的存储结构都是不同的,所以每一个集合存和取都是不一样,那么就需要在每一个类中定义hasNext()和next()方法,这样做是可以的,但是会让整个集合体系过于臃肿,迭代器是将这样的方法向上抽取出接口,然后在每个类的内部,定义自己迭代方式,这样做的好处有二,第一规定了整个集合体系的遍历方式都是hasNext()和next()方法,第二,代码有底层内部实现,使用者不用管怎么实现的,会用即可。

上一篇 下一篇

猜你喜欢

热点阅读