public class GenericExample { // generic method given a type T // returns the last element from an array of Ts // note the is to denote generic method // the T after that is the return type public static T getLast(T list[]) { if (list == null || list.length == 0) { return null; } // doesn't make sense even if we sometimes have array of cats //list[0].miaow(); return list[list.length - 1]; } // generic method given a type T // returns whether list has nulls in it public static boolean hasNulls(T list[]) { // if no list or no length, no nulls if (list == null || list.length == 0) { return false; } for (int i = 0; i < list.length; i++) { if (list[i] == null) { return true; } } return false; } // generic method with bounded type // note we would use "extends" even for interfaces // a and b must be the same type // which must be or extend Namey public static T matchesName(String s, T a, T b) { // if a's name matches if (a.getName().equals(s) ) { return a; } // if b's name matches if (b.getName().equals(s) ) { return a; } // neither matches return null; } public static void main(String[] args) { // this pair holds a string and an int // we can't really say int, so we Integer wrapper class // Java will autobox the ints we use for us MyPair p1 = new MyPair("hello", 53); System.out.println(p1); // Java unboxes too -- Integer becomes int int q = p1.getSecond(); // this pair holds an int and a Cat MyPair p2 = new MyPair(75, new Bee()); System.out.println(p2); // we specified the type, // so we know what getSecond returns for this pair // so no problem calling Cat-specific method. p2.getSecond().sting(); Coordinate c1 = new Coordinate(2, 4); Coordinate c2 = new Coordinate(); System.out.println(c1 + " to " + c2 + " is " + c1.distance(c2)); // array of ninjas Ninja[] nlist = {new Ninja("Mr. Death"), new Ninja("Black Widow"), new Ninja("Killy")}; // to use with generic method, use Integer wrapper class // and let Java autobox Integer[] intlist = {1, 2, 3, 4, 5}; // call generic method for ninjas System.out.println(getLast(nlist)); // we know it will return a ninja getLast(nlist).assassinate(p2.getSecond()); // call generic method for ints System.out.println(getLast(intlist)); Ninja n1 = new Ninja("Ninja A"); Ninja n2 = new Ninja("Ninja B"); // we know it will return a Ninja Ninja nMatch = matchesName("Ninja A", n1, n2); MyPair pa= new MyPair(new Bee(), true); MyPair pb = new MyPair(new Bee(), false); pa.setName("Deadly Bees"); pb.setName("Covered in Bees"); // we know it will return a MyPair whose first is a Bee matchesName("Covered in Bees", pa, pb).getFirst().sting(); } }