Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if array is full

Tags:

java

arrays

If I have an Array Candy[] type;

and type = new Candy[capacity];

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

like image 588
Michel Tamer Avatar asked Apr 08 '14 15:04

Michel Tamer


3 Answers

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.

like image 145
user3437460 Avatar answered Nov 15 '22 05:11

user3437460


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};
like image 28
Boris Brodski Avatar answered Nov 15 '22 04:11

Boris Brodski


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.

like image 20
Ivaylo Strandjev Avatar answered Nov 15 '22 03:11

Ivaylo Strandjev