首页 > 编程语言 > 详细

java 高级for循环

时间:2016-05-12 12:18:36      阅读:246      评论:0      收藏:0      [点我收藏+]
/*
高级for循环是集合中(Collection)迭代器的简写形式。即集合中的迭代器可以使用高级for来代替。
格式:
for(数据类型 变量名:被便利的集合(Collection)或数组)
{

}

高级for循环只对集合进行遍历。
只能获取集合元素,但是不能对集合进行操作。

迭代器除了遍历,还可以进行remove集合中元素的动作。
如果使用ListIterator,还可以对集合中的元素进行增删改查的动作。


传统for循环和高级for循环有什么区别呢?
高级for循环有一个局限性,必须有被遍历的目标;
建议在遍历数组的时候还是使用传统for。因为传统for可以定义角标。
*/
import java.util.*;
class ForEachDemo 
{
	public static void main(String[] args) 
	{
		/*
		ArrayList<String> al=new ArrayList<String>();
		al.add("abc1");
		al.add("abc2");
		al.add("abc3");
		for(String s:al)
			sop(s);

		int[] arr={1,3,4,5,2};
		for(int i:arr)
			sop("i:"+i);
		*/
		HashMap<Integer,String> hm=new HashMap<Integer,String>();
		hm.put(1,"hello1");
		hm.put(3,"hello3");
		hm.put(2,"hello2");
		hm.put(4,"hello4");

		Set<Integer> set=hm.keySet();
		for(Integer i:set)
			sop(i+".."+hm.get(i));


		Set<Map.Entry<Integer,String>> set1=hm.entrySet();
		for(Map.Entry<Integer,String> me:set1)
		{
			Integer key=me.getKey();
			String value=me.getValue();
			sop(key+"......."+value);
		}

	}


	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}

java 高级for循环

原文:http://blog.csdn.net/iemdm1110/article/details/51371849

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!