package com.atguigu.java1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.junit.Test;
public class TestIterator {
//面试题:
@Test
public void testFor3(){
String[] str = new String[]{"AA","BB","DD"};
for (String s:str) {
s = "MM";
System.out.println(s);//输出MM MM MM
}
for (int i = 0; i < str.length; i ++){
System.out.println(str[i]);//输出AA BB DD
}
}
@Test
public void testFor2(){
String[] str = new String[]{"AA","BB","DD"};
for(int i = 0; i < str.length;i ++){
str[i] = i + "";
}
for(int i = 0; i < str.length; i ++){
System.out.println(str[i]); //输出结果为,0 1 2
}
}
//使用增强for循环实现数组的遍历(数组不能使用集合while的那种方式,因为数组没有Iterator这个函数)
@Test
public void testFor1(){
String[] str = new String[]{"AA","BB","DD"};
for(String s:str){
System.out.println(s);
}
}
//使用增强for循环实现集合的遍历
@Test
public void testFor(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM",23));
for(Object i:coll){
System.out.println(i);
}
}
//错误的写法
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM",23));
Iterator i = coll.iterator();
//会出错,输出结果会间隔输出;错误提示为java.util.NoSuchElementException,因为while成立,但是输出的next里面没有东西
//间隔输出的主要原因是i.next()会向下取值,输出的时候,指针i.next()又向下走了一步。
while (i.next() != null) {
System.out.println(i.next());
}
}
//正确的写法:使用迭代器Iterator实现集合的遍历
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM",23));
Iterator i = coll.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
网友评论