Object Methods & Generic Methods - Instead of developing almost identical classes and
methods that only change in data type (e.g. IntBagArray vs DoubleBagArray
you could use Object as the data type.
For example:
public static Object middle( Object [] data) {
if (data.length == 0)
{ // The array has no elements, so return null.
return null;
}
else
{ // Return an element near the center of the array.
return data[data.length/2];
}
}
Why Not Just Do This? - Well, using objects instead of generics is not quite a useful as
you have to make sure to cast your variables to and from objects in order for everything
to work and some casts may not work at runtime causing errors you can't catch as you compile.
Using Generic Method - A generic method is a method that is written with the types of the parameters not fully specified. Our middle method is written this way as a generic method:
public static <T> T middle(T[] data) {
if (data.length == 0)
{ // The array has no elements, so return null.
return null;
}
else
{ // Return an element near the center of the array.
return data[data.length/2];
}
}
Generic Type Parameter - <T> is a generic type parameter and can eventually be
supplied by the programmer when calling the method and supplied a variable of any class type.
The generic type parameter should be one character and should always be included with its angle
brackets before the return type of the same letter in the method. This syntax indicates to the
Java compiler that anywhere else in the method the generic type is replaced with that single letter.
Convention Alert! - The designers of Java recommend using a capital T for data types
and a capital E for elements when specifying a generic type parameter.
Generic Type Restrictions - A generic type must be of a class type and cannot be one of Java's
primitive data types.
Review: -
A generic method is written by putting a generic type parameter in angle brackets before the return type in the heading of the method.
For example: static <T> T middle(T[] data)...
The generic data type is often named with a single capital letter, such as T for “type.” The name T can then be used in the rest of the method implementation as if it were a real class name (with a few exceptions).
A programmer can activate a generic method just like any other method. The compiler will look at the data types of the arguments and infer a correct type for each generic type parameter. The inferred types help catch type errors at compile time.
For example: // i is an integer; ia is an Integer array; c is a Character
i = middle(ia); // This is fine
c = middle(ia); // Compile-time type error