import java.uti1.*;
public class CreateAnArrayList {
public < t > void makeArrayList(T t) { // take an object of an
// unknown type and use a
// "T" to represent the type
List< t > list = new ArrayList
// list using "T"
list.add(t);
}
}
In the preceding code, if you invoke the makeArrayList() method with a Dog instance, the method will behave as though it looked like this all along:
public void makeArrayList(Dog t) {
List
list.add(t);
}
And of course if you invoke the method with an Integer, then the T is replaced by Integer (not in the bytecode, remember—we're describing how it appears to behave, not how it actually gets it done).
The strangest thing about generic methods is that you must declare the type variable BEFORE the return type of the method:
public
The
You're also free to put boundaries on the type you declare, for example if you want to restrict the makeArrayList() method to only Number or its subtypes (Integer, Float, and so on) you would say
public
No comments:
Post a Comment