java - 在java中将元素推送到Vector

标签 java vector biginteger

我正在用 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);
        }
    }

如果我定义ArrayListLong构造函数第一个构造函数出现错误。同样,add()中的错误第二个方法,如果我定义 AVector<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 use ArrayList in place of Vector.

关于java - 在java中将元素推送到Vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58402545/

相关文章:

java - CDI生产方法-注入(inject)

java - 将 Google Protocol Buffers 与 Java NIO 结合使用?

r - 有条件地删除向量中的元素

java - 从 Cassandra ResultSet 获取一个 BigInteger 属性

java 。执行其他类中的一个类?

java - 在 GXT 中重新渲染

c++ - 如何将字符串与 vector 值进行比较?

javascript - 查明 LngLat 点是否位于其他两个点之间

Java:BigInteger,如何通过OutputStream编写它

c - 按位算术教程