8.46 优先使用for-each循环代替for循环

使用for-each循环更简洁,进而减少错误,对比如下:

		Collection<String> parents=new ArrayList<String>();
		Collection<String> childs=new ArrayList<String>();
		
		for(Iterator<String> p=parents.iterator();p.hasNext();)
			for(Iterator<String> c=childs.iterator();c.hasNext();)
				//do something
		
		//更简洁
		for(String parent:parents)
			for(String child:childs)
				//do something

 

for-each循环并不适合所有情况,如需要移除,替换元素时,可能只能使用for循环

 

 

你可能感兴趣的:(for循环)