List集合和Set集合的遍历方法

Set集合遍历方法:

对 set 的遍历

1.迭代遍历:
Set<String> set = new HashSet<String>();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
  String str = it.next();
  System.out.println(str);
}

2.for循环遍历:
for (String str : set) {
      System.out.println(str);
}


优点还体现在泛型 假如 set中存放的是Object

Set<Object> set = new HashSet<Object>();
for循环遍历:
for (Object obj: set) {
      if(obj instanceof Integer){
                int aa= (Integer)obj;
             }else if(obj instanceof String){
               String aa = (String)obj
             }
              ........
} 
View Code

List集合的遍历方法

List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
方法一:
超级for循环遍历
for(String attribute : list) {
  System.out.println(attribute);
}
方法二:
对于ArrayList来说速度比较快, 用for循环, 以size为条件遍历:
for(int i = 0 ; i < list.size() ; i++) {
  system.out.println(list.get(i));
}
方法三:
集合类的通用遍历方式, 从很早的版本就有, 用迭代器迭代
Iterator it = list.iterator();
while(it.hasNext()) {
  System.ou.println(it.next);
}
View Code

来源:http://www.cnblogs.com/lzq198754/p/5774593.html

          http://ahomeeye.iteye.com/blog/1235370

原文地址:https://www.cnblogs.com/hezhiyao/p/7496669.html