gpt4 book ai didi

java - 为什么没有 java.lang.Array 类?如果一个java数组是一个对象,它不应该扩展对象吗?

转载 作者:IT老高 更新时间:2023-10-28 20:53:30 25 4
gpt4 key购买 nike

这里是 java 包树: http://docs.oracle.com/javase/7/docs/api/java/lang/package-tree.html

我阅读了一篇关于 Java 的教程,其中指出在 Java 中数组是对象。

数组类在哪里?为什么我们可以制作这样的数组:

byte[] byteArr = new byte[];
char[] charArr = new char[];
int[] intArr = new int[];

并且数组将继承 Object 的方法;例如:

    byte thisByte = 1;
byte thatByte = 2;
byte[] theseBytes = new byte[] {thisByte, thatByte};
int inheritance = theseBytes.length; //inherited 'length' field and some methods
int wasntInWill = thatByte.length; //error

这是怎么回事?

编辑:

根据答案,我现在知道它是 java.lang.reflect 包中的 final 类。

我现在在我的 Android 项目中创建了一个包 java.lang.reflect 并添加了一个名为 Array.java 的类。为了确认这是在原始类的方式,Eclipse 给了我错误“...已经存在于 path/to/android.jar”

如果我写出与 java.lang.reflect.Array 相同的类,但更改 toString() 方法...这应该在我的应用程序中工作,对吧?

最佳答案

来自 JLS :

Every array has an associated Class object, shared with all other arrays with the same component type. [This] acts as if: the direct superclass of an array type is Object [and] every array type implements the interfaces Cloneable and java.io.Serializable.

以下示例代码显示了这一点:

class Test {
public static void main(String[] args) {
int[] ia = new int[3];
System.out.println(ia.getClass());
System.out.println(ia.getClass().getSuperclass());
}
}

哪个打印:

class [I
class java.lang.Object

其中字符串 "[I" 是类对象 "array with component type int"的运行时类型签名

是的,因为数组类型有效地扩展了 Object,你可以在 arrayObject 上调用 toString() 也可以看上面的例子

int arr[] = new arr[2];
arr.toString();

关于java - 为什么没有 java.lang.Array 类?如果一个java数组是一个对象,它不应该扩展对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8546500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com