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.

 
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));
    }

    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 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.