Checking to see if array is full

折月煮酒 提交于 2021-02-16 13:33:52

问题


If I have an Array Candy[] type;

and type = new Candy[capacity];

if the Array is full is capacity = type.length ?


回答1:


Since you are using array, the size of array is determined during compilation. Thus if your intention is to check whether current array's index has reached the last array element, you may use the following condtion (possibly in a loop) to check whether your current array index is the last element. If it is true, then it has reached the last element of your array.

Example:

     int[] candy = new int[10];  //Array size is 10
     //first array: Index 0, last array index: 9. 
     for (int x=0; x < candy.length; x++)
           if (x == candy.length - 1)
                //Reached last element of array

You can check the size of the array by using:

candy.length

You check whether it is last element by using:

if (currentIndex == candy.length - 1) //Where candy is your array

Make sure you are using double equal == for comparison.

Single equal = is for assignment.




回答2:


Java creates an array with capacity count of references to the Candy instances initializing array with the nulls. So any array in java is full and

type.length == capacity

is always true.

type = new Candy[capacity] is equivalent to

type = new Candy[] {null, null, null, /* capacity count of nulls */, null};



回答3:


In the example you show type.length will always be equal to capacity(after the initialization). Also your array will always have capacity elements but they will initially all be null.




回答4:


If you want to check if array is full (no null elements), use something like this:

//1
boolean b = false;

//2
for(int i = 0; i < type.length; i++){
    if(type[i] == null){
        b = true;
    }
}

//3
if(b == false){
    System.out.println("Array is full");
}

What does it mean?

//1. At beginning you have one boolean (b) which is false.

//2. If any value in your array is null, b will be true.

//3. You check if value of b is still false. If it is, that means that b is never changed, so array is full (no null elements) .



来源:https://stackoverflow.com/questions/22942115/checking-to-see-if-array-is-full

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!