What is wrong with this conversion?
public int getTheNumber(int[] factors) {
ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
Collections.sort(f);
return f.get(0)*f.get(f.size()-1);
}
I made this after reading the solution found in Create ArrayList from array. The second line (sorting) in getTheNumber(...) causes the following exception:
Exception in thread “main” java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable]
What is wrong here? I do realize that sorting could be done with Arrays.sort(), I’m just curious about this one.
Let’s consider the following simplified example:
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<Integer>()ornew ArrayList<>()instead ofnew ArrayList(). If you had used it, there would have been a compile error because of trying to passList<int[]>to the constructor.There is no autoboxing from
int[]toInteger[], and anyways autoboxing is only syntactic sugar in the compiler, so in this case you need to do the array copy manually: