有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类型不匹配将char[]转换为对象

我肯定我错过了一些简单的东西,但这个问题似乎非常愚蠢

private static void method501(char ac[])
{
    char ac1[] = ac.clone();
}

我的问题是char ac1[] = ac.clone();在eclipse中抛出了一个类型不匹配错误,告诉我不能将字符数组转换为对象

有什么原因吗?在eclipse的最新版本上,它没有给我同样的错误,所以想知道是不是这个旧版本给了我问题


共 (1) 个答案

  1. # 1 楼答案

    如果编译器设置的目标是非常旧的源代码兼容性,那么在Eclipse中就会发生这种情况

    如果兼容级别为1.5或更高,就可以了——但如果将源代码兼容级别设置为1.3或1.4,就会出现此错误,因为早期版本的Java语言规范没有指定T[].clone()返回T[]

    JLS 1.0第10.7节中的文本:

    The members of an array type are all of the following:

    • [...]
    • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions

    Java 8 JLS中的等效文本:

    The members of an array type are all of the following:

    • [...]
    • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    进入项目属性,检查它是否使用默认设置或特定于项目的设置,并修复相应的设置(特定于项目的设置或您的工作区设置),以使用更为最新的源兼容性

    我怀疑你会发现,在当前设置下,你也无法使用泛型或其他1.5+功能