Generic reverse method and its testing program.

public class GenericReverse {
    public static void main( String [] args) {
	String [] strings = {"apples","bananas", "oranges", "grapes", 
			     "lemons"};
	reverse(strings);
	print(strings);

	Car [] cars = {new Car("Dodge",4,80,"automatic"), 
		       new Car("Honda",2, 100, "manual"),
		       new Car("Toyota",4,90,"automatic")};
	reverse(cars);
	print(cars);
    }

    public static void print(Object [] array) {
	for (int i = 0; i < array.length; ++i) {
	    System.out.println(array[i]);
	}
    }

    public static void reverse(Object [] array) {
	for (int i = 0; i < array.length/2; ++i) {
	    Object temp;
	    temp = array[i];
	    array[i] = array[array.length-1-i];
	    array[array.length-1-i] = temp;
	}
    }
}
A generic method for finding a minimum and a generic quicksort method.

 
public class GenericMin {

    public static void main( String [] args) {
	String [] strings = {"bananas", "oranges", "grapes", "mango",
			     "lemons", "pineapples", "apples", "kiwi", 
			     "watermelons", "tangerines"};
	System.out.println(min(strings));
	quickSort(strings);
	print(strings);
    }

    public static Comparable min(Comparable [] array) {
	Comparable min = array[0];
	for (int i = 1; i < array.length; ++i) {
	    if (min.compareTo(array[i]) > 0) {
		min = array[i];
	    }
	}
	return min;
    }

    public static void quickSort(Comparable [] array) {
	quickSortRec(array, 0, array.length - 1);
    }

    public static void quickSortRec(Comparable [] array, int first, int last) {
	// System.out.println(first + " , " + last);
	// print(array);
	if (first >= last ) return;
	Comparable pivot = array[last];
	// partition the array with this pivot
	int i = first;
	for (int j = first; j < last; ++j) {
	    if (array[j].compareTo(pivot) < 0) {
		Comparable a = array[i];
		array[i] = array[j];
		array[j] = a;
		i++;
	    }
	}
	Comparable a = array[i];
	array[i] = array[last];
	array[last] = a;
	quickSortRec(array,first,i-1);
	quickSortRec(array,i+1,last);
    }

    public static void print(Object [] array) {
	for (int i = 0; i < array.length; ++i) {
	    System.out.println(array[i]);
	}
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.