Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "big = big.add(..)" need to be used to sum BigIntegers?

I am a beginner. This might be a silly question.

I have an array of really big numbers. I need to find the sum of all those numbers in the array. I defined a BigInteger and initialised it to zero. Now I will traverse the array and add each element to this BigInteger.

BigInteger big = BigInteger.ZERO;
for(BigInteger b : array){
   big.add(b);
}

No compilation error but big value was still zero,the code didn't work. So, I checked it up and learnt BigInteger add method returns the sum. I modified above code.

big = big.add(b);

Now this worked fine.

My Question: What actually is happening there? Why didn't the first code update big value.

Can I compare this BigInteger.add() with collection.add()

More insight is appreciated. Thank you.

like image 520
Charan Avatar asked Aug 01 '15 06:08

Charan


2 Answers

Why didn't the first code update big value.

BigInteger is immutable, you can't change it any more than you can change a String, or any primitive wrapper.

e.g.

String s = "Hello ";
s.concat("World"); // doesn't change anything.

s = s.concat("World"); // Updates 's'

Can I compare this BigInteger.add() with collection.add()

Collections are mutable, but this scalar value is not.

Using mutable objects is largely a performance concession. If you have a collection which takes a complete copy each time it would perform very badly.

like image 147
Peter Lawrey Avatar answered Nov 03 '22 01:11

Peter Lawrey


This is the JavaDoc for the method

public BigInteger add(BigInteger val)
Returns a BigInteger whose value is (this + val).

Parameters:
val - value to be added to this BigInteger.

Returns:
this + val

This means that rather than modifying the value, it calculates a new value and returns it. When you perform big = big.add(b), you're running that method, taking the resultant value, and replacing the original value of big with it.

Consider the equivalent using ints, x and y.

int x = 3;
int y = 4;
x + y; // At this point, x is still 3 - as you've not assigned the result of this calculation anywhere
x = x + y; // Now - x will be 7
like image 29
Ren Avatar answered Nov 03 '22 00:11

Ren