import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
/**
* @author xianyu
* @version 1.0
* @date 2019/12/29 21:24
*/
public class CollectionTest2 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add("AA");
coll.add(456);
coll.add("Hello");
coll.add("AA");
coll.add(123);
coll.add(new Person("Tom",23));
coll.add(new Date());
System.out.println(coll);
System.out.println("********************");
// 遍历方法1
Iterator iterator = coll.iterator();
while(iterator.hasNext()){ // hasNext():判断是否还有下一个元素
System.out.println(iterator.next()); // //next():①指针下移 ②将下移以后集合位置上的元素返回
}
System.out.println("********************");
// 遍历方法2
for(Object obj : coll){
System.out.println(obj);
}
System.out.println("********************");
// 遍历方法3
Iterator iter = coll.iterator();
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
//System.out.println(iter.next()); // "main" java.util.NoSuchElementException
System.out.println("********************");
// 删除Hello
Iterator iter2 = coll.iterator();
while(iter2.hasNext()){ // hasNext():判断是否还有下一个元素
Object obj = iter2.next();
if("Hello".equals(obj)){
iter2.remove();
}
}
System.out.println(coll);
}
}
运行结果
[AA, 456, Hello, AA, 123, Person{name='Tom', age=23}, Sun Dec 29 21:48:13 CST 2019]
********************
AA
456
Hello
AA
123
Person{name='Tom', age=23}
Sun Dec 29 21:48:13 CST 2019
********************
AA
456
Hello
AA
123
Person{name='Tom', age=23}
Sun Dec 29 21:48:13 CST 2019
********************
AA
456
Hello
AA
123
Person{name='Tom', age=23}
Sun Dec 29 21:48:13 CST 2019
********************
[AA, 456, AA, 123, Person{name='Tom', age=23}, Sun Dec 29 21:48:13 CST 2019]