我正在用 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>();。我該如何修復它?
1 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
快速瀏覽一下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.
添加回答
舉報
0/150
提交
取消