What does the syntax mean in Java: new Stream

2019-02-24 19:23发布

I have encountered the following Java syntax that I don't recognize.

This part is fine:

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

But this I don't get:

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

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

What it is?

3条回答
The star\"
2楼-- · 2019-02-24 19:53

This is providing an inline (anonymous) subclass of the Stream class.

Functionally, it is the same as:

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

and

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

but as this class definition isn't used outside the method body, you can define it as anonymous.

查看更多
萌系小妹纸
3楼-- · 2019-02-24 20:07

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

Assigns a new instance of an anonymous implementation of Stream<Integer> (that contains a virtually unlimited number of 1s. You may find more on anonymous classes in Java In A Nutshell

查看更多
Viruses.
4楼-- · 2019-02-24 20:09

This is defining a Anonymous class which implements the Stream interface. To implement the interface we need to implement the method next.

查看更多
登录 后发表回答