迭代器遍历集合

用Iterator实现遍历集合

总结:

List属于线性集合,有序,按照数组形式有序添加。   (Vector, ArrayList, LinkedList)

而Set属于非线性的,是无序的,顺序不一定一致。   (HashSet)

对于HashSet,其实它返回的顺序是按Hashcode的顺序。

如果迭代也有序,则可以用LinkedHashSet。

使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码。

示例:

[java] view plain copy
 
  1. Collection coll = new Vector();            //LinkedList(); //ArrayList();  
  2. coll.add("Tody");  
  3. coll.add("is");  
  4. coll.add("Sunday.");  
  5.   
  6. // Output all elements by iterator  
  7. Iterator it = coll.iterator();  
  8. while(it.hasNext()) {  
  9.     System.out.print(it.next() + " ");  
  10. }  

输出:

Tody is Sunday.   ------总结--------Vector--有序

[java] view plain copy
 
  1. Collection coll = new HashSet();  
  2. coll.add("Tody");  
  3. coll.add("is");  
  4. coll.add("Sunday.");  
  5.   
  6. // Output all elements by iterator  
  7. Iterator it = coll.iterator();  
  8. while(it.hasNext()) {  
  9.     System.out.print(it.next() + " ");  
  10. }  

输出:

is Sunday. Tody   ----- HashSet()---无序

原文地址:https://www.cnblogs.com/Darkqueen/p/9172598.html