6

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.

5
  • 4
    Are you sure you should be using an array, rather than an ArrayList? Commented Sep 18, 2014 at 17:09
  • What is the type of the array ? if it is primitive types then how would you determine null/empty ? Commented Sep 18, 2014 at 17:12
  • 1
    array is primitive or Object type?
    – Vishrant
    Commented Sep 18, 2014 at 17:12
  • What are you actually trying to achieve? Commented Sep 18, 2014 at 17:22
  • I can't be using ArrayList, It's an Object type array .
    – Jared
    Commented Sep 18, 2014 at 18:02

4 Answers 4

5

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;
    }
0
1

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.

2
  • Unfortunately I can't be using stacks.
    – Jared
    Commented Sep 18, 2014 at 18:05
  • You can implement a stack via another array
    – Cratylus
    Commented Sep 18, 2014 at 18:16
1

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;
    }
}
0

Loop through the array until you find zero/null. For example,

int a[] = new int[100];
int x; //Number to be inserted
for(int i=0;i<a.length;i++)
{
   if(a[i]==0)
     a[i]=x;
}

object a[] = new object[100];
int x;
for(int i=0;i<a.length;i++)
{
   if(a[i]==null)
     a[i]= new Integer(x);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.