Java:集合for高级循环遍历
生活随笔
收集整理的這篇文章主要介紹了
Java:集合for高级循环遍历
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
增強(qiáng)for循環(huán):
格式:for(變量數(shù)據(jù)類型 要遍歷的變量 :元素所在數(shù)組(集合)名稱)
也即 for(Type element: array或collection)
使用foreach遍歷集合:
? ?只能獲取集合中的元素,不能對(duì)集合進(jìn)行操作。
? ?而迭代器Iterator除了可以遍歷,還可以對(duì)集合中的元素遍歷時(shí)進(jìn)行remove操作。
? ?如果使用ListIterator還可以在遍歷過程中進(jìn)行增刪改查的動(dòng)作。
//例子1:
import java.util.*; class Foreach {public static<T> void sop(T t){System.out.println(t);}public static void main(String[] args) {ArrayList<String> al = new ArrayList<String>();al.add("abc");al.add("bcd");al.add("kef");//1、傳統(tǒng)for循環(huán)遍歷(按角標(biāo)獲取)for(int i=0;i<al.size();i++){sop(al.get(i));}sop("\n");//2、for循環(huán)遍歷(迭代器)for(Iterator<String> it2 = al.iterator();it2.hasNext();){sop(it2.next());}sop("\n");/* //for循環(huán)遍歷(vector集合的枚舉)for(Enumeration<String> en = al.elements();en.hasMoreElements();){sop(en.nextElement());}sop("\n"); *///3、for循環(huán)增強(qiáng)遍歷for(String s: al){sop(s);}} }?
在Map集合中使用for高級(jí)遍歷(foreach)
//例子2:?
import java.util.*; class Foreach2 {public static void sop(Object obj){System.out.println(obj);}public static void main(String[] args) {Map<String,Integer> hm = new HashMap<String,Integer>();hm.put("a",1);hm.put("b",2);hm.put("c",3);Set<String> keyset = hm.keySet();Set<Map.Entry<String,Integer>> entryset = hm.entrySet();//轉(zhuǎn)化為Set集合后,直接用迭代器獲取元素(方法:keySet())Iterator<String> it1 = keyset.iterator();while(it1.hasNext()){String str = it1.next();Integer in = hm.get(str);sop("str:"+str+" "+"in:"+in);}sop("---------------------");//轉(zhuǎn)化為Set集合后,用for循環(huán)高級(jí)遍歷獲取元素for(String str: keyset){sop("str:"+str+"::"+"in:"+hm.get(str));}sop("---------------------");//轉(zhuǎn)化為Set集合后,直接用迭代器獲取元素(方法:entrySet())Iterator<Map.Entry<String,Integer>> it2 = entryset.iterator();while(it2.hasNext()){Map.Entry<String,Integer> me = it2.next();String str = me.getKey();Integer in = me.getValue();sop("str:"+str+" "+"in:"+in);}sop("---------------------");//轉(zhuǎn)化為Set集合后,用for循環(huán)高級(jí)遍歷獲取元素for(Map.Entry<String,Integer> me: entryset){sop("str:"+me.getKey()+"....."+"in:"+me.getValue());}} }?
轉(zhuǎn)載于:https://www.cnblogs.com/XYQ-208910/p/4915913.html
總結(jié)
以上是生活随笔為你收集整理的Java:集合for高级循环遍历的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决Coldfusion连接MySQL数
- 下一篇: jsp通过include指令引入html