Arrays.asList() of an array

后端 未结 9 794
我寻月下人不归
我寻月下人不归 2020-11-27 15:41

What is wrong with this conversion?

public int getTheNumber(int[] factors) {
    ArrayList f = new ArrayList(Arrays.asList(factors));  
    Co         


        
9条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 16:14

    Let's consider the following simplified example:

    public class Example {
        public static void main(String[] args) {
            int[] factors = {1, 2, 3};
            ArrayList f = new ArrayList(Arrays.asList(factors));
            System.out.println(f);
        }
    }
    

    At the println line this prints something like "[[I@190d11]" which means that you have actually constructed an ArrayList that contains int arrays.

    Your IDE and compiler should warn about unchecked assignments in that code. You should always use new ArrayList() or new ArrayList<>() instead of new ArrayList(). If you had used it, there would have been a compile error because of trying to pass List to the constructor.

    There is no autoboxing from int[] to Integer[], and anyways autoboxing is only syntactic sugar in the compiler, so in this case you need to do the array copy manually:

    public static int getTheNumber(int[] factors) {
        List f = new ArrayList();
        for (int factor : factors) {
            f.add(factor); // after autoboxing the same as: f.add(Integer.valueOf(factor));
        }
        Collections.sort(f);
        return f.get(0) * f.get(f.size() - 1);
    }
    

提交回复
热议问题