Iterate with for loop or while loop?

后端 未结 15 1495
野趣味
野趣味 2020-12-01 13:31

I often see code like:

Iterator i = list.iterator();
while(i.hasNext()) {
    ...
}

but I write that (when Java 1.5 isn\'t available or for

15条回答
  •  伪装坚强ぢ
    2020-12-01 14:08

    Why not use the for-each construct? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too):

    List names = new ArrayList();
    names.add("a");
    names.add("b");
    names.add("c");
    
    for (String name : names)
        System.out.println(name.charAt(0));
    

提交回复
热议问题