[英]Can we use IntStream#sum, If sum of elements is greater than the Integer.MAX_VALUE?
What happens when the sum of elements in a stream is greater than the Integer.MAX_VALUE
? 当流中的元素总数大于Integer.MAX_VALUE
什么?
int sum = IntStream.of(Integer.MAX_VALUE, 1).sum();
In my computer this returns, -(Integer.MAX_VALUE + 1)
-> -2147483648
在我的计算机中,这将返回-(Integer.MAX_VALUE + 1)
-> -2147483648
So when should one not use java.util.stream.IntStream#sum
? 因此,什么时候不应该使用java.util.stream.IntStream#sum
?
You should use IntStream#sum if you can either guarantee that your values will not exceed the maximum integer value or you handle the overflow in the code. 如果可以保证您的值不会超过最大整数值,或者您可以处理代码中的溢出,则应使用IntStream#sum。 Otherwise, you can use LongStream, eg System.out.println(LongStream.of(Integer.MAX_VALUE, 1).sum());
否则,您可以使用LongStream,例如System.out.println(LongStream.of(Integer.MAX_VALUE, 1).sum());
whenever any integers crosses the max value it starts counting from the lower bound of integers. 每当任何整数超过最大值时,它就会从整数的下限开始计数。 for ex: if u write Integer.MAX_VAlUE+10 it will give u -2147483639. 例如:如果您编写Integer.MAX_VAlUE + 10,它将给您-2147483639。 so here, jvm started counted with 0 to the max value of integer and then after reaching the max value it started counting form (-2147483648,-2147483647,...upto -2147483639) 所以在这里,jvm从0开始计数到整数的最大值,然后在达到最大值后开始计数形式(-2147483648,-2147483647,...直到-2147483639)
int + int
does the same thing. int + int
做同样的事情。 This problem is not with sum()
but rather you are using a type which is too limited. 问题不在于sum()
,而是您使用的类型太有限。
long sum = IntStream.of(Integer.MAX_VALUE, 1)
.asLongStream()
.sum();
System.out.println(sum);
prints 版画
2147483648
All data types have limitations and you need to be aware of these when using them. 所有数据类型都有局限性,使用它们时您需要意识到这些限制。 You could argue that it would be better for an error to be produced rather than silently giving an unexpected result, but that is not how the types have been implemented. 您可能会争辩说,产生错误要比静默给出意外结果更好,但这不是实现类型的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.