Add item to java array

Here is the layout

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

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

}

      

How can I add 35?

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;

      

+3


source to share


7 replies


Since this is something you have to accomplish yourself, I will only suggest his method, not the code:

If you set a number at a position index

, you must overwrite the value that was there previously. So what you need to do is move each element one position at a time to the end of the array, starting at index

: num[x]

becomes num[x+1]

, etc.

You will find out that you need to do it in reverse order, otherwise you will fill your array with a 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 can just overwrite it by dropping the value
  • You can return it from your function
  • You can throw an exception if it is nonzero.
  • You can create a new array that will contain 1 entry more than the current array to keep all values
  • and etc.


After that, you duplicate num[index]

: this value is also present in num[index+1]

, since you deleted it.

Now you can write the new value to the desired position without overriding the existing value.

EDIT

There are several errors in the code:

  • You increase k

    , you need to decrease it ( k--

    , not k++

    )
  • You are changing again k

    in your loop body: it is updated twice in every loop
  • If you start with k = num.length

    , you try to write in num[num.length + 1]

    , which is impossible
+5


source


You need

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

    int[] newArray = new int[oldArray.length + 1];
    
          

  • Copy all the elements and leave some space for pasting.

    for (int i = 0; i < newArray.length - 1; i++)
        newArray[i < insertIndex ? i : i + 1] = oldArray[i];
    
          

  • Insert 35 in the blank space.

    newArray[insertIndex] = numberToInsert;
    
          


Note that this is not possible in a method like this:

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

      



since you cannot change the length num

.

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

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

      

and then call the method like this:

myArr = method(myArr, 3, 35);

      

+1


source


Very roughly, 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]; 
}

      

+1


source


Well, you can't if you don't have "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 appropriate place.
[what actually happens is that the last element is discarded].

However, the best solution would probably be to use ArrayList and use the methodmyArrayList.add(index,element)

0


source


Since this closely resembles homework, you need to understand 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
 } 

      

This pseudocode above should get you started.

0


source


What you are looking for is a sort insert .

This is a cool job, so you need to figure out the correct code.

0


source


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

      

0


source







All Articles