JAVA学习--集合的遍历
生活随笔
收集整理的這篇文章主要介紹了
JAVA学习--集合的遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 @Test
2 public void testFor3(){
3 String[] str = new String[]{"AA","BB","DD"};
4 for(String s : str){
5 s = "MM";//此處的s是新定義的局部變量,其值的修改不會對str本身造成影響。
6 System.out.println(s);
7 }
8
9 for(int i = 0;i < str.length;i++){
10 System.out.println(str[i]);
11 }
12 }
13 @Test
14 public void testFor2(){
15 String[] str = new String[]{"AA","BB","DD"};
16 for(int i = 0;i < str.length;i++){
17 str[i] = i + "";
18 }
19
20 for(int i = 0;i < str.length;i++){
21 System.out.println(str[i]);
22 }
23 }
24
25 //***********************************************
26 //使用增強for循環實現數組的遍歷
27 @Test
28 public void testFor1(){
29 String[] str = new String[]{"AA","BB","DD"};
30 for(String s:str){
31 System.out.println(s);
32 }
33 }
34
35 //使用增強for循環實現集合的遍歷
36 @Test
37 public void testFor(){
38 Collection coll = new ArrayList();
39 coll.add(123);
40 coll.add(new String("AA"));
41 coll.add(new Date());
42 coll.add("BB");
43
44 for(Object i:coll){
45 System.out.println(i);
46 }
47 }
48
49 //錯誤的寫法
50 @Test
51 public void test2(){
52 Collection coll = new ArrayList();
53 coll.add(123);
54 coll.add(new String("AA"));
55 coll.add(new Date());
56 coll.add("BB");
57 coll.add(new Person("MM", 23));
58
59 Iterator i = coll.iterator();
60
61 while((i.next())!= null){
62 //java.util.NoSuchElementException
63 System.out.println(i.next());
64 }
65 }
66 //正確的寫法:使用迭代器Iterator實現集合的遍歷
67 @Test
68 public void test1(){
69 Collection coll = new ArrayList();
70 coll.add(123);
71 coll.add(new String("AA"));
72 coll.add(new Date());
73 coll.add("BB");
74
75 Iterator i = coll.iterator();
76 while(i.hasNext()){
77 System.out.println(i.next());
78 }
79 }
?
轉載于:https://www.cnblogs.com/zhangfan94/p/4263325.html
總結
以上是生活随笔為你收集整理的JAVA学习--集合的遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 代理服务器Tengine的研究与测试
- 下一篇: js中div显示和隐藏钮为什么页面总是跳