Skip to content
Advertisement

Best way to convert an array of integers to a vector? in java

I have an array like

JavaScript

So i wanted it convert it into an vector I did try

JavaScript

and got this error

JavaScript

Is there a way to change the types or a faster method than this?

Advertisement

Answer

NB: Before I answer the question, Vector is deprecated and should never be used. You’re looking for List. Whatever property Vector has that makes you think you need it, I really doubt it.

The problem here is that List (and Vector) are generified, and generics cannot be a primitive type. So, int[] and Integer[] aren’t the same thing, and for the same reason, you can’t casually turn an int[] into a List<Integer>. Instead, Arrays.asList(someIntArray) gives you a list with only one element in it, and that list is of type List<int[]> – in other words, nums is treated as the single element of a list of int arrays.

There is no method in the java.* libraries that turns an int[] into a List<Integer> (or Vector<Integer>, naturally).

An easy-ish way to do it:

JavaScript

This will first create an IntStream of your numbers. It then maps the int values to Integer values, using the identity operation which gets automatically sugared into x -> Integer.valueOf(x) (if you find it more readable like so, then go ahead and write it like that), and then turns the whole thing into a list. If toList() doesn’t work – you’re on java pre-16, write .collect(Collectors.toList()) instead of .toList().

If you don’t like the above, a simple for loop would then do the job. This works just as well:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement