import org.junit.Test;
import org.junit.runners.model.InvalidTestClassError;
import java.util.ArrayList;
import java.util.Collection;
/**
* jdk5.0新增foreach循环,用于遍历数组和集合
* @author 冀帅
* @date 2020/8/10-15:20
*/
public class ForTest {
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("jerry",20));
coll.add(new String("Tom"));
coll.add(false);
//for(集合中元素的类型 局部变量(i): 集合对象
//内仍然是迭代器
for (Object o : coll) {
System.out.println(o);
}
}
@Test
public void test(){
int[] arr = new int[]{1,2,3,4,5,6};
//for(数组元素的类型 局部变量(i): 数组对象
for (int i : arr) {
System.out.println(i);
}
}
//练习题
@Test
public void test3(){
String[] arr = new String[]{"MM","MM","MM"};
//方式一:普通for循环赋值,结果是三个GG
// for (int i = 0; i <arr.length ; i++) {
// arr[i] = "GG";
//
// }
//方式二:增强for循环。有个新的s,所以原来的不变 还是三个MM
for (String s : arr) {
s="GG";
}
for (int i = 0; i <arr.length; i++) {
System.out.println(arr[i]);
}
}
}