Java 迭代器

1.快速报错

1 public class FailFast {
2       public static void main(String[] args) {
3             List<String> c = new ArrayList<String>();
4             Iterator<String> it = c.iterator();
5             c.add("An object");
6             String s = it.next();  // java.util.ConcurrentModificationException
7      }
8 }

在取得迭代器之后,Java采用快速报错机制防止多个线程同时修改同一个容器的内容,而不是在事后来检查问题。

 

2.在容器中查找满足条件的元素,并将之删除

 1     public  static void main(String[] args) {
 2         HashSet hs=new HashSet();
 3         hs.add("mm");
 4         hs.add("kk");
 5         hs.add("ss");
 6         Iterator itor=hs.iterator();
 7 
 8         while(itor.hasNext()){
 9             String c=(String)itor.next();
10             if(c=="kk"){
11                 itor.remove();
12             }
13         }
14 
15        System.out.println(hs.toString());
16 
17     }

 

3.多种实现 

 1 class ReversibleArrayList<T> extends ArrayList<T> {
 2     public ReversibleArrayList(Collection<T> c) { 
 3         super(c);
 4     }
 5     
 6     public Iterable<T> reversed() {
 7              return new Iterable<T>() {
 8                       public Iterator<T> iterator() {
 9                             return new Iterator<T>() {
10                                   int current = size() - 1;
11                                   public boolean hasNext() { 
12                                       return current > -1; 
13                                   }
14                                   public T next() { 
15                                       return get(current--);
16                                   }
17                                   public void remove() { 
18                                         throw new UnsupportedOperationException();
19                                   }
20                             };
21                   }
22             };
23       }
24 }    
25 
26 public class AdapterMethodIdiom {
27     public static void main(String[] args) {
28         ReversibleArrayList<String> ral = new ReversibleArrayList<String>(Arrays.asList("To be or not to be".split(" ")));
29         for(String s : ral)
30           System.out.print(s + " ");
31         
32         System.out.println("");
33         
34         for(String s : ral.reversed())
35           System.out.print(s + " ");
36   }
37 } 
posted @ 2014-07-18 01:18  等风来。。  Views(367)  Comments(0Edit  收藏  举报
------------------------------------------------------------------------------------------------------------ --------------- 欢迎联系 x.guan.ling@gmail.com--------------- ------------------------------------------------------------------------------------------------------------