Java方法返回值前面的<T>是啥?

Java方法返回值前面的是什么?
它的作用是“定义泛型”
一段简单的代码

class Show<T> {
	public void print1(T t) {
		System.out.println(t);
	}

	public <T> void print2(T t) {
		System.out.println(t);
	}
}

public class Demo {
	public static void main(String[] args) {
		Show<String> show = new Show<String>();
		show.print1(new Integer(1));// 不能编译
		show.print2(new Integer(1));// 可以编译
	}
}

Show类定义了泛型T,它有两个print方法,两个方法只有一点差别,print2有,而print1没有。
Demo类实例化Show类,并将泛型类型定义为String类型,却为两个print方法传入Integer类型的对象。print2可以编译,而print1不可编译。
print1中的泛型与show对象的泛型相同,都是String,因此不能传入Integer类型的参数。而print2方法自定义了一个泛型T,因此方法参数类型不受对象泛型类型限制,这样定义的话这个方法是可以传入任意类型的参数的。

其它问题
IDE(Eclipse)警告“The type parameter T is hiding the type T”,这是因为print2方法定义的泛型名与类定义的泛型名相同,都为T。将print2方法的泛型名改为E,或是其它的,就不会有警告了。如果同名的话,调用方法时方法的泛型将覆盖对象的泛型。

猜你喜欢

转载自blog.csdn.net/u010651249/article/details/83929924
今日推荐