泛型

泛型

为什么使用泛型?

泛型可以让类型作为参数传入当你正在定义类,接口和方法时,可以让你用相同的代码用不同的输入类型

泛型的例子

我们先定义一个普通的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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值