CSC152 2005S, Class 32: Java Generics Admin: * Ring pops! * Extra credit for 5K walk/run * Extra credit for significant class participation in 5K walk/run * Extra credit for Stone's talk Wednesday at 4:30 * Questions for the exam * Reminder: We may have a visitor tomorrow * Note: Reading tonight (I hope) Overview: * Heterogenous vs. homogenous types * Parameterizing types * Java's solution: Generics * Using generics for linear structures * Using generics for dictionaries "Do the indices in a dictionary have to be the same type of object?" => Are dictionaries homogenous or heterogeneous? "Homogenous: Same type; Hetereogenous: Different type" Consider some kind of linear structure LinearStructure stuff = ...; for (int i = 0; i < 10; i++) stuff.put(BigInteger.valueOf(i)); // Note: stuff should only contain BigIntegers while (!stuff.isEmpty()) { BigInteger bi = stuff.get(); } Why can we successfully put BigIntegers? * Because linear structures contain Objects, and every BigInteger is an object (Polymorphism) Why can we not successfull get BigIntegers? * Because Java is too damn stupid to know that stuff contains only BigIntegers. * We can tell it so by casting stuff.get() Linear structures are * Homogeneous: They only contain objects * Heterogeneous: They can contain different kinds of objects * Homogeneous: We can choose to use them homogenously (only put in Strings or BigIntegers or whatever) Java 1.5 introduced "generics": We can "parameterize" any class with a type (or with more than one type) public interface NewLinear { public void put(T putme); public T get(); public T peek(); public boolean isEmpty(); } Put the type varaible in angle brackkets after the interface or class name. Use the type variable as a type hane in function declarations Using them: NewLinear ints = ...; BigInteger i = ints.get(); Why do this? * Don't have to cast result * Clarify code * Java can catch you being stupid Making parameterized types more useful: You can restrict the type of the type parameter // One form of priority queue: Only permit comparable things that can be compared to each other * Integers are Comparable (they implement that interface) * Strings are Comparable (they implement that interface) * Integers and Strings are not comparable (they cannot be compared to each other) * We want: * The things we store to implement Comparable * The things we store to have the same type, so they can be compared to each other public interface NewPriorityQueue extends NewLinear Observation: We can still acheive heterogeneity by choosing a very general type and using polymorphism NewLinear stuff = ...; PQ otherstuff = ... Suppose we were defining, let's say, dictionaries. Can we have more than one type parameter (e.g., one for the type of the index and one for the type of the value)? Yes. Use a comma to separate the two. public interface NewDict { public void put(I index, V value); public V get(I index); }