在运行时,[Ljava.lang.Object; 无法转换为类 [Ljava.lang.Integer。

huangapple go评论51阅读模式
英文:

Running into [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer at runtime

问题

在运行时,当尝试将List<Integer[]>转换为Integer[]时,我一直遇到上面的错误。

public static Integer[] findKthLargest(List&lt;Integer[]&gt; 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&lt;Integer[]&gt; 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&lt;Integer[]&gt; list = List.of(new Integer[]{1,2,3}, new Integer[]{4,5,5});
Integer[] arr = list.stream()
                .flatMap(Arrays::stream)
                .toArray(Integer[]::new);

&gt; [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.

huangapple
  • 本文由 发表于 2023年2月10日 03:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定