2010-04-25 47 views
1

我有以下代碼實現可迭代在Java中

public class A extends Iterable<Integer> { 
    ... 
    public Iterator<Integer> iterator() { 
     return new Iterator<Integer>() { 

      A a; 

      public boolean hasNext() { 
       ... 
      } 

      public Integer next() { 
       ... 
      } 

      public void remove(){ 
       ... 
      } 
}; 

我想初始化「一」字段與這個迭代方法的實例的匿名類被稱爲上。可能嗎?

謝謝。

+3

這應該是一個'實現Iterable'。 – SLaks 2010-04-25 17:36:26

回答

11

你不需要。

您可以在內部類中正常調用外部類的方法。
編譯它時,編譯器會自動生成一個隱藏字段,其中包含對外部類的引用。

要自己引用此變量,您可以編寫A.this。 (A.this是編譯器生成的領域,相當於你a場)

1

試試這個:

public class A extends Iterable<Integer> { 

    public Iterator<Integer> iterator() { 

     final A a = this; 

     return new Iterator<Integer>() { 
     public boolean hasNext() { 
      // here you can use 'a' 
     } 
     }  
    } 

} 
+0

錯了。他想要外面的'這個'。 – SLaks 2010-04-25 17:30:14

+2

說明的方式是外面的'這個'。如果你在方法iterator()中並且你要求'this'(就像我寫的那樣)它指的是iterator()是一個方法的對象。所以'a'是指'A'類型的對象。 – rmarimon 2010-04-25 20:14:02

1

用途:

A a = A.this