A generic class is a class with one or more type variables. In this chapter, we use a simple Pair class as an example. This class allows us to focus on generics without being distracted by data storage details. Here is the code for the generic Pair class: public class Pair<T> { public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } private T first; private T second; } The Pair class introduces a type variable T, enclosed in angle brackets < >, after the class name. A generic class can have more than one type variable. For example, we could have defined the Pair class with separate types for the first and second field: public class Pair<T, U> { . . . } The type variables are used throughout the class definition to specify method return types and the types of fields and local variables. For example, private T first; // uses type variable NOTE
You instantiate the generic type by substituting types for the type variables, such as Pair<String> You can think of the result as an ordinary class with constructors Pair<String>() Pair<String>(String, String) and methods String getFirst() String getSecond() void setFirst(String) void setSecond(String) In other words, the generic class acts as a factory for ordinary classes. The program in Example 13-1 puts the Pair class to work. The static minmax method traverses an array and simultaneously computes the minimum and maximum value. It uses a Pair object to return both results. Recall that the compareTo method compares two strings, returning 0 if the strings are identical, a negative integer if the first string comes before the second in dictionary order, and a positive integer otherwise. C++ NOTE
Example 13-1. PairTest1.java1. public class PairTest1 2. { 3. public static void main(String[] args) 4. { 5. String[] words = { "Mary", "had", "a", "little", "lamb" }; 6. Pair<String> mm = ArrayAlg.minmax(words); 7. System.out.println("min = " + mm.getFirst()); 8. System.out.println("max = " + mm.getSecond()); 9. } 10. } 11. 12. class ArrayAlg 13. { 14. /** 15. Gets the minimum and maximum of an array of strings. 16. @param a an array of strings 17. @return a pair with the min and max value, or null if a is 18. null or empty 19. */ 20. public static Pair<String> minmax(String[] a) 21. { 22. if (a == null || a.length == 0) return null; 23. String min = a[0]; 24. String max = a[0]; 25. for (int i = 1; i < a.length; i++) 26. { 27. if (min.compareTo(a[i]) > 0) min = a[i]; 28. if (max.compareTo(a[i]) < 0) max = a[i]; 29. } 30. return new Pair<String>(min, max); 31. } 32. } |