我正在try 连接/合并两个Integer[]数组,并将其存储在另一个Integer[]中.但我在运行时遇到了以下错误.

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer; ([Ljava.lang.Object; and [Ljava.lang.Integer; are in module java.base of loader 'bootstrap') at AllInOnePack.MainClass.AllInOne.main(AllInOne.java:61)

我的代码是这样的.

Main class.java

    static Integer[] hardCodeValus = {1,2,3,4};
    static Integer[] userValue = {1,2,3,4};
    concatArray = new Integer[hardCodeValus.length+userValue.length];
    concatArray = (Integer[]) StreamsFunc.concatenate(hardCodeValus, userValue);

StreamsFunc.java

    public static <T> Object[] concatenate(T[] hardCodeValus, T[] userValue) 
    {
            return Stream.concat(Arrays.stream(hardCodeValus), Arrays.stream(userValue)).toArray();
    }

在运行时,我收到错误.那么,为什么在编译时找不到呢?

推荐答案

那么,为什么在编译时找不到呢?

因为你casted的结果是concatenateInteger[].如果删除了强制转换,将会出现编译器错误,指出Object[](返回类型为concatenate)无法转换为Integer[](类型为concatArray).

请注意,无参数Stream.toArray()返回Object[]的实例,而不是流包含的任何类型元素的array.由于类型擦除,它不可能执行后一种操作.

Returns:

一个运行时组件类型为Object的数组,其中包含 此流的元素

还要注意,如果concatenate要返回新的数组anyway,则不需要将concatArray初始化为new Integer[...].

要修复concatenate,一种方法是用IntFunction调用toArrayoverload:

public static <T> T[] concatenate(T[] hardCodeValus, T[] userValue, IntFunction<T[]> arrayCreator)
{
    return Stream.concat(Arrays.stream(hardCodeValus), Arrays.stream(userValue))
            .toArray(arrayCreator);
}

用途:

var concatArray = concatenate(hardCodeValus, userValue, Integer[]::new);

Java相关问答推荐

具有默认分支的JUnit代码覆盖率切换声明

Select 按位运算序列

滚动视图&不能在alert 对话框中工作(&Q;&Q;)

对Java中的通配符参数的混淆

从Spring5迁移到Spring6:无法在雅加达包中找到类

什么是Java原子属性的正确getter和setter

格式中的特定回录键-值对

如何在我的世界中为互动增加冷却时间?

如何使这两种方法合二为一?

使用for循环时出现堆栈溢出错误,但如果使用if块执行相同的操作,则不会产生错误

对角线填充二维数组

为什么JavaFX MediaPlayer音频播放在Windows和Mac上运行良好,但在Linux(POPOS/Ubuntu)上却有问题?

org.springframework.web.HttpRequestMethodNotSupportedException:请求方法';帖子';不支持

如何通过gradle命令行从build.gradle获得Java targetCompatibility

设置背景时缺少Android编辑文本下划线

当我try 返回可选时,Mock无法正常工作

为什么我得到默认方法的值而不是被覆盖的方法的值?

using case default on switch语句返回;预览特征切换中的模式匹配仅在源级别20及以上的情况下可用;

Xml Reader 将 BMP 外部的字符解析为代理项对,这会导致无效的 xml

对于 Hangman 游戏,索引 0 超出长度 0 的范围