Jay
Jay

Reputation: 185

how do i turn a array of integers into a vector?

I'm trying to turn an array of inputed integers to a vector, then output the result. I've searched google and every example uses the " (Arrays.asList(randomArray)". However, when i try to compile i get a "cannot find symbol - constructor Vector(java.util.list)" what is the correct code to convert an array to a vector?

here is my code:

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));

Upvotes: 0

Views: 77

Answers (3)

Srinivas
Srinivas

Reputation: 1790

Your vecArray should be of type Integer instead of primitive int.

Integer [] vecArray = new Integer[vecSize];

Upvotes: 0

Aleksander Blomsk&#248;ld
Aleksander Blomsk&#248;ld

Reputation: 18542

The problem is that you have an array of primitive type (int), which doesnt work well with Arrays.asList(). Arrays.asList(vecArray) actually returns a List<int[]> with one element (your array).

The easiest fix is to populate the vector yourself manually:

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

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114767

The Problem is, that your array is not an Integer[] but an int[], and java can't convert between those two types.

You can either replace the int by Integer or copy the values from the int[] to a fresh Integer[] (with another loop) and feed that into the vector.

In your code, the last statement tries to copy all int[] objects into the vector but you hoped, that it would automatically inbox and copy the values from the array. But that is not the case.

BTW, the error message gives a hint:

The constructor Vector<Integer>(List<int[]>) is undefined

You expected to use the constructor Vector<Integer>(List<Integer>) instead and Java decided to look for the one from the error message.

Upvotes: 3

Related Questions