How do I write a generic method to insert an element into an array?
I have an input array [3, 5, 12, 8] and I want the output array (the input must not be affeccted) identical to the input, but with element 7 inserted between 5 and 12, so at index 2 of the input array.
Here's what I have so far. I commented out the code that is not compiled by the event and added a couple of questions that came up when trying one way or another:
public static <O>ArrayList<O> addToSet(O[] in,O add,int newIndex){
// O obj = (O) new Object(); //this doesnt work
// ParameterizedType obj = (ParameterizedType) getClass().getGenericSuperClass(); // this is not even recognized
ArrayList<O> out = multipleOfSameSet(obj, in.length);
if (newIndex > in.length){
out = new ArrayList<>(newIndex+1); // also noticed that initializing an ArrayList
//like this throws an IndexOutOfBoundsException when i try to run out.get(),
// could someone explain why??
out.set(newIndex, add);
}
int j = 0;
int i = 0;
while(j<in.length+1){
if (j==newIndex){
out.set(j, add);
} else if(i<in.length){
out.set(j, in[i]);
i++;
}
j++;
}
return out;
}
The array component type can be String, Integer, or even JPanel.
+3
source to share
2 answers
Here is the general version of the code
@SuppressWarnings("unchecked")
public <T> T[] insertInCopy(T[] src, T obj, int i) throws Exception {
T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length + 1);
System.arraycopy(src, 0, dst, 0, i);
dst[i] = obj;
System.arraycopy(src, i, dst, i + 1, src.length - i);
return dst;
}
but you can specialize in the method of handling primitive types. I mean, generics and arrays don't mix well - so you'll have problems with int and have to use wrapper types:
@Test
public void testInsertInTheMiddle() throws Exception {
Integer[] in = {3, 5, 12, 8};
Integer[] out = target.insertInCopy(in, 7, 2);
assertEquals(out, new Integer[] {3, 5, 7, 12, 8});
}
+1
source to share