Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an element to the first empty array's index

I've created an array of size x . And want to add an element to the first empty index in the array .For example , if the array's size is 10 and indexes 1 and 2 are taken, then the element is added to index 3.

like image 798
Jared Avatar asked Sep 18 '14 17:09

Jared


3 Answers

If the array is an int array you can do

for(int i=0; i < array.length; i++)
    if(array[i] == 0) {
        array[i] = newValue;
        break;
    }

if it is an Object array you can do

for(int i = 0; i < array.length; i++)
    if(array[i] == null) {
        array[i] = newObject;
        break;
    }
like image 127
gkrls Avatar answered Sep 25 '22 02:09

gkrls


Create the array of size x.
Create a stack of size x which indicates all free indexes. Push all indexes (in reverse order) to the stack.
When you try to add an element to the array pop from the stack the next free index. Use the index to insert to the array.
If an element is removed, push the index back to the stack to indicate that it is free and nullify the element in the array.
If you want to add an element and the stack is empty i.e. the array is full, well you decide what to do.

Your other option would be to loop over the array to find the next "free" spot which would be indicated by a null.

like image 25
Cratylus Avatar answered Sep 27 '22 02:09

Cratylus


In the responses above, there is no early termination of the for-loop after the first empty index is found. To avoid all empty indexes being populated, add a break statement as part of the conditional statement.

for(int i = 0; i < array.length; i++)
{
    if(array[i] == null)
    {
        array[i] = newObject;
        break;
    }
}
like image 27
John K Avatar answered Sep 25 '22 02:09

John K