Java generics and "..."
- What do
T
andS
mean?
开发者_JS百科 public void main(String... abc)
; what does...
mean? Is...
called generic as well?
- That are parameterized types. You can use any identifier here to represent a certain object type.
- That are varargs. You can pass a single String, or multiple Strings, or a String array in.
T
and S
are generic classes. They can be any type of class that you want. For example, Map<K, V>
uses the K
for the key class and V
for the value class.
Map<Integer, String> map = new HashMap<Integer, String>
As for the String...
, it means any number of String parameters.
- Please read the documentation. Briefly, they are type parameters so that generic types and methods can know what type of objects they are acting on.
- That indicates that the method can accept a variable number of arguments. See varargs. It's basically sugar around an array.
Sun's Java Generics documentation can be a bit hard to understand at times, so I tried to write a simpler tutorial on Java Generics. You can find it here:
http://tutorials.jenkov.com/java-generics/index.html
complementing:
String...
is almost the same as String[]
.
On the method side it is the same,
on the calling side the're is a difference: the compiler creates the array from the parameters.
void method(String... args) {
// args is an array: getClass() returns [java.lang.String
if (args.length > 0) {
System.out.println(args[0]);
...
method(); // same as method(new String[0]);
method("1", "2", "3"); // same as method(new String[] {"1", "2", "3"});
T and S means that the class itself does not know what classes they are, but things that use the class do.
Take java.util.List. The list class does not know anything about T and makes no assumptions about T. Things that use the List class:
List<MyBean> l = new ArrayList<MyBean>();
Know what's in it.
精彩评论