Search code examples
javagetnestedbiginteger

Java Big Integer - Nested get


I'm having trouble working with BigInteger class. I had a input list with just normal ints, but I had to change the said to list to accept Big Integers as well.

In multiple parts of my code I have instructions like this one:

input.set(input.get(i + 3), 
        (input.get(input.get(i + 1)) + input.get(input.get(i + 2))));

And they produce errors like this one:

Cannot convert type of expression  
    (input.get(input.get(i + 1)) + input.get(input.get(i + 2))) from int to E  

I have tried doing something like this:

(input.get(BigInteger.valueOf(input.get(i + 1)))
    .add(BigInteger.valueOf(input.get(BigInteger(input.get(i + 2)))))));

But that hasn't helped.


Solution

  • You could write your own method taking a List<BigInteger> to be searched and a String value to be found, because there is the constructor new BigInteger(String value). You could find the value by streaming the list:

    public static BigInteger findIn(List<BigInteger> source, String value) {
        return source.stream()
                .filter(bi -> bi.equals(new BigInteger(String.valueOf(value))))
                .findFirst()
                .orElse(null);
    }
    

    This assumes that the values to be searched for are converted into Strings beforehand.

    Why Strings?

    That is already explained in the answer given by @Amongalen:
    (..) BigInteger can store much bigger numbers than can be represented with int.
    Which means you may have to pass a value that is not storable in an int variable.

    You can use it as follows:

    public static void main(String[] args) {
        // provide some sample data
        List<BigInteger> bigInts = new ArrayList<>();
        bigInts.add(new BigInteger("123456789101112"));
        bigInts.add(new BigInteger("123456789101113"));
        bigInts.add(new BigInteger("123456789101114"));
        bigInts.add(new BigInteger("123456789101115"));
        bigInts.add(new BigInteger("54"));
    
        // provide a variable for the expression
        int i = 51;
        // convert your expression to String
        BigInteger n = findIn(bigInts, String.valueOf(3 + i));
    
        System.out.println(n.toString());
    }
    

    The output is just 54.

    Please note that you cannot simply add a value to an existing BigInteger and expect it to change, because an arithmetical operation does not alter an existing instance but returns a new one:

    From JavaDocs:

    public BigInteger add(BigInteger val)
    

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

    Conclusion
    You have to
    (1) find the value in the list,
    (2) perform the arithmetical operation and store the return value,
    (3) remove the old value from the list and
    (4) add the new one.