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

I came across the following Java syntax, which I do not know.

This part is in order:

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

But this I do not get:

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

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

What it is?

+3
source share
3 answers

This provides a built-in (anonymous) subclass of the class Stream.

Functionally, this is the same as:

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

and

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

but since this class definition is not used outside the method body, you can define it as anonymous.

+4
source

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

Stream<Integer> ( 1 s. Java

+2

This is the definition of an anonymous class that implements the Stream interface. To implement the interface, we need to implement the following method.

0
source

Source: https://habr.com/ru/post/1731006/


All Articles