我正在用 Java 编写自己的自定义 BigInteger 类,并且想要在我的类的构造函数中解析整数。所以问题是,如何将数字 n 的每个数字正确添加到我的 vector 中,并保持正确的顺序?换句话说,如何将每个数字添加到其中,就像将它们添加到堆栈中一样?
例如对于 n = 1234
我需要将其添加到我的 vector 中,例如 1 2 3 4。
这就是我已经拥有的:
class VeryLong {
Vector<Integer> A = new Vector<Integer>();
VeryLong(int n) {
while (n > 0) {
// A.push(n % 10)
n /= 10;
}
}
还有一个问题,我需要重载该类的构造函数以从 int 和 long 创建 VeryLong 的实例。这是我的代码:
private ArrayList<Long> A = new ArrayList<>();
private VeryLong(int n) {
while (n > 0) {
A.add(long()(n % 10));
n /= 10;
}
while (!A.isEmpty()) {
System.out.println(A.get(0));
A.remove(0);
}
}
private VeryLong(long n) {
while (n > 0) {
A.add(n % 10);
n /= 10;
}
while (!A.isEmpty()) {
System.out.println(A.get(0));
A.remove(0);
}
}
如果我定义ArrayList
的Long
构造函数第一个构造函数出现错误。同样,add()
中的错误第二个方法,如果我定义 A
如Vector<Integer> A = new Vector<Integer>();
。我该如何修复它?
最佳答案
快速浏览一下 the Javadoc ,没有 push
方法。但是,我认为您正在寻找的是 add
方法,它将给定的项目添加到 Vector
的末尾(或者如果提供了附加整数,则在该方法中) vector 的索引
)。在您的示例中,这看起来像
class VeryLong {
Vector<Integer> A = new Vector<Integer>();
VeryLong(int n) {
while (n > 0) {
A.add(0, n % 10);
n /= 10;
}
}
在本例中,我编写了 A.add(0, n % 10);
因为您希望末尾有“不太重要”的数字。在这种情况下,添加的每个连续数字都会将现有元素推到列表的“右侧”或末尾。这应该可以解决你的问题。 :)
正如 acarlstein 指出的那样,在这种情况下不一定推荐使用 Vector
。引用自 Vector
Javadoc ,
As of the Java 2 platform v1.2, this class was retrofitted to implement the
List
interface, making it a member of the Java Collections Framework. Unlike the new collection implementations,Vector
is synchronized. If a thread-safe implementation is not needed, it is recommended to useArrayList
in place ofVector
.
关于java - 在java中将元素推送到Vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58402545/