静态方法中的泛型
1.public static void show(T t){}错误
2.static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o);
} }
正确
泛型不可以在静态方法 中使用,那么为什么2是正确的
程序代码:
// Java除了支持泛型类以外,在处理相对简单的问题时,还支持更加简便的泛型方法。
// 即:在普通的类、或者泛型类中,定义一个带有类型参数的方法。
// 示例中的<T>称为类型变量。
// Java中规定,类型变量<T>放在修饰符public static后面,返回类型boolean/void前面。
// 泛型方法示例:判断一个对象是否为“负”
public class GenericMethod {
public static void main(String[] args) {
GenericMethod.<Integer>print(-1); // 调用泛型方法时,在方法名前面的尖括号中指定具体的类型
print(0); // 在编译器已经有足够信息可以决定类型时,可以使用简写方式,下同
print(1);
GenericMethod.<Double>print(-1.0);
print(0.0);
print(1.0);
GenericMethod.<String>print("-1");
print("0");
print("1");
GenericMethod.<Object>print(null);
print(null);
}
public static <T> boolean isNegative(T x) {
boolean returnValue = false;
try {
if (x != null && x.toString().trim().length() > 0) {
if (x.toString().trim().substring(0, 1).equals("-")) {
returnValue = true;
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
}
return returnValue;
}
public static <T> void print(T x) {
if (isNegative(x)) {
System.out.println(x + "\tis a negative number.");
} else {
System.out.println(x + "\tis not a negative number.");
}
}
}
程序代码:-1 is a negative number. 0 is not a negative number. 1 is not a negative number. -1.0 is a negative number. 0.0 is not a negative number. 1.0 is not a negative number. -1 is a negative number. 0 is not a negative number. 1 is not a negative number. null is not a negative number. null is not a negative number.