Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there BigInteger(String) but no BigInteger(long)?

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?

like image 479
Morad Avatar asked Oct 03 '14 20:10

Morad


2 Answers

@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.

like image 80
Alboz Avatar answered Sep 29 '22 16:09

Alboz


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.

like image 29
Krease Avatar answered Sep 29 '22 17:09

Krease