猿问

在java中将元素推送到Vector

我正在用 Java 编写自己的自定义 BigInteger 类,并且想要在我的类的构造函数中解析整数。所以问题是,如何将数字 n 的每个数字正确添加到我的向量中,并保持正确的顺序?换句话说,如何将每个数字添加到其中,就像将它们添加到堆栈中一样?


例如,n = 1234我需要将 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>();。我该如何修复它?


慕莱坞森
浏览 100回答 1
1回答

qq_遁去的一_1

快速浏览一下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不一定建议在这种情况下使用 a。引用VectorJavadoc,从 Java 2 平台 v1.2 开始,对该类进行了改进以实现该List接口,使其成为 Java Collections Framework 的成员。与新的集合实现不同,Vector它是同步的。如果不需要线程安全的实现,建议ArrayList使用Vector.
随时随地看视频慕课网APP

相关分类

Java
我要回答