In the preceding section, you have seen how to define a generic class. You can also define a single method with type parameters. class ArrayAlg { public static <T> T getMiddle(T[] a) { return a[a.length / 2]); } } This method is defined inside an ordinary class, not inside a generic class. However, it is a generic method, as you can see from the angle brackets and the type variable. Note that the type variables are inserted after the modifiers (public static, in our case) and before the return type. You can define generic methods both inside ordinary classes and inside generic classes. When you call a generic method, you can place the actual types, enclosed in angle brackets, before the method name: String[] names = { "John", "Q.", "Public" }; String middle = ArrayAlg.<String>getMiddle(names); In this case (and indeed in most cases), you can omit the <String> type parameter from the method call. The compiler has enough information to infer the method that you want. It matches the type of names (that is, String[]) against the generic type T[] and deduces that T must be String. That is, you can simply call String middle = ArrayAlg.getMiddle(names); C++ NOTE
|