简体   繁体   English

数组大小在Java中无关紧要吗?

[英]Is array size irrelevant in java?

As per the below statement, 根据以下声明,

An array of subclass may be assigned to an array of its superclass. 子类的数组可以分配给其超类的数组。 An array of implementing class may be assigned to an array of its interface type. 可以将实现类的数组分配给其接口类型的数组。 Size is irrelevant. 大小无关紧要。

I wrote below sample code to check the behavior of size in array 我写了下面的示例代码来检查数组中大小的行为

interface I{}
class C implements I{}

/* dummy.java*/
public class dummy{
    public static void main(String[] args){
        C[] c = new C[6];
        I[] i = new I[2];
        c[0] = new C();
        c[1] = new C();
        c[2] = new C();
        c[3] = new C();
        c[4] = new C();
        c[5] = new C();
        i = c;
        System.out.println(i[5].getClass());
    }
}

When i say, new C[6]; 当我说new C[6]; , an object [null,null,null,null,null,null] gets created of type class [LC and c points to this object. ,将创建类型为class [LC [null,null,null,null,null,null]的对象[null,null,null,null,null,null]c指向该对象。 When i say, new I[2]; 当我说new I[2]; , an object [null,null] gets created of type class [LI and i points to this object. ,将创建类型为class [LI [null,null]的对象[null,null] ,并且i指向该对象。

My question: 我的问题:

How interface array is working here, when i say i[5] , despite an object [null, null] being created after defining new I[2] ? 尽管new I[2]在定义new I[2]之后创建了对象[null, null] ,但我说i[5]时接口数组在这里如何工作? What exactly is happening when i say i = c; 当我说i = c;时,到底发生了什么? ? Is size of array of interface new I[2]; 接口new I[2];的数组大小new I[2]; getting modified during assignment i = c; 在分配过程中被修改i = c; ?

What that quote is trying to say is that the size of an array is part of the object, ie. 引用试图说的是,数组的大小是对象的一部分,即。 it is not part of the reference or the variable type. 它不是引用或变量类型的一部分。

In

i = c;

you are assigning a copy of the value of the reference held in c to i . 您正在将c保存的引用的值的副本分配给i That is, i will reference the same instance as c . 也就是说, i将引用与c相同的实例。

Is size of array of interface new I[2]; 接口新I [2]的数组大小; getting modified during assignment i=c;? 在分配i = c时被修改?

No, that's the whole point. 不,这就是重点。 i and c are just variables. ic只是变量。 Variable assignment has no side effects. 变量分配没有副作用。

When you set i=c 当您设置i=c

You are setting i to point to the object created by c. 您将i设置为指向c创建的对象。 Therefore, i will now point to C[6]; 因此, i现在将指向C[6]; < this array <此数组

So... i[1] = new I(); 所以... i[1] = new I(); c[1] will return a I object c[1]将返回一个I object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM