java泛型笔记

泛型好处
    * 提高安全性(将运行期的错误转换到编译期) 
    * 省去强转的麻烦
泛型基本使用
    * <>中放的必须是引用数据类型 
泛型使用注意事项
    * 前后的泛型必须一致,或者后面的泛型可以省略不写(1.7的新特性菱形泛型)

类内的方法最好与类的泛型一致,否则需要在方法上声明该泛型:

静态方法必须声明自己的泛型,它不能跟类的泛型是一致的(即是需要在static与返回值之间添加<T>,该静态方法的参数也应有T  t或者它的子类

public class Tool<T> {
    private T t;
    
	public T getobj() {
		return t;
	}

	public void setObject(T t) {
		this.t = t;
	}

	public Tool() {
		// TODO Auto-generated constructor stub
	}
	public void see(T t) {
		System.out.println(t);
	}
	
	public<E> void show(E e) {
		System.out.println(e);
	}
    public static <W> void see(W w){
     System.out.println(w);
}
    
}

猜你喜欢

转载自blog.csdn.net/rngweskt/article/details/82914755