Java 创建实例后如何初始化BigInteger(无法调用构造函数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6563258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialise BigInteger after creating instantces (constructor can't be called)
提问by CoolEulerProject
Imagine an instance of BigInteger
, then how to initialize it after creating instance?
想象一个 的实例BigInteger
,那么创建实例后如何对其进行初始化?
For example:
例如:
BigInteger t = new BigInteger();
How to put a value in t
?
如何将值放入t
?
If the constructor cannot be called, then what can be done, to put the value in the object?
如果无法调用构造函数,那么可以做什么,将值放入对象中?
采纳答案by Hovercraft Full Of Eels
I'm not 100% sure of what specifically is confusing you as you'd initialize the items in the BigInteger array as you would any other object array. e.g.,
我不能 100% 确定具体是什么让您感到困惑,因为您会像初始化任何其他对象数组一样初始化 BigInteger 数组中的项目。例如,
BigInteger t2 [] = new BigInteger[2];
t2[0] = new BigInteger("2");
t2[1] = BigInteger.ZERO; // ZERO, ONE, and TEN are defined by constants
// or
BigInteger[] t3 = {new BigInteger("2"), BigInteger.ZERO};
Edit 1:
Ah, now I understand your problem: you want to create a BigInteger instance and then later set its value. The answer is the same as for Strings: you can't, and that it is because BigIntegers like Strings are immutableand can't be changed once created. For this reason the class has no "setter" methods. The way to change the value of a BigInteger variableis to set it to a new BigInteger instance.
编辑 1:
啊,现在我明白你的问题了:你想创建一个 BigInteger 实例,然后再设置它的值。答案与字符串相同:你不能,这是因为像字符串这样的 BigInteger 是不可变的,一旦创建就无法更改。出于这个原因,该类没有“setter”方法。更改 BigInteger变量值的方法是将其设置为新的 BigInteger 实例。
回答by ncmathsadist
To convert a long (or a regular integer) to BigInteger, use the static factory method valueOf. The call BigInteger.valueOf(<i>someInteger</i>)
returns a new BigInteger
object holding the integer value you specify. You could also use new BigInteger("" + <i>someInteger</i>)
to get the same thing, but this is clunkier.
要将 long(或常规整数)转换为 BigInteger,请使用静态工厂方法 valueOf。该调用BigInteger.valueOf(<i>someInteger</i>)
返回一个新BigInteger
对象,其中包含您指定的整数值。你也可以使用 newBigInteger("" + <i>someInteger</i>)
来得到同样的东西,但这更笨拙。
回答by Mauro Zallocco
here are some examples:
这里有些例子:
BigInteger t = BigInteger.valueOf(23);
int i = 66;
t = BigInteger.valueOf(i);
t = BigInteger.ZERO
回答by Nikhil Nagaraju
I did something like this
我做了这样的事情
//initialize with zero
BigInteger t = BigInteger.ZERO;
//if i is any value that is to be assigned
t=t.add(BigInteger.valueOf(i));