Java Arrays
Following example shows how to insert a new element to an array:
package com.logicbig.example;
import java.lang.reflect.Array;
import java.util.Arrays;
public class ArrayInsert {
//insert array of objects
public static <T> T[] insert(T[] input, T newT, int index) {
if (input == null) {
return input;
}
T[] newArray = (T[]) Array.newInstance(input.getClass().getComponentType(), input.length + 1);
int c = 0;
for (int i = 0; i < input.length + 1; i++) {
newArray[i] = i == index ? newT : input[c++];
}
return newArray;
}
//insert array of primitive int
public static int[] insert(int[] input, int newT, int index) {
if (input == null) {
return input;
}
int[] newArray = new int[input.length + 1];
int c = 0;
for (int i = 0; i < input.length + 1; i++) {
newArray[i] = i == index ? newT : input[c++];
}
return newArray;
}
public static void main(String[] args) {
int[] intArray = {3, 6, 4, 8};
intArray = insert(intArray, 9, 3);
System.out.println(Arrays.toString(intArray));
String[] strArray = {"one", "two", "three"};
strArray = insert(strArray, "two-two", 2);
System.out.println(Arrays.toString(strArray));
}
}
[3, 6, 4, 9, 8] [one, two, two-two, three]
The object version of insert method, in above example, is generic for all objects but for primitives we have to create separate methods individually for each primitive.
In above example we showed how to do that with int array.
|
|