gpt4 book ai didi

java - 为什么 x 被视为对象(即使它引用数组)也是一个错误?

转载 作者:行者123 更新时间:2023-12-02 02:24:12 26 4
gpt4 key购买 nike

有人可以帮我理解这段代码吗?

int[] A = new int[2];
Object x = A; // All references are Objects
A[0] = 0; // Static type of A is array...
x[1] = 1; // But static type of x is not an array: ERROR

根据 Oracle Java SE 站点:

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

我知道数组可以分配给Object类型变量,但是,我的困惑可能在于引用的概念。当我们说Object x = A时,我们是说x拥有对数组A的引用。然而,我的困惑在于x[1] = 1。为什么 x 被认为是 Object 即使它引用了一个数组也是一个错误?我是否认为 [] 是一种只能在“array”类中访问的方法?

最佳答案

虽然我不会不必要地丢弃类型信息,但您可以使用 Array#setInt(Object, int, int)通过对象访问int[]。也就是说,

Array.setInt(x, 1, 1); // x[1] = 1;

可以。

关于java - 为什么 x 被视为对象(即使它引用数组)也是一个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039517/

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