2013-01-10 31 views
0

我想將輸入整數的數組轉換爲向量,然後輸出結果。我搜索谷歌和每個例子使用「(Arrays.asList(randomArray)」。但是,當我嘗試編譯我得到一個「無法找到符號 - 構造函數向量(java.util.list)」什麼是正確的代碼?一個數組轉換爲矢量如何將整數數組轉換爲矢量?

這裏是我的代碼:

Scanner inputNumber = new Scanner(System.in); 
System.out.println("How big would you like the vector to be?"); 
int vecSize = inputNumber.nextInt(); 
int [] vecArray = new int[vecSize]; 
int [] primeArray = new int[vecSize]; 
System.out.println("Please enter " + vecSize + " postive numbers please: "); 

for (int i = 0; i < vecSize; i++) { 
    int arrayInput = inputNumber.nextInt(); 
    if (arrayInput > 0){ 
    vecArray[i] = arrayInput; 
    } 
} 
Vector<Integer> arrayToVec = new Vector<Integer>(Arrays.asList(vecArray)); 
+1

你爲什麼要使用矢量?如果你想同步,使用'Collections.synchronizedList'。 – zengr

+0

...如果你不需要線程安全同步,你可以使用'ArrayList'或者'Arrays.asList()' –

回答

1

的問題是,你有原始類型(INT),這與犯規Arrays.asList()工作良好的陣列。 Arrays.asList(vecArray)實際上返回一個List<int[]>與一個元素(您的數組)。

最簡單的解決方法是自己手動填充載體:

Vector<Integer> arrayToVec = new Vector<Integer>(); 
for (int i : vecArray) { 
    arrayToVec.add(i); 
} 
+0

我甚至不知道這是可能的!非常感謝你 – Jay

3

的問題是,你的陣列是不是Integer[]而是int[],和java不能這兩種類型之間的轉換。

您可以將int替換爲Integer,也可以將中的值更新爲Integer[](使用另一個循環)並將其輸入到矢量中。

在您的代碼中,最後一條語句嘗試將所有int[]對象複製到向量中,但是您希望它會自動收件箱並複製數組中的值。但事實並非如此。

BTW,錯誤消息給出了一個暗示:

構造Vector<Integer>(List<int[]>)未定義

您希望使用構造Vector<Integer>(List<Integer>),而不是和Java決定找錯誤消息中的一個。

0

vecArray應該代替原始intInteger類型。

Integer [] vecArray = new Integer[vecSize];