简体   繁体   English

Java中零长度的数组

[英]Array of zero length in java

Below code 下面的代码

public class Example {
    static int[] member;
    public static void main(String[] args) {
        int[] ic = new int[0];
        if (ic == null){
            System.out.println("ic is null");
        }
        System.out.println(ic);  // [I@659e0bfd
        if(member == null){
            System.out.println("member is null");
        }
    }
}

It is obvious that elements can't be added in zero length array. 很明显,不能在零长度数组中添加元素。

What does ic point to, if ic is not null ? 如果ic不为nullic指向什么?

As per below diagram, Is ic pointing to memory location 659e0bfd (which is empty)? 如下图所示, ic是否指向内存位置659e0bfd (为空)?

在此处输入图片说明

What does ic point to, if it is not null? ic指向什么(如果不为null)?

It points an empty array of zero capacity. 它指向一个零容量的空数组。 Arrays are reference types and memory space is allocated for them like any other reference type. 数组是引用类型,并且像其他任何引用类型一样为它们分配存储空间。

Imagine an array as a box. 想象一个数组作为一个盒子。 You can declare a box with some capacity, say 3 您可以声明一个具有一定容量的盒子,例如3

int[] x = new int[3];

and you'll get this box: [_,_,_] . 然后您会看到以下框: [_,_,_] You can fill it with some numbers 您可以用一些数字填充它

x[1] = 9;

to get [_,9,_] . 得到[_,9,_] What you did, instead, is declaring an zero capacity box 相反,您所做的是声明一个零容量的框

int[] x = new int[0];

to get this: [] . 得到这个: [] And guess what happens if you try to add an element to it? 并猜测如果尝试向其中添加元素会发生什么? You cannot. 你不能。

So, to answer your question, what does ic point to? 因此,为回答您的问题, ic指向什么? Your empty (and zero capacity) box. 您的空(和零容量)框。

ic refers to an empty array instance. ic表示一个空数组实例。 It contains no elements ( ic[i] would throw ArrayIndexOutOfBoundsException for each value of i ), but it's not null. 它不包含任何元素( ic[i]会抛出ArrayIndexOutOfBoundsException的每个值i ),但它不是空。

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

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