简体   繁体   中英

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 ?

int sum = IntStream.of(Integer.MAX_VALUE, 1).sum();

In my computer this returns, -(Integer.MAX_VALUE + 1) -> -2147483648

So when should one not use 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. Otherwise, you can use LongStream, eg 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. 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)

int + int does the same thing. This problem is not with sum() but rather you are using a type which is too limited.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM