线程“main”中的异常 java.lang.ClassCastException: [我无法转换为 java.lang.Integer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28791359/
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
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Integer
提问by Ashish Patil
List<Integer> P = new ArrayList(Arrays.asList(p)); // Copies array p into Arraylist P
P.sort(null);
List<Integer> kk = new ArrayList();
kk.set(0, P.get(0)+k); //Exception generated on this line
I do not know why I'm unable to set it that way. Can anyone please help me on this? Thanks.
我不知道为什么我不能这样设置。任何人都可以帮我解决这个问题吗?谢谢。
回答by Eran
If p
is a primitive array int[]
, Arrays.asList(p)
would return a List whose single element is an int[]
. That would explain why P.get(0)
can't be cast to an Integer.
如果p
是原始数组int[]
,Arrays.asList(p)
将返回一个列表,其单个元素是int[]
。这将解释为什么P.get(0)
不能转换为整数。
Change p
to Integer[]
, and Arrays.asList()
would generate the List you desire.
更改p
为Integer[]
,Arrays.asList()
将生成您想要的列表。
It would also allow you to change this line :
它还允许您更改此行:
List<Integer> P = new ArrayList(Arrays.asList(p));
to
到
List<Integer> P = Arrays.asList(p);
You should avoid assigning a raw type to a generic type. This way you'd get a compilation error instead of a runtime error when you assign a List of the wrong type to P
(which is easier to find and fix).
您应该避免将原始类型分配给泛型类型。这样,当您将错误类型的 List 分配给P
(更容易查找和修复)时,您会收到编译错误而不是运行时错误。