开发者

Collections.addAll, Queue<Integer> and int[]

开发者 https://www.devze.com 2023-03-14 04:35 出处:网络
The following code doesn\'t work though it seems quite correct: import java.util.*; public class Jaba {

The following code doesn't work though it seems quite correct:

import java.util.*;

public class Jaba {

    public static void main(String args[]) {
        Random rand = new Random();
        int[] array = new int[10];
        for (int i = 0; i < array.length; ++i) {
            array[i] = 开发者_开发技巧rand.nextInt(30);
        }
        Queue<Integer> que = new PriorityQueue<Integer>();
        Collections.addAll(que, Arrays.asList(array));
    }

}

What should be fixed?


Arrays.asList takes an array of objects. (It's the only option, as it can't return a List<int>.)

When you pass an int[] to Arrays.asList, it will be interpreted as a singleton array containing one int[].

You'll have to

  • Change to a for-loop:

    for (int i : array)
        que.add(i);
    

    or

  • change the type of array from int[] to Integer[].

    This would allow you to do

    que.addAll(Arrays.asList(array))
    

    or,

    Collections.addAll(que, array);
    

The reason that Collections.addAll(que, Arrays.asList(array)) fails is that it takes a T... as second argument, which is really an array and not a List.


method addAll in class java.util.Collections cannot be applied to given types; required: java.util.Collection,T[] found: java.util.List,java.util.List reason: no instance(s) of type variable(s) T exist so that argument type java.util.List conforms to formal parameter type T[]

Because List< int[]> != List< Integer>. Arrays.asList(T ...) returns T[], so giving it an int[] will return a List of int[].

Why not just use:

    Random rand = new Random();
    Queue<Integer> que = new PriorityQueue<Integer>();
    for (int i = 0; i < 10; ++i) {
           que.add(rand.nextInt(30));
    }

Do you really need the int[] array? If not, the above should do the job.

-- Edit, with Collections.addAll:

    Random rand = new Random();
    Queue<Integer> que = new PriorityQueue<Integer>();
    Integer[] toAdd = new Integer[10];
    for (int i = 0; i < toAdd.length; ++i) {
           toAdd[i] = rand.nextInt(30);
    }
    Collections.addAll(que, toAdd); // T ... Elements can be either separate elements, or a T[] array.


You could use the google guava Ints class:

    que.addAll(Ints.asList(array));

Where Ints.asList() converts an int[] to a List<Integer> which is what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号