Reputation: 379
I have an input array [3, 5, 12, 8] and I want an output array (the input must not be affeccted) identical to the input, but with the element 7 inserted between 5 and 12, so at index 2 of the input array.
Here is what I have so far. I commented out code that doesn't event compile, and added a couple of questions that arose while trying this or that way:
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 could be String, Integer or even a JPanel.
Upvotes: 3
Views: 1048
Reputation: 20885
Here is the generic 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 may want to specialize the method for dealing with primitive types. I mean, generics and arrays don't mix well - so you'll have troubles with int and will need 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});
}
Upvotes: 1
Reputation: 346
You can do this way.
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o);
}
}
Upvotes: 0