Car*_*arl 2 java iterator iterable guava
我正在使用Google Collections库AbstractIterator来实现生成器.我这样做时遇到了一个问题; 我把它缩小为更基本的类型并重现了这个问题.这种减少对于它的作用显然有点过分,通过Iterable从1计算到数字.
基本上在下面的代码中,未注释的版本起作用,而注释的版本不起作用(最后提供一个null元素,而不是以最后一个数字结尾).
我做错了什么,或者这是图书馆的问题?
private Iterable<Integer> elementGenerator(final int numelements) {
return new Iterable<Integer>() {
@Override public Iterator<Integer> iterator() {
return new AbstractIterator<Integer>(){
int localcount=0;
@Override protected Integer computeNext() {
if (localcount++ == numelements) return endOfData();
return localcount;
// return (localcount++ == numelements) ? endOfData() : localcount;
}
};
}
};
}
Run Code Online (Sandbox Code Playgroud)
我也尝试摆弄这个?:安排(例如,在返回前加上前缀并比较+1),但无济于事.我捅了一下寻找关于这个的文档,但没有找到任何东西.显然,?:语法只是方便,不是必需品,但仍然......
你得到一个NullPointerException因为使用三元运算符,条件表达式,具有不同的数字类型.在三元表达式中混合不同类型的数值时,Java有复杂的规则:JLS Section 15.25.
鉴于它endOfData()是返回的先前Integer,localcount而是一个int,Java取消装箱的值endOfData().但是,如果endOfData()返回null,则取消装箱操作会导致空指针异常.
您可以继续使用if语句,也可以将localcount声明为Integer.