Arrays.asList() of an array

后端 未结 9 762
我寻月下人不归
我寻月下人不归 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:24

    I think you have found an example where auto-boxing doesn't really work. Because Arrays.asList(T... a) has a varargs parameter the compiler apparently considers the int[] and returns a List<int[]> with a single element in it.

    You should change the method into this:

    public int getTheNumber(Integer[] factors) {
        ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  
        Collections.sort(f);
        return f.get(0) * f.get(f.size() - 1);
    }
    

    and possibly add this for compatibility

    public int getTheNumber(int[] factors) {
        Integer[] factorsInteger = new Integer[factors.length];
        for(int ii=0; ii<factors.length; ++ii) {
            factorsInteger[ii] = factors[ii];
        }
    
        return getTheNumber(factorsInteger);
    }
    
    0 讨论(0)
  • 2020-11-27 16:30

    this is from Java API "sort

    public static void sort(List list) Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list)."

    it has to do with implementing the Comparable interface

    0 讨论(0)
  • 2020-11-27 16:33

    Use java.utils.Arrays:

    public int getTheNumber(int[] factors) {
        int[] f = (int[])factors.clone();
        Arrays.sort(f);
        return f[0]*f[(f.length-1];
    }
    

    Or if you want to be efficient avoid all the object allocation just actually do the work:

    public static int getTheNumber(int[] array) {
        if (array.length == 0)
            throw new IllegalArgumentException();
        int min = array[0];
        int max = array[0];
        for (int i = 1; i< array.length;++i) {
            int v = array[i];
            if (v < min) {
                min = v;
            } else if (v > max) {
                max = v;
            }
        }
        return min * max;
    }
    
    0 讨论(0)
提交回复
热议问题