G.A. Cheran G.A. Cheran - 1 year ago 71
Java Question

How to check a certain index of an array contains a value or not

I have 4 objects to place in an array. I can't place it if the index contains any other object. How should I check if there is an element or nothing in a certain index of an array in java. Example ;

I have an array called numList and it contains some values. I want to add another number to index 6. For this I have to check numList[6] contains a value or not.

Answer Source

In Java an array of types other than built-ins is initialized to null values. Use a loop to find the lowest index at which a null is stored:

MyObject[] array = new MyObject[mySize];
... // Populate some locations in the array, then...
int placeAt = -1;
for (int i = 0 ; i != array.length; i++) {
    if (array[i] == null) {
        placeAt = i;
if (placeAt != -1) {
    // You found the first index with a null
    array[placeAt] = myNewObject;
} else {
    ... // Array has no empty spaces - report an error and/or exit
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download