泛型
为什么使用泛型?
泛型可以让类型作为参数传入当你正在定义类,接口和方法时,可以让你用相同的代码用不同的输入类型
泛型的例子
我们先定义一个普通的class
public class Insstance() {
private int instance;
public void setInstance(int instance) {
this.instance = instance;
}
public int getInstatce() {
return this.instance;
}
}
我们可以使用以下两句代码测试
Instance ins = new Instance();
ins.setInstance(2);//不会报错
ins.setInstance("2");//会报错
但是如果我们为ins设置不同类型的属性该怎么做呢?这时候就需要泛型了
public class Insstance<T>() {
private T instance;
public void setInstance(T instance) {
this.instance = instance;
}
public T getInstatce() {
return this.instance;
}
}
Instance<String> ins = new Instance<>();
ins.setInstance("2");//不会报错
Instance<Integer> ins = new Instance<>();
ins.setInstance(2);//不会报错
上面只是泛型中泛型类类的使用,类似的还有泛型接口,泛型方法的使用
泛型参数的命名约定
- E - Element (used extensively by the Java Collections Framework)
- K - Key
- N - Number
- T - Type
- V - Value
- S,U,V etc. - 2nd, 3rd, 4th types