Varargs to ArrayList problem in Java

后端 未结 4 1042
一整个雨季
一整个雨季 2020-12-05 04:20

I don\'t understand why the following does not work:

public void doSomething(int... args){
  List broken = new ArrayList(Arrays         


        
相关标签:
4条回答
  • 2020-12-05 04:31

    In this case, autoboxing (automatic conversion from int to Integer) doesn't work. You have to add each int manually to the list.

    If you need code like that often, consider using commons lang which has org.apache.commons.lang.ArrayUtils.toObject(int[])

    0 讨论(0)
  • 2020-12-05 04:34

    You can do

    public void doSomething(int... args){
        List<Integer> ints = new ArrayList<Integer>(args.length);
        for(int i: args) ints.add(i);
    }
    

    or

    public void doSomething(Integer... args){
        List<Integer> ints = Arrays.asList(args);
    }
    
    0 讨论(0)
  • 2020-12-05 04:43

    Java cannot autobox an array, only individual values. I would suggest changing your method signature to

    public void doSomething(Integer... args)
    

    Then the autoboxing will take place when calling doSomething, rather than trying (and failing) when calling Arrays.asList.

    What is happening is Java is now autoboxing each individual value as it is passed to your function. What you were trying to do before was, by passing an int[] to Arrays.asList(), you were asking that function to do the autoboxing.

    But autoboxing is implemented by the compiler -- it sees that you needed an object but were passing a primitive, so it automatically inserted the necessary code to turn it into an appropriate object. The Arrays.asList() function has already been compiled and expects objects, and the compiler cannot turn an int[] into an Integer[].

    By moving the autoboxing to the callers of your function, you've solved that problem.

    0 讨论(0)
  • 2020-12-05 04:44

    You can solve this using Guava:

    List<Integer> broken = new ArrayList<>(Ints.asList(args))
    

    Or with streams:

    List<Integer> broken = Arrays
        .stream(array)
        .boxed()
        .collect(Collectors.toCollection(ArrayList::new));
    
    0 讨论(0)
提交回复
热议问题