Java教程 – 如何在Java中创建泛型方法
可以创建一个包含在非泛型类中的通用方法。
public class Main {
static <T, V extends T> boolean isIn(T x, V[] y) {
for (int i = 0; i < y.length; i++) {
if (x.equals(y[i])) {
return true;
}
}
return false;
}
public static void main(String args[]) {
Integer nums[] = { 1, 2, 3, 4, 5 };
if (isIn(2, nums)){
System.out.println("2 is in nums");
}
String strs[] = { "one", "two", "three", "four", "five" };
if (isIn("two", strs)){
System.out.println("two is in strs");
}
}
}
上面的代码生成以下结果。

例子
下面的代码声明一个 copyList()通用方法。
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> ls = new ArrayList<String>();
ls.add("A");
ls.add("B");
ls.add("C");
List<String> lsCopy = new ArrayList<String>();
copyList(ls, lsCopy);
List<Integer> lc = new ArrayList<Integer>();
lc.add(0);
lc.add(5);
List<Integer> lcCopy = new ArrayList<Integer>();
copyList(lc, lcCopy);
}
static <T> void copyList(List<T> src, List<T> dest) {
for (int i = 0; i < src.size(); i++)
dest.add(src.get(i));
}
}
Java通用构造函数
构造函数可以是通用的,即使它们的类不是。例如,考虑以下短程序:
class MyClass {
private double val;
<T extends Number> MyClass(T arg) {
val = arg.doubleValue();
}
void showval() {
System.out.println("val: " + val);
}
}
public class Main {
public static void main(String args[]) {
MyClass test = new MyClass(100);
MyClass test2 = new MyClass(123.5F);
test.showval();
test2.showval();
}
}
上面的代码生成以下结果。


国外主机测评 - 国外VPS,国外服务器,国外云服务器,测评及优惠码













