package examples; /** * * CS401 Example 26 * * Demonstration of "generic" operations in Java We are sorting various * different Comparable objects using the same sort method. * * NOTE: The way this is presented in the Lewis / Loftus text is somewhat * obsolete. The Comparable interface in Java is now parameterized, and this way * of using it is no longer recommended. In fact, when compiling this program, a * warning is given about this. * * To show how it "should" be done now, I have provided an alternate version. * See the same class names with the letter T behind them ex24T.java, * SortingT.java, CDT.java * * @author Dr. Ramirez, PJ Dillon */ public class ex26 { //This method is another (simple) example of a generic method. // I am using it here to display all of my arrays, since it // relies only on the toString() method, which is defined in // class Object and overridden by most other classes (including // those used in this example) public static void showData(Object [] Ar, int perLine) { System.out.println("The data is: "); for (int i = 0; i < Ar.length-1; i++) { System.out.print(Ar[i] + ", "); if ((i+1) % perLine == 0) System.out.println(); } if (Ar.length > 0) System.out.println(Ar[Ar.length-1]); System.out.println(); } public static void main(String [] args) { String [] S = { "Talking Heads", "Midnight Oil", "Beatles", "Metallica", "U2", "Tori Amos", "Sarah McLachlan", "NIN", "Cranberries", "Garbage"}; Integer [] A = new Integer[23]; for (int i = 0; i < A.length; i++) A[i] = new Integer((i * 11)%(A.length)); showData(S, 5); System.out.println(); showData(A, 12); System.out.println(); // Calling the selectionSort method defined by Lewis / Loftus in // the Sorting class. Sorting.selectionSort(S); Sorting.selectionSort(A); showData(S, 5); System.out.println(); showData(A, 12); System.out.println(); // Note: I modified the file CD.java to have it implement the // Comparable interface. If you already downloaded it, take a look // at the new version. Note also that had I so chosen, I could have // defined compareTo in the CD class to compare by any of the // fields in the class. Here it is just comparing by the title. MusicCD2 [] myCDs = new MusicCD2[4]; myCDs[0] = new MusicCD2("The Downward Spiral", "Nine Inch Nails", 8, "1/1/1994", new String[] {""}, 3901); myCDs[1] = new MusicCD2("Fables of the Reconstruction", "REM", 1, "", new String[] {""}, 2379); myCDs[2] = new MusicCD2("Diamond Life", "Sade", 4, "2/2/1985", new String[] {"Smooth Operator"}, 2692); myCDs[3] = new MusicCD2("Moby 18", "Moby", 0, "1/1/2002", new String[] {""}, 4274); showData(myCDs, 1); System.out.println(); Sorting.selectionSort(myCDs); showData(myCDs, 1); } }