简体   繁体   中英

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

I have an array like

int [] nums={1,2,3,1,1,3};

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

Vector<Integer> num= new Vector<Integer>(Arrays.asList(nums));

and got this error

java: method addAll in class java.util.Collections cannot be applied to given types;
  required: java.util.Collection<? super T>,T[]
  found:    java.util.Vector<java.lang.Integer>,int[]
  reason: inference variable T has incompatible bounds

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

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:

List<Integer> list = Arrays.stream(nums).mapToObj(x -> x).toList();

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:

List<Integer> list = new ArrayList<Integer>();
for (int n : nums) list.add(n);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM