您的位置:首页 > 编程语言 > Java开发

Java:集合for高级循环遍历

2015-10-27 23:04 483 查看
增强for循环:

格式:for(变量数据类型 要遍历的变量 :元素所在数组(集合)名称)

也即 for(Type element: array或collection)

使用foreach遍历集合:

只能获取集合中的元素,不能对集合进行操作。

而迭代器Iterator除了可以遍历,还可以对集合中的元素遍历时进行remove操作。

如果使用ListIterator还可以在遍历过程中进行增删改查的动作。

//例子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、传统for循环遍历(按角标获取)
for(int i=0;i<al.size();i++)
{
sop(al.get(i));
}
sop("\n");

//2、for循环遍历(迭代器)
for(Iterator<String> it2 = al.iterator();it2.hasNext();)
{
sop(it2.next());
}
sop("\n");

/*     //for循环遍历(vector集合的枚举)
for(Enumeration<String> en = al.elements();en.hasMoreElements();)
{
sop(en.nextElement());
}
sop("\n");
*/
//3、for循环增强遍历
for(String s: al)
{
sop(s);
}
}
}


在Map集合中使用for高级遍历(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();

//转化为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("---------------------");

//转化为Set集合后,用for循环高级遍历获取元素
for(String str: keyset)
{
sop("str:"+str+"::"+"in:"+hm.get(str));
}
sop("---------------------");

//转化为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("---------------------");

//转化为Set集合后,用for循环高级遍历获取元素
for(Map.Entry<String,Integer> me: entryset)
{
sop("str:"+me.getKey()+"....."+"in:"+me.getValue());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: