October 28, 20169 yr I made a post on stackoverflow but nobody has helped me. I am supposed to write a program that has a generic method to swap any two variables of any data type. I have this, could anyone help me. public class GArray <E extends Number> {} private E[] list; public GArray() list = (E[]) new Number[10] I don't know how to write this. Could anyone tell me how to do this? Thanks
October 28, 20169 yr I made a post on stackoverflow but nobody has helped me. I am supposed to write a program that has a generic method to swap any two variables of any data type. I have this, could anyone help me. public class GArray <E extends Number> {} private E[] list; public GArray() list = (E[]) new Number[10] I don't know how to write this. Could anyone tell me how to do this? Thanks public static <E> List<E> swapIt(List<E> things, E thing1, E thing2) { Collections.swap(things, things.indexOf(thing1), things.indexOf(thing2)); return things; } something like this?
October 28, 20169 yr Author Thank you for your help. This is my second java course and I can tell you I am not taking up programming anymore. Just taking this class to satisfy needs in Information Technology. How would I go about giving it some sample data like int 10 and string tree?I am almost done with this course thank god. 1 monthi put this in the main swapIt(things, 10, "tree"); //something is wrong Edited October 28, 20169 yr by Mechagoober
October 28, 20169 yr Thank you for your help. This is my second java course and I can tell you I am not taking up programming anymore. Just taking this class to satisfy needs in Information Technology. How would I go about giving it some sample data like int 10 and string tree? I am almost done with this course thank god. 1 month i put this in the main swapIt(things, 10, "tree"); //something is wrong you're passing two different types. They should both be of 1 type (E) public static <IIlIiiiIIlII> List<IIlIiiiIIlII> IIIIiiiIIlII (List<IIlIiiiIIlII> IIIIiiiIIlII, IIlIiiiIIlII IIIIiiIIlII, IIlIiiiIIlII IIIIiiIIII) { Collections.swap(IIIIiiiIIlII, IIIIiiiIIlII.indexOf(IIIIiiIIlII), IIIIiiiIIlII.indexOf(IIIIiiIIII)); return IIIIiiiIIlII; } just for the sake of it i decided to do this Edited October 28, 20169 yr by Imateamcape
November 3, 20169 yr public class Swap { public static List<?> swap(List<?> list, Object a, Object b) { List<?> result = new ArrayList<>(list); Collections.swap(result, list.indexOf(a), list.indexOf(b)); return result; } public static <A, B> Object[] swap(Object[] array, Object a, Object b) { return swap(Arrays.asList(array), a , b).toArray(); } /* Example */ public static void main(String[] args) { Object[] array = new Object[]{1, "two", 3, "four"}; List<?> list = new ArrayList<>(Arrays.asList(array)); System.out.println(swap(array, 3, "two")); System.out.println(swap(list, "four", 1)); } } yw Edited November 3, 20169 yr by Botre