user1284791
user1284791

Reputation: 179

Add element into array java

Here's what the layout is

index   num 
0      [10]
1      [20]
2      [30]
 (Add 35 here)
3      [40] Move elements down
4      [50]
5      [60]
6      [70]

then my method is this

public static void method(int[] num, int index, int addnum)
{

}

How can i add 35 in there?

Tried this:

public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
        Num[k]=num[k++]
}
    Num[3] = 35;

Upvotes: 3

Views: 55778

Answers (7)

aioobe
aioobe

Reputation: 421310

You need to

  1. allocate a new array with room for one new element.

    int[] newArray = new int[oldArray.length + 1];
    
  2. Copy over all elements and leave room for the one to insert.

    for (int i = 0; i < newArray.length - 1; i++)
        newArray[i < insertIndex ? i : i + 1] = oldArray[i];
    
  3. Insert 35 in the empty spot.

    newArray[insertIndex] = numberToInsert;
    

Note that it's not possible to do in a method like this:

public static void method(int[] num, int index, int addnum)
              ^^^^

since you can't change the length of num.

You need to allocate a new array, which means that need to return the new array:

public static int[] method(int[] num, int index, int addnum)
              ^^^^^

and then call the method like this:

myArr = method(myArr, 3, 35);

Upvotes: 1

Arijit
Arijit

Reputation: 1674

How about this?

public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{   if(i==3) //becaues I want to add the value 4 in 4th place
        myarray[i]=4;
    else if(i>3)
        myarray[i]=temp_myarray[i-1];
    else 
        myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
    System.out.print(myarray[i]);//Print new array
}

static int[] addElement(int[] arr, int elem) {
    arr  = Arrays.copyOf(arr, arr.length + 1);
    arr[arr.length - 1] = elem;
    return arr;
}
}

Upvotes: 0

soulmerge
soulmerge

Reputation: 75774

As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:

If you would set the number at position index, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index: num[x] becomes num[x+1], etc.

You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index].

During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]):

  • You could just overwrite it, discarding the value
  • You could return it from your function
  • You could throw an exception if it is non-zero
  • You could create a new array that is 1 entry larger than the current array instead to keep all values
  • etc.

After this, you have duplicated num[index]: the value is present in num[index+1], too, as you have moved it away.

Now it is possible to write the new value at the desired position without overriding an existing value.

EDIT

You have several errors in your code:

  • You increment k, you need to decrement it (k--, not k++)
  • You modify k again in your loop body: it is updated twice in each cycle
  • If you start with k = num.length, you will try to write at num[num.length + 1], which is not possible

Upvotes: 5

DukeOfMarmalade
DukeOfMarmalade

Reputation: 2788

Very crudely, you want to do something like this:

public static void(int[] num, int index, int addnum)
{    
    // initialize new array with size of current array plus room for new element
    int[] newArray = new int[num.length + 1]; 

    // loop until we reach point of insertion of new element
    // copy the value from the same position in old array over to
    // same position in new array
    for(int i = 0; i < index; i++)
    {
        newArray[i] = num[i]; 
    }
    i = i + 1; // move to position to insert new value

    newArray[i] = addnum; // insert the value

    // loop until you reach the length of the old array 
    while(i < num.length)
    {
        newArray[i] = num[i-1];
    }

    // finally copy last value over
    newArray[i + 1] = num[i]; 
}

Upvotes: 1

amit
amit

Reputation: 178521

Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index] one element to the right, and add 35 [num] to the relevant place.
[what actually happen is that the last element is discarded out].

However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)

Upvotes: 0

jefflunt
jefflunt

Reputation: 33954

What you're looking for is an insertion sort.

It's classwork, so it's up to you to figure out the proper code.

Upvotes: 0

Woot4Moo
Woot4Moo

Reputation: 24336

Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:

    public static void(int[] num, int index, int addnum)
 {   
       int[] temp = new int[num.length *2];  
       for(int i = 0; i < index; i++)  
            copy num[i] into temp[i]  
       insert addnum into temp[index]  
       fill temp with remaining num values
 } 

That pseudocode above should get you started.

Upvotes: 0

Related Questions