您可以按照下面的方法一个:
1)基本,单一类型:
//One type
public static <T> void fill(List <T> list, T val) {
for(int i=0; i<list.size(); i++){
list.set(i, val);
}
}
2)多种类型:
// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {
return val1+" "+val2;
}
3)下面会引发编译器错误,因为'T3不在函数声明部分使用的泛型类型列表中。
//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}
正确:编译细
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}
样品类代码:
package generics.basics;
import java.util.ArrayList;
import java.util.List;
public class GenericMethods {
/*
Declare the generic type parameter T in this method.
After the qualifiers public and static, you put <T> and
then followed it by return type, method name, and its parameters.
Observe : type of val is 'T' and not '<T>'
* */
//One type
public static <T> void fill(List <T> list, T val) {
for(int i=0; i<list.size(); i++){
list.set(i, val);
}
}
// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {
return val1+" "+val2;
}
/*// Q: To audience -> will this compile ?
*
* public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
return 0;
}*/
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
return null;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
System.out.println(list.toString());
fill(list, 100);
System.out.println(list.toString());
List<String> Strlist = new ArrayList<>();
Strlist.add("Chirag");
Strlist.add("Nayak");
System.out.println(Strlist.toString());
fill(Strlist, "GOOD BOY");
System.out.println(Strlist.toString());
System.out.println(multipleTypeArgument("Chirag", 100));
System.out.println(multipleTypeArgument(100,"Nayak"));
}
}
//类定义结束
样本输出:
[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak
我不明白为什么对这两个问题都是“是”(具体而言,为什么“是”,“这会工作吗?”)。上面的函数(我知道,用int返回)不会接受这两种不同的类型,因为它对于两个参数都需要相同的泛型类型T,对吧? – ash 2009-11-18 22:29:47
对不起 - 我的意思是“是有可能的”和“是的,在您定义的签名中,类型需要相同” – 2009-11-18 22:32:46
我已经澄清了它 – 2009-11-18 22:34:08