java - How to write a generic method to insert an element in an array? -
i have input array [3, 5, 12, 8] , want output array (the input must not affeccted) identical input, element 7 inserted between 5 , 12, @ index 2 of input array.
here have far. commented out code doesn't event compile, , added couple of questions arose while trying or 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(); // not recognized arraylist<o> out = multipleofsameset(obj, in.length); if (newindex > in.length){ out = new arraylist<>(newindex+1); // noticed initializing arraylist //like throws indexoutofboundsexception when try run out.get(), // explain why?? out.set(newindex, add); } int j = 0; int = 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 string, integer or jpanel.
here generic version of 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, + 1, src.length - i); return dst; }
but may want specialize method dealing primitive types. mean, generics , arrays don't mix - you'll have troubles int , need 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}); }
Comments
Post a Comment