1. for(集合元素类型:集合名)
Collection collection = new ArrayList();
collection.add(123);
collection.add("abc");
collection.add(new Date());
collection.add(false);
System.out.println(collection);
for(Object obj:collection){
System.out.println(obj);
}
2. for(数组元素类型:数组名)
int[] array = new int[]{1,3,5,2,3,4};
for(int i:array){
System.out.println(i);
}
3. for(字符串数组元素类型:字符串数组名)
String[] strings = new String[]{"abc","dfg","ghj"};
for(String str:strings){
System.out.println(str);
}
4. 普通for循环和增强for循环赋值的区别
String[] str = new String[]{"abc","def","efg","hjk"};
for(int i=0;i<str.length;i++){
str[i]="xx";
}
for(int i=0;i<str.length;i++){
System.out.println(str[i]);
}
- 增强for循环只是用一个参数来接收,并打印参数,并不会改变数组内容
for(String string:str){
string="yy";
}
for(int i=0;i<str.length;i++){
System.out.println(str[i]);
}