黑马程序员技术交流社区
标题:
高级for()循环与迭代器。
[打印本页]
作者:
郭振
时间:
2012-5-12 19:39
标题:
高级for()循环与迭代器。
本帖最后由 郭振 于 2012-5-12 19:40 编辑
//下边代码中,用高级for循环与迭代器都能得到list集合中的元素,那它们有什么区别,如果高级for能得到集合的元素,为什么还要集合还要用迭代器呢?
import java.io.*;
import java.util.*;
public class FileDigui {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File dir=new File("F:\\javawork");
List<File>list=new ArrayList<File>();
fun(dir,list);
System.out.println(list.size());
fun2(list);
}
public static void fun(File dir,List<File>l)
{
File[] fs=dir.listFiles();
for(File f:fs)
{
if(f.isDirectory())
{
fun(f,l);
}
else{
if(f.getName().endsWith(".java"));
l.add(f);
}
}
}
public static void fun2(List<File> list) throws IOException
{
BufferedWriter bw=new BufferedWriter(new FileWriter("e:\\sbx.txt"));
Iterator<File>it= list.iterator();
while(it.hasNext())
{
File f=it.next();
String s=f.getAbsolutePath();
bw.write(s);
bw.newLine();
bw.flush();
}
/*for(File f:list)
{
String s= f.getAbsolutePath();
bw.write(s);
bw.newLine();
bw.flush();
}
bw.close();*/
}
}
作者:
蒋映辉
时间:
2012-5-12 19:45
foreach循环是JDK1.5增加的新特性,在出Iterator的时候还没这个东西。现在用foreach循环代码会简洁很多
作者:
金肖
时间:
2012-5-12 20:26
高级for是一种简化形式
它必须有遍历目标,该目标要么是数组,要么是Collection单列集合
作者:
张成龙
时间:
2012-5-12 20:29
存在的就是合理的,其实好多东西没必要打破砂锅问道底的{:soso_e113:}
作者:
杨永峰
时间:
2012-5-12 20:41
//for循环的操作对象主要是底层以数组为数据结构的数据 ,比如ArrayList ,array
//不同于for,iterator的操作对象以链表为数据结构的数据为主, 比如 HashSet, LinkedList
作者:
杨静
时间:
2012-5-12 20:43
高级的for()循环可以实现查找但是不能用于删除元素,但是迭代器可以,同时高级for循环内部也是用迭代器实现的,所以高级for循环的应用面是比较小的。
作者:
杨永峰
时间:
2012-5-12 20:52
杨静 发表于 2012-5-12 20:43
高级的for()循环可以实现查找但是不能用于删除元素,但是迭代器可以,同时高级for循环内部也是用迭代器实现 ...
你的名字真的好熟悉{:3_56:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2