为什么我们在将 int 转换为 bigInteger 时不使用 new 关键字,而在将 string 转换为 bigInteger 时使用 new 关键字?

问题描述

在从int到BigInteger的转换中,我们写

int n = 100;
BigInteger bi = BigInteger.valueOf(n);

当我们打印 bi 时,我们得到 100。 但是,在从 String 到 BigInteger 的转换中,我们写

String str = "100";
BigInteger biStr = new BigInteger(str);

biStr 对象使用 new 关键字来存储从字符串转换而来的 BigInteger 值的值,但是 bi 对象将在哪里存储其从字符串转换而来的 BigInteger 值内部

解决方法

引用 BigInteger javadoc for valueOf

“这种“静态工厂方法”优先于(长)构造函数提供,因为它允许重用常用的 BigInteger。”