A&lt; T extends B&gt;的区别是什么?和A <?扩展B&gt;? [英] What is the difference between A&lt;T extends B&gt; and A&lt;? extends B&gt;?

查看:1133
本文介绍了A&lt; T extends B&gt;的区别是什么?和A <?扩展B&gt;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新的java学习者。最近我正在阅读泛型编程,并对此感到困惑......

  A< T extends B>和A <?扩展B> 


解决方案

首先,这些是完全不同的结构不同的上下文。

A< T extends B> 是泛型类型声明的一部分,例如

  public class A< T extends B> {...} 

它声明通用类型 A T ,并在 T 上引入一个绑定,这样 T 必须是 B 的子类型。






A< ;?扩展B> 是一个带通配符的参数化类型,它可以在变量和方法声明等中用作普通类型:

  A< ;?扩展B> a = ...; 

public void foo(A< ;? extends B> a){...}

变量声明,如 A <?扩展B>一个表示 a 的类型是 A ,它的某些子类型为 B



例如,给出这个声明

 列表与LT ;?扩展Number>升; 

您可以:

    $ b $将 Number 的某些子类型的 List 赋值给 l

      l = new ArrayList< Integer>(); 


  • 获取 Number 从那个列表:

      Number n = l.get(0); 




但是,列表 l ,因为您不知道列表的实际类型参数:

  Double d = ...; 
.add(d); //不会编译


I am a new java learner. Recently I was reading Generic programming and got my self confused with this...

A<T extends B> and A<? extends B>

解决方案

First of all, those are completely different constructs used in different contexts.

A<T extends B> is a part of generic type declaration such as

public class A<T extends B> { ... }

It declares generic type A with type parameter T, and introduces a bound on T, so that T must be a subtype of B.


A<? extends B> is a parameterized type with wildcard, it can be used in variable and method declarations, etc, as a normal type:

A<? extends B> a = ...;

public void foo(A<? extends B> a) { ... }

Variable declaration such as A<? extends B> a means that type of a is A parameterized with some subtype of B.

For example, given this declaration

List<? extends Number> l;

you can:

  • Assign a List of some subtype of Number to l:

    l = new ArrayList<Integer>(); 
    

  • Get an object of type Number from that list:

    Number n = l.get(0);
    

However, you can't put anything into list l since you don't know actual type parameter of the list:

Double d = ...;
l.add(d); // Won't compile

这篇关于A&lt; T extends B&gt;的区别是什么?和A <?扩展B&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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