Java,Google Collections Library; AbstractIterator有问题吗? [英] Java, Google Collections Library; problem with AbstractIterator?
问题描述
我正在使用Google Collections库 AbstractIterator 实现生成器。这样做我遇到了一个问题;我把它缩小为更基本的类型并重现了这个问题。这种减少对于它的作用显然有点过分,通过Iterable从1计数到数字。
I am using the Google Collections library AbstractIterator to implement a generator. I ran across a problem while doing so; I've reduced it to a more basic type and reproduced the problem. This reduction is obviously overkill for what it does, counting from 1 to numelements via an Iterable.
基本上在以下代码中,未注释的版本可以工作,而注释的版本可以not(最后提供一个null元素,而不是以最后一个数字结尾)。
Essentially in the following code, the uncommented version works, and the commented one does not (provides a null element last, instead of ending on the last number).
我做错了什么,或者这是库的问题?
Am I doing something wrong, or is this a problem with the library?
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;
}
};
}
};
}
我还尝试摆弄?:
安排(例如,在返回前加上前缀并与+1比较),无济于事。我捅了一下寻找关于这个的文档,但没有找到任何东西。显然,?:
语法只是方便,不是必需,但仍然......
I also tried fiddling around with the ?:
arrangement (e.g., prefixing the return and comparing to +1 instead), to no avail. I poked around a bit looking for documentation about this, but didn't find anything. Obviously, the ?:
syntax is only a convenience, not a necessity, but still...
推荐答案
由于使用了具有不同数值类型的三元运算符条件表达式,因此得到 NullPointerException
。在三元表达式中混合不同类型的数值时,Java有复杂的规则: JLS第15.25节
。
You get a NullPointerException
because of the use of the ternary operator, conditional expression, with different numerical types. Java has complex rules when mixing numerical values of different types in ternary expression: JLS Section 15.25
.
鉴于 endOfData()
之前返回 Integer
,而 localcount
是 int
,Java取消装箱 endOfData()
的值。但是,假设 endOfData()
返回null,则取消装箱操作会导致空指针异常。
Given that endOfData()
is preceived to return Integer
, while localcount
is an int
, Java unboxes the value of endOfData()
. However, given that endOfData()
returns a null, the unboxing operation results into a null pointer exception.
你可以继续使用if语句,也可以将localcount声明为 Integer
。
You can either continue using the if statement, or declare localcount as Integer
.
这篇关于Java,Google Collections Library; AbstractIterator有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!