黑马程序员技术交流社区
标题:
遍历集合
[打印本页]
作者:
papercup
时间:
2014-4-10 10:03
标题:
遍历集合
遍历集合的方式有哪些?求大神讲解下, 多谢!
作者:
耿渊博
时间:
2014-4-10 10:10
三种方式吧,for,增强for和迭代器三种遍历方式
public class ForTraverse{
public static void main(String[] args){
Collection<Integer> collection = new ArrayList<Integer>();
for(int i=0;i<5;i++){
collection.add(i);
}
System.out.println("[");
//普通for遍历
for(int i=0;i<collection.size();i++){
System.out.print(i+",");
}
System.out.println("]");
}
}
public class ForeachTraverse{
public static void main(String[] args){
Collection<Integer> collection = new ArrayList<Integer>();
for(int i=0;i<5;i++){
collection.add(i);
}
System.out.println("]");
//增强for遍历
for(Integer i:collection){
System.out.print(i+",");
}
System.out.println("]");
}
}
public class IteratorTraverse{
public static void main(String[] args){
Collection<Integer> collection = new ArrayList<Integer>();
for(int i=0;i<5;i++){
collection.add(i);
}
System.out.println("[");
//iterator遍历
Iterator<Integer> it=collection.iterator();
while(it.hasNext()){
System.out.println(collection);
}
System.out.println("]");
}
}
复制代码
作者:
491138002
时间:
2014-4-10 10:29
有三种方法:
比如 List list = new ArrayList();
list.add...
1. 对于ArrayList来说速度比较快, 用for循环, 以size为条件遍历:
int size = list.size();
for(int i = 0; i < size; i ++) {
list.get(i);
}
2. 集合类的通用遍历方式, 从很早的版本就有, 用迭代器迭代:
Iterator it = list.iterator();
while(it.hasNext()) {
Object obj = it.next();
}
3. JDK较新版本中有的方法, 但是我不太明白它的原理, 和js中的遍历很像:
for(Object obj : list) {
// obj 就是一次取出来的元素.
}
作者:
東少
时间:
2014-4-10 14:52
本帖最后由 東少 于 2014-4-10 14:53 编辑
对集合的遍历优先选用迭代器的方式 方式有四种
1,普通for循环
for(int i=0;i<list.size( );i++){
System.out.println(list.get(i));
}
2,增加for循环
for(Object obj:list){
System.out.println(obj);
}3,for循环迭代器
for(Iterator it=list.iterator();it.hasNext( ); ){
System.out.println(it.next( ));
}
4, while循环迭代器
Iterator it=list.iterator( );
while(it.hasNext( )){
System.out.println(it.next( ));
}
作者:
luoyilan222
时间:
2014-4-10 15:20
1. 对于ArrayList来说速度比较快, 用for循环, 以size为条件遍历:
int size = list.size();
for(int i = 0; i < size; i ++) {
list.get(i);
}
2. 集合类的通用遍历方式, 从很早的版本就有, 用迭代器迭代:
Iterator it = list.iterator();
while(it.hasNext()) {
Object obj = it.next();
}
3. JDK较新版本中有的方法, 但是我不太明白它的原理, 和js中的遍历很像:
for(Object obj : list) {
// obj 就是一次取出来的元素.
}
作者:
姜姗姗
时间:
2014-4-11 21:30
同意楼上所说的三种方式
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2