Java学习之for-each循环与集合的遍历

for-each循环(Java 1.5后)

	for (type varname :obj){//循环体}


type:数据类型

varname:元素变量
obj:需要遍历的对象,如数组,集合等
上课的讲师说这个循环里面的变量只读
于是我对此作了个小测试

测试:

package kj.t1;
import java.util.Arrays;public class Test {public void test1(){System.out.println("-----------test1------------------");int []intArr = {1,2,3,4,7};for (int a:intArr){a+=10;System.out.println(a);}System.out.println(Arrays.toString(intArr));}public void test2(){System.out.println("------------test2----------------");int [][] intArr = {{1},{2,3},{4,5,6}};for (int x[]:intArr){for (int e:x){e += 100;System.out.println(e);}}for (int x[]:intArr){System.out.println(Arrays.toString(x));}}
}

Main:

package kj.t1;
public class ForEach {public static void main(String[] args) {// TODO Auto-generated method stubTest x = new Test();x.test1();x.test2();}
}

运行结果:

-----------test1------------------
11
12
13
14
17
[1, 2, 3, 4, 7]
------------test2----------------
101
102
103
104
105
106
[1]
[2, 3]
[4, 5, 6]

也就是说,foreach能够遍历数组的每一个元素,但是并不会改变数组的值,但是可以改变元素变量的值

我是这样理解的foreach就相当于单独讲数组的元素用另外一个变量存起来了,同时隐藏了当前循环的次数
所以我这样理解test1:

	public void test3(){System.out.println("--------------test3--------------");int [] intArr = {1,2,3,4,7};for (int i = 0;i < intArr.length;++i){int a = intArr[i];a += 10;System.out.println(a);}System.out.println(Arrays.toString(intArr));}

这样的foreach的特点很显然:

1.它的代码更简洁(虽然并没有简洁很多)
2.它不改变原数组的值(只读,或者只是暂时改,就像给方法传形参而不改变实参的值)
3.它隐藏了当前循环的次数(当需要输出循环次数检测时foreach不好使)
总的来说,foreach可以实现的功能for循环都可以实现
但是for能做到的foreach不一定做得到

package kj.t1;
import java.util.*;
public class Test {public void test1(){/*				一维数组			*/System.out.println("-----------test1------------------");int []intArr = {1,2,3,4,7};for (int a:intArr){a+=10;System.out.println(a);}System.out.println(Arrays.toString(intArr));}public void test2(){/*             二维数组                                */System.out.println("------------test2----------------");int [][] intArr = {{1},{2,3},{4,5,6}};for (int x[]:intArr){for (int e:x){e += 100;System.out.println(e);}}for (int x[]:intArr){System.out.println(Arrays.toString(x));}}public void test3(){/*		与test1实现相同功能的for循环		*/System.out.println("--------------test3--------------");int [] intArr = {1,2,3,4,7};for (int i = 0;i < intArr.length;++i){int a = intArr[i];a += 10;System.out.println(a);}System.out.println(Arrays.toString(intArr));}public void test4(){/*		list				*/System.out.println("-----------------test4--------------");List<String>list = new ArrayList<String>();list.add("1");list.add("2");list.add("3");for (String x:list){System.out.println(x);}}public void test5(){/*		对String 使用 for-each			*/String a = "12347";char []ch = a.toCharArray();for (char x:ch){System.out.println(x);}}
}


但是foreach也有其独特的优点,在集合的遍历的时候用foreach确实很方便。
它利用了父类可以调用子类的特点。
下面是学习集合之后记录的集合遍历的代码:(用iterator遍历和用for-each遍历)

package com.mustso.java1;import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;import org.junit.Test;public class TestIterator {/** 正确的写法* 使用迭代器Iterator实现集合的遍历*/@Testpublic 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 it = coll.iterator();while (it.hasNext()){System.out.println(it.next());}}@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 it = coll.iterator();/** 错误的写法!* next()执行了具体内容* 当syso里面的it.next()空了之后再执行循环里判断的it.next()时* 会抛出java.util.NoSuchElementException*/while (it.next()!=null){System.out.println(it.next());}}/** 使用增强for循环实现数组的遍历*/@Testpublic void testFor1(){String[] str=new String[]{"AA","BB","DD"};for (String s : str) {System.out.println(s);}}/** 使用增强for循环实现集合的遍历*/@Testpublic 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);}}//面试题:@Testpublic 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]);}}@Testpublic void testFor3(){String[] str = new String[]{"AA","BB","DD"};for (String s : str) {s = "MM";//此处的s是新定义的局部变量,其值的修改不会对str本身造成影响}for (String s : str) {System.out.println(s);}}
}