Java – how do I add an array in the middle?

I try to create a method named insertat, which accepts three parameters (int index, int n, int value). If I call:

Int index is where I start placing values

How many values is int n

Int value is the actual value or number I want to put in

I create this method in a class called arrayintlist:

public class ArrayIntList {
    private int[] elementData; // list of integers
    private int size;          // current # of elements in the list 
}

I try to make the following method, but I still insist on what I lack I would appreciate it if you could help me!

public void insertAt(int index,int value) {
    if (index < 0 || index > size || n < 0) {
        throw new IllegalArgumentException();
    }
    size = size + n;
    for (int i = 0; i < n; i++) {
        elementData[(size - 1) - i] = elementData[(size - n) + i];
        elementData[n + i] = value;
    }
}

Solution

The array in the example contains only four values, but you try to add four values This is not possible because the array has a fixed length So you must create a new array of length n:

int[] newElements = new int[size + n];

Then, you must copy all elements from 0 to the index and copy the index elements from the old version to the new array:

System.arraycopy(elementData,newElements,index);
System.arraycopy(elementData,index,index + n,size - index);

Then you must insert the new element into the array n times:

Arrays.fill(newElements,value);

Finally, you must reassign the new array to the old instance 1 and set the new size:

elementData = newElements;
size += n;

I have used some auxiliary methods in JDK, such as system Arraycopy, which has the following signature:

void arraycopy(Object src,int srcPos,Object dest,int destPos,int length);

It copies the elements in SRC from srcpos to srcpos length, DeST, and destpos to destpost length

Array. Fill is also a good helper with the following signature:

void fill(int[] a,int fromIndex,int toIndex,int val)

It fills the array a with the value Val from fromindex to toindex

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>