Why is there BigInteger(String) but no BigInteger(long)?
Asked Answered
B

2

8

In Java, to convert a String to BigInteger you use the constructor new BigInteger(String) but to convert an int/long you use the factory function BigInteger.valueof(long), why is that?

Beneficence answered 3/10, 2014 at 20:24 Comment(3)
That is just how they designed it when they built it. You would have to ask whoever created BigInteger that question.Ohare
Typically the implementation caches common values like positive integers close to 0.Jennettejenni
@JakeCobb - exactly - in this case, it caches values between -16 and 16.Depreciatory
D
12

There actually is a BigInteger(long) constructor, but it's private. The javadoc on the factory method provides info on why:

This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

Depreciatory answered 3/10, 2014 at 20:30 Comment(0)
F
21

@Morad you can find the answer in the docs: JavaDoc of BigInteger.valueOf(long):

This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

Explained: BigInteger.valueOf(long) does exactly what you would expect from the BigInteger(long) constructor, and it is (or should be) more efficient at it.

Fabiano answered 3/10, 2014 at 20:29 Comment(0)
D
12

There actually is a BigInteger(long) constructor, but it's private. The javadoc on the factory method provides info on why:

This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

Depreciatory answered 3/10, 2014 at 20:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.