开发者

Yield in Python needs to be implemented in java

开发者 https://www.devze.com 2023-04-05 16:59 出处:网络
I have a following question: Write a class that takes a series of integers from a generator that generates numbers one by one. Include two functions: 1- Sum 2- Average.

I have a following question:

Write a class that takes a series of integers from a generator that generates numbers one by one. Include two functions: 1- Sum 2- Average.

I know that yield statement is the choice in python if the generator needs to generate numbers one by one by returning at each step.

How would you guys do it in java? I somehow don't have any idea of how I 开发者_如何学JAVAcan realize this

Thanks.


if you want to implement "sequence" like behavior you may choose to implement java.util.Iterator interface.

class RandomSequence implements Iterator<Integer>, Iterable<Integer> {
     private int count;
     private Random random;


     public RandomSequence(int count) {
        this.count = count;
        this.random = new Random();
     }

     Integer next() {
        count--;

        return random.nextInt();

     }

     boolean hasNext() {
        return count > 0;
     }

     Iterator<Integer> iterator() {
        return this;
     }

     public static void main(String[] args) {
         int n = 0;
         for(int n: new RandomSequence(10))
             sum += n;
     }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号