首页 > 其他 > 详细

Iterator and Iterable Iterable range

时间:2020-09-28 14:52:44      阅读:25      评论:0      收藏:0      [点我收藏+]

Given a class named Range. It represents a range from A (inclusive) to B (exclusive). The class implements the interface Iterable, therefore, an instance of Range can be used in the for-each loop.

Write a body of the overridden method iterator so that the following code works correctly:

Range range = new Range(2, 6);

for (Long val : range) {
System.out.println(val);
}
It must print:

2
3
4
5
Report a typo
Sample Input 1:

2 6
Sample Output 1:

2
3
4
5


import java.util.Iterator;

class Range implements Iterable<Long> {

    private long fromInclusive;
    private long toExclusive;

    public Range(long from, long to) {
        this.fromInclusive = from;
        this.toExclusive = to;
    }

    @Override
    public Iterator<Long> iterator() {
        // write your code here
        return new Iterator<Long>() {
            private long current = fromInclusive;
            
            @Override
            public boolean hasNext() {
                return current < toExclusive;
            }
            
            @Override
            public Long next() {
                return current++;
            }
        };
    }
}

Iterator and Iterable Iterable range

原文:https://www.cnblogs.com/longlong6296/p/13744612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!