[转]java泛型中?和T的区别

在代码中经常会看到这样的函数

public static void printColl(ArrayList<?> al){
       Iterator<?> it = al.iterator();
       while(it.hasNext())
       {
           System.out.println(it.next().toString());
       }
}
  • <T>在java中都代表着泛型 属于类型形参的一种
  • <?>为类型通配符,类型通配符一般是使用?代替具体的类型实参,注意了,此处?是类型实参,而不是类型形参 。

下列为使用中的不同:

public class FanXing {
 
    TestA a = new TestA("13");
    TestA b = new TestA(123);
 
    public void getClass1(TestA<?> test) {
 
    }
    //报错
    public void getClass2(TestA<T> test) {
 
    }
}
 
class TestA<T> {
    private T t;
 
    public TestA(T key) {
        this.t = key;
    }
}

在使用泛型作为方法的参数时 就需要使用泛型通配符来解除传入参数的类型,类型参数就做不到

<?><T>的还有一个区别就在于字母形参可以在之后的函数调用函数。

public static void printColl(ArrayList<T> al){
        Iterator<T> it = al.iterator();
        while(it.hasNext())
        {
            T t = it.next();
            System.out.println(t.toString());
        }
}

参考文章:
https://blog.csdn.net/sinat_29774479/article/details/75072964

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值