Java 数组的 Arrays.asList()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1248763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arrays.asList() of an array
提问by nbl
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:
我在阅读了在Create ArrayList from array 中找到的解决方案后做了这个。第二行(排序)getTheNumber(...)
导致以下异常:
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable]
线程“main”中的异常 java.lang.ClassCastException: [我无法转换为 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.
这里有什么问题?我确实意识到排序可以用 来完成Arrays.sort()
,我只是对这个很好奇。
采纳答案by Esko Luontola
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);
}
}
At the println line this prints something like "[[I@190d11]" which means that you have actually constructed an ArrayList that contains int arrays.
在 println 行,它会打印类似 "[[I@190d11]" 的内容,这意味着您实际上已经构建了一个包含 int arrays的 ArrayList 。
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.
您的 IDE 和编译器应该警告该代码中未经检查的赋值。您应该始终使用new ArrayList<Integer>()
或new ArrayList<>()
代替new ArrayList()
。如果你使用过它,就会因为试图传递List<int[]>
给构造函数而出现编译错误。
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:
从int[]
to没有自动装箱Integer[]
,无论如何自动装箱只是编译器中的语法糖,因此在这种情况下,您需要手动进行数组复制:
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);
}
回答by CoDeR
this is from Java API "sort
这是来自Java API“排序
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)."
public static void sort(List list) 根据其元素的自然顺序,将指定列表按升序排序。列表中的所有元素都必须实现 Comparable 接口。此外,列表中的所有元素必须相互比较(即,对于列表中的任何元素 e1 和 e2,e1.compareTo(e2) 不得抛出 ClassCastException)。”
it has to do with implementing the Comparable interface
它与实现 Comparable 接口有关
回答by Kevin Boyd
As far as I understand it, the sort function in the collection class can only be used to sort collections implementing the comparable interface.
据我了解,collection类中的sort函数只能用于对实现了可比接口的collection进行排序。
You are supplying it a array of integers. You should probably wrap this around one of the know Wrapper classes such as Integer. Integer implements comparable.
您正在为其提供一个整数数组。您可能应该将它包装在一个已知的 Wrapper 类中,例如 Integer。整数实现可比。
Its been a long time since I have worked on some serious Java, however reading some matter on the sort function will help.
自从我从事一些严肃的 Java 工作已经很长时间了,但是阅读有关排序功能的一些内容会有所帮助。
回答by sepp2k
Arrays.asList(factors)
returns a List<int[]>
, not a List<Integer>
. Since you're doing new ArrayList
instead of new ArrayList<Integer>
you don't get a compile error for that, but create an ArrayList<Object>
which contains an int[]
and you then implicitly cast that arraylist to ArrayList<Integer>
. Of course the first time you try to use one of those "Integers" you get an exception.
Arrays.asList(factors)
返回 a List<int[]>
,而不是 a List<Integer>
。由于您正在执行new ArrayList
而不是new ArrayList<Integer>
您不会因此而收到编译错误,而是创建一个ArrayList<Object>
包含 an 的对象int[]
,然后将该数组列表隐式转换为ArrayList<Integer>
. 当然,当您第一次尝试使用其中一个“整数”时,您会遇到异常。
回答by Rich Seller
You are trying to cast int[] to Integer[], this is not possible.
您正在尝试将 int[] 转换为 Integer[],这是不可能的。
You can use commons-lang's ArrayUtils to convert the ints to Integers before getting the List from the array:
在从数组中获取列表之前,您可以使用 commons-lang 的 ArrayUtils 将整数转换为整数:
public int getTheNumber(int[] factors) {
Integer[] integers = ArrayUtils.toObject(factors);
ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(integers));
Collections.sort(f);
return f.get(0)*f.get(f.size()-1);
}
回答by Tom
Use java.utils.Arrays:
使用 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;
}
回答by dfa
there are two cause of this exception:
此异常有两个原因:
1
1
Arrays.asList(factors)
returns a List<int[]>
where factors
is an int array
Arrays.asList(factors)
返回一个List<int[]>
wherefactors
是一个int 数组
2
2
you forgot to add the type parameter to:
您忘记将类型参数添加到:
ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
with:
和:
ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));
resulting in a compile-timeerror:
导致编译时错误:
found : java.util.List<int[]> required: java.util.List<java.lang.Integer>
回答by Robert Petermeier
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.
我想你已经找到了一个自动装箱不起作用的例子。因为Arrays.asList(T... a)
有一个 varargs 参数,编译器显然会考虑 int[] 并返回一个List<int[]>
包含单个元素的 a 。
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);
}
回答by Nuno Rafael Figueiredo
This works from Java 5 to 7:
这适用于 Java 5 到 7:
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);
}
In Java 4 there is no vararg... :-)
在 Java 4 中没有 vararg ... :-)