英文:
Running into [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer at runtime
问题
在运行时,当尝试将List<Integer[]>转换为Integer[]时,我一直遇到上面的错误。
public static Integer[] findKthLargest(List<Integer[]> list, int k) throws IllegalArgumentException {
Integer[] arr = (Integer[]) list.toArray();
insertionSort(arr, new ArrayComparator());
System.out.println(Arrays.toString(arr));
return arr[k];
}
我尝试过将List<Integer[]>强制转换为Object[],然后再转换为Integer[],但我仍然遇到相同的错误。我不能更改方法头部。
我还没有完成方法的其余部分的实现,所以我放置了一个println来查看它是否会为我提供大致预期的结果。
英文:
At runtime, I keep running into the error above when trying to make a List<Integer[]> to an Integer[].
public static Integer[] findKthLargest(List<Integer[]> list, int k) throws IllegalArgumentException {
Integer[] arr = (Integer[]) list.toArray();
insertionSort(arr, new ArrayComparator());
System.out.println(Arrays.toString(arr));
return arr[k];
I've tried casting the List<Integer[]> into an Object[] and then to an Integer[] but I run into the same error. I can't change the method header
I haven't finished the rest of the method's implementation yet so I placed a println to see if it'd provide me with roughly the results I expected.
答案1
得分: 1
以下是翻译好的部分:
无法使用以下代码:
Integer[] arr = (Integer[]) list.toArray();
如果我理解您想要做的事情,您需要类似以下的代码:
Integer[] arr = list.stream()
.flatMap(Arrays::stream)
.toArray(Integer[]::new);
示例:
List<Integer[]> list = List.of(new Integer[]{1, 2, 3}, new Integer[]{4, 5, 5});
Integer[] arr = list.stream()
.flatMap(Arrays::stream)
.toArray(Integer[]::new);
输出结果:
[1, 2, 3, 4, 5, 5]
英文:
You can't use this:
Integer[] arr = (Integer[]) list.toArray();
If I understand what you want to do, you need something like this:
Integer[] arr = list.stream()
.flatMap(Arrays::stream)
.toArray(Integer[]::new);
Example:
List<Integer[]> list = List.of(new Integer[]{1,2,3}, new Integer[]{4,5,5});
Integer[] arr = list.stream()
.flatMap(Arrays::stream)
.toArray(Integer[]::new);
> [1, 2, 3, 4, 5, 5]
答案2
得分: 1
你需要使用类似以下的方法来做:
Integer[][] arr = list.toArray(new Integer[0][]);
或者使用流。
英文:
You are going to have to do that with something like
Integer[][] arr = list.toArray(new Integer[0][]);
or use streams.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论