有 Java 编程相关的问题?

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

java不应该反对。clone()需要显式强制转换吗?

为什么不反对。clone()调用需要显式强制转换吗?这难道不是“downcast always need and explicit cast”规则的例外吗?我使用javac命令行和EclipseHelios与JDK1编译并成功运行了以下代码。6.0_29.

public class Main {

    public static void main(String[] args) {
        byte[] original = { 1, 2, 3, 4 };
        byte[] copy = original.clone();

        for (byte b : copy) {
            System.out.print(b + " ");
        }

        int[] originalInt = { 11, 22, 33, 44 };
        int[] copyInt = originalInt.clone();

        for (int i : copyInt) {
            System.out.print(i + " ");
        }

        String[] originalStr = { "1", "2", "3", "4" };
        String[] copyStr = originalStr.clone();

        for (String s : copyStr) {
            System.out.print(s + " ");
        }

        Main[] originalMain = { new Main() };
        Main[] copyMain = originalMain.clone();

        for (Main m : copyMain) {
            System.out.print(m + " ");
        }
    } // end method main

} // end class Main

共 (1) 个答案

  1. # 1 楼答案

    你不是在给Object.clone()打电话。您正在调用T[].clone(),它被覆盖以返回T[]

    JLS 10.7 Array Members

    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[].