2010-02-02 69 views
3

我遇到了以下我不認識的Java語法。Java中的語法意味着什麼:new Stream <Integer>(){...}?

這部分是好的:

public abstract class Stream<T> implements Iterator<T> { 
    public boolean hasNext() { 
     return true; } 
    public void remove() { 
     throw new RuntimeException("Unsupported Operation"); } 
} 

但是,這我不明白:

Stream<Integer> ones = new Stream<Integer>() { 
    public Integer next() { 
     return 1; } 
}; 

while(true){ 
    System.out.print(ones.next() + ", "); 
} 

它是什麼?

回答

4

這是提供Stream類的內聯(匿名)子類。

功能上,它是一樣的:

public NewClass extends Stream { 
    public Integer next() { 
     return 1; 
    } 
} 

void someMethodInAnotherClass { 
    Stream stream = new NewClass(); 
} 

但作爲這個類的定義不是方法體外使用時,可以將其定義爲匿名。

2

ones = new Stream<Integer>() {
public Integer next() {
return 1; }
};

分配一個匿名實現Stream<Integer>(即包含1秒的幾乎無限數量的新實例。您可能會發現Java In A Nutshell

0

這是定義一個匿名類的更多的匿名類,其實現Stream接口,爲了實現接口,我們需要實現下面的方法。