使用foreach循环遍历集合元素
生活随笔
收集整理的這篇文章主要介紹了
使用foreach循环遍历集合元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用foreach循環遍歷集合元素
代碼實現
import java.util.ArrayList; import java.util.Collection; import java.util.Date; /** jdk5.0新增了foreach循環,用于遍歷集合,數組*/ public class ForTest {public static void main(String[] args) {Collection coll = new ArrayList();coll.add(123);coll.add(new Date());coll.add("heipapap");coll.add("baibai");coll.add(false);coll.add(new Person("Tom",23));coll.add(new Person("maruya",23));//for(集合元素的類型 局部變量 : 集合對象)//內部仍然調用了迭代器for(Object obj:coll){System.out.println(obj);}int[] arr = new int[]{1,2,3,4,5,6,7,8};//for(數組元素的類型 局部變量 :數組對象)for(int i :arr){System.out.println(i);}//通過一個練習題來理解一下增強for循環和普通for循環的區別//方式一 普通for循環String[] str = new String[]{"gege","gege","gege"};for(int i =0;i<str.length;i++){str[i]="woc";}//遍歷for(int i =0;i<str.length;i++){System.out.println(str[i]);//woc//woc//woc}//方式二:增強for循環for(String s : str){s = "hahaha";}//遍歷for(int i =0;i<str.length;i++){System.out.println(str[i]);//woc//woc//woc}} }總結
以上是生活随笔為你收集整理的使用foreach循环遍历集合元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring入门hello world常
- 下一篇: 将Jquery序列化后的表单值转换成Js