Generic types allow you to write a general method with a type parameter (usually denoted as T). When the method gets called, T gets replaced by the actual type.

Here we use a parametrized interface Comprable<T>. By doing so we restrict the type of the parameter in compareTO method to T. This means that Vehicle can be compared only to another Vehicle, since it implements Comprable<Vehicle>. The class String in Java 5.0 implements Comprable<String>, therefore a String can be compared only to another String.

Here is the class Vehicle which implements Comprable<Vehicle>:



public class Vehicle implements Comparable<Vehicle> {
    protected String model;
    protected int maxPassengers;
    protected double maxSpeed;  // mph

    public Vehicle(String m, int passengers, double speed) {
        model = m;
        maxPassengers = passengers;
        maxSpeed = speed;
    }

    public int compareTo(Vehicle v) {
        return (int) (maxSpeed - v.maxSpeed);
    }

    // takes distance in miles, returns time in hours
    public double time(double distance) {
        return distance/maxSpeed;
    }


    public void print() {
        System.out.println("this is a " + model + ", it can carry " +
                           maxPassengers + " and can travel at " +
                           maxSpeed + " mph");
    }
}

Here is the testing program which defines min as a method with a type parameter T and uses it for Vehicles and Strings:

public class TestGenerics {
    public static void main(String [] args) {
	Vehicle [] vehicles = {new Car("Dodge",4,80.0,"automatic"),
			       new Airplane("Airbus",200,1000,30000),
			       new Vehicle ("Broom",1,100)};
	Vehicle v = min(vehicles);
	v.print();

	String [] strings = {"orange", "banana", "apple", "lemon", "kiwi"};
	String s = min(strings);
	System.out.println(s);
    }

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

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.