import java.util.Random; /*********************** * @author gTowell * Created: August 28, 2019 * Modified: August 29, 2019 * * Purpose: * Generic Methods ***********************/ public class GenericMethod { public static void main(String[] args) { Integer[] jj = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // NOTE AUTOBOXING!!! new GenericMethod().randomize(jj); for (int j : jj) System.out.println(j); String[] ss = { "A", "B", "c", "d", "E", "F" }; new GenericMethod().randomize(ss); for (String s : ss) System.out.println(s); } /** * Generic method to randomize list * @param * @param data the data (of Type T) to be randomized */ public void randomize(T[] data) { Random r = new Random(); for (int i = 0; i < data.length; i++) { int tgt = r.nextInt(data.length); swap(data, i, tgt); } } /** * Generic swap function. From within the passed array, swap the location of the dat items at locA and locB * @param Note here that although swap is called from randomized, the naming of the type does not have to match * That is, it is T in randomize and W here. * @param data the data (of type W) to be worked on * @param locA the first location in the array * @param locB the second location in the array */ public void swap(W[] data, int locA, int locB) { W temp = data[locA]; data[locA]=data[locB]; data[locB]=temp; } /** * Question from class, can you have a generic method with two generic classes. Answer yes. As here. Also 3, 4, ... * @param * @param * @param ess * @param tee */ public void twoGenericMethod(S ess, T tee) { System.out.println(ess + " " + tee); } }