What does the syntax mean in Java: new Stream<Integer>(){ … }?

冷暖自知 提交于 2019-12-20 02:13:08

问题


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?


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/2184052/what-does-the-syntax-mean-in-java-new-streaminteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!