import java.util.ArrayList; public class GenericTest { //a generic method to print values //specify a type variable T public static void listData(T[] data){ //variable of type T for(T item: data){ System.out.print(item + " "); } System.out.println(); } //get the largest item in an array //The type T should be Comparable //This is an "upper bound" for T //You can specify "lower bound" with super public static > T getMax(T[] data){ if(data.length == 0) return null; T max = data[0]; for(int i = 1; i < data.length; i++){ if(max.compareTo(data[i]) < 0) max = data[i]; } return max; } /** * @param args */ public static void main(String[] args) { Integer[] intData = {1,2,3,4,5}; Double[] dblData = {.1, .2, .3, .4, .5}; String[] strData = {"one", "two", "three", "four", "five"}; listData(intData); listData(dblData); listData(strData); int iMax = getMax(intData); double dMax = getMax(dblData); String sMax = getMax(strData); System.out.printf("Max: %d %f %s\n", iMax, dMax, sMax); Association a1 = new Association(3, 6); Association a2 = new Association(3, "six"); Association a3 = new Association(3,6); System.out.println(a1.equals(a2)); System.out.println(a1.equals(a3)); System.out.println(a3.equals(a1)); //create a list of Associations involving numbers ArrayList> list = new ArrayList>(); list.add(a1); list.add(a3); //list.add(a2); //doesn't work //list.add("worth a try"); //won't work either } }