传递给方法的无界通配符 [英] Unbounded wildcard passed to method

查看:74
本文介绍了传递给方法的无界通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class ColTest {
static< T> T wildSub(ArrayList<?extends T> holder,T arg){
T t = holder.get(0);
return t;
}

public static void main(String [] args){
ArrayList<?> list = new ArrayList< Long>(Arrays.asList(2L,3L,7L));
Long lng = 1L;
ColTest.wildSub(list,lng);






$ b

真正感兴趣的是为什么这段代码是合法的,因为签名的wildSub只需要 ArrayList of T 或从 T ,以及 T 类型的参数。但<?> 表示 - 某些特定类型,未知,以及它如何满足编译器?所有类型<?> 并不意味着< ;? extends Long> ...

解决方案

这是由于 capture转换。在内部,编译器将表达式 Foo<> 的类型转换为 Foo< X> ,其中 X 是一个特定的虽然未知的类型。


public class ColTest {
static<T> T wildSub(ArrayList<? extends T> holder, T arg){
        T t=holder.get(0);
        return t;
    }

    public static void main(String[] args) {
        ArrayList<?> list=new ArrayList<Long>(Arrays.asList(2L,3L,7L));
        Long lng=1L;
        ColTest.wildSub(list, lng);
    }
}

Really interested why this snippet is legal, because the signature of wildSub takes only ArrayList of T or derived from T, and arg of type T. But <?> means - some specific type, not known, and how it can satisfy the compiler? After all type <?> doesn't mean <? extends Long> ...

解决方案

This is due to capture conversion. Internally, compiler converts the type of an expression Foo<?> to Foo<X>, where X is a specific albeit unknown type.

这篇关于传递给方法的无界通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆