我确定我遗漏了一些简单的东西,但这个问题看起来绝对愚蠢。
private static void method501(char ac[])
{
char ac1[] = ac.clone();
}
我的问题是 char ac1[] = ac.clone();
在 eclipse 中抛出一个类型不匹配错误,告诉我我不能转换一个字符数组到对象?
这是什么原因?在 最新版本 的 eclipse 上没有给我同样的错误所以想知道是否只是这个旧版本给我这个问题。
最佳答案
如果您将编译器设置为目标非常旧的源兼容性,那么在 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 classObject
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 classObject
and throws no checked exceptions. The return type of the clone method of an array typeT[]
isT[]
.
进入项目属性并检查它是使用默认设置还是特定于项目的设置,并修复适当的设置(特定于项目的设置或您的工作区设置)以使用更新的源兼容性.
我怀疑您会发现在当前设置下您将无法使用泛型或其他 1.5+ 功能。
关于java - 类型不匹配将 char[] 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45391056/