数组的 Arrays.asList() [英] Arrays.asList() of an array
问题描述
这种转换有什么问题?
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);
}
我在阅读了中的解决方案后做了这个从数组创建 ArrayList.getTheNumber(...)
中的第二行(排序)导致以下异常:
I made this after reading the solution found in Create ArrayList from array. The second line (sorting) in getTheNumber(...)
causes the following exception:
线程main"中的异常 java.lang.ClassCastException: [我无法转换为 java.lang.Comparable]
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable]
这里有什么问题?我确实意识到可以使用 Arrays.sort()
进行排序,我只是对这个很好奇.
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:
public class Example {
public static void main(String[] args) {
int[] factors = {1, 2, 3};
ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
System.out.println(f);
}
}
在 println 行,这会打印类似[[I@190d11]"的内容,这意味着您实际上已经构建了一个包含 int arrays 的 ArrayList.
At the println line this prints something like "[[I@190d11]" which means that you have actually constructed an ArrayList that contains int arrays.
您的 IDE 和编译器应该警告该代码中未经检查的赋值.您应该始终使用 new ArrayList
或 new ArrayList<>()
而不是 new ArrayList()
.如果你使用过它,就会因为试图将 List
传递给构造函数而出现编译错误.
Your IDE and compiler should warn about unchecked assignments in that code. You should always use new ArrayList<Integer>()
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<int[]>
to the constructor.
从 int[]
到 Integer[]
没有自动装箱,无论如何自动装箱只是编译器中的语法糖,所以在这种情况下你需要做手动复制数组:
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<Integer> f = new ArrayList<Integer>();
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);
}
这篇关于数组的 Arrays.asList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!