Java集合的遍历方法

来源:互联网 发布:超赢topview数据 编辑:程序博客网 时间:2024/05/16 09:04
import java.util.ArrayList;import java.util.Collection;import java.util.Date;import java.util.Iterator;import org.junit.Test;public class TestIterator {//迭代器遍历@Testpublic void test1() {Collection col = new ArrayList();col.add(123);col.add(new String("AAA"));col.add(new Date());col.add(new TestObject1("MM"));col.add(new TestObject2("GG"));Iterator iterator = col.iterator();while(iterator.hasNext()) {System.out.println(iterator.next());}}//foreach遍历@Testpublic void test2() {Collection col = new ArrayList();col.add(123);col.add(new String("AAA"));col.add(new Date());col.add(new TestObject1("MM"));col.add(new TestObject2("GG"));for (Object obj : col) {System.out.println(obj);}}//foreach遍历再举例@Testpublic void test3() {String[] str = new String[]{"AA","BB","DD"};for (String s : str) {System.out.println(s);}}//注意:foreach遍历@Testpublic void test4() {String[] str = new String[]{"AA","BB","DD"};for (String s : str) {s = "MM";//此处的s是定义的局部变量,其值的修改不会对str本身造成影响}for (String s : str) {System.out.println(s);}/* * 结果: * AA * BB * DD */}}

0 0