---
title: " java泛型之通配符的使用"
author: "美丽的小岛"
date: "2015-11-12T12:15:45Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-11-12T12:16:43Z"
id: 2256372
url: "https://happyprince.iteye.com/blog/2256372"
---

转自： http://blog.csdn.net/lonelyroamer/article/details/7927212

 

通配符有三种：

1、无限定通配符   形式&lt;?&gt;

2、上边界限定通配符 形式&lt; ? extends Number&gt;    //用Number举例

3、下边界限定通配符    形式&lt; ? super Number&gt;    //用Number举例

**1、泛型中的？通配符**

如果定义一个方法，该方法用于打印出任意参数化类型的集合中的所有数据，如果这样写

 

**\[java]** [view plain](http://blog.csdn.net/lonelyroamer/article/details/7927212 "view plain")[copy](http://blog.csdn.net/lonelyroamer/article/details/7927212 "copy")

 

01. import java.util.ArrayList;
02. import java.util.Collection;
03. import java.util.List;
04. publicclass GernericTest {
05. publicstaticvoid main(String\[] args) throws Exception{
06. List&lt;Integer&gt; listInteger =new ArrayList&lt;Integer&gt;();
07. List&lt;String&gt; listString =new ArrayList&lt;String&gt;();
08. printCollection(listInteger);
09. printCollection(listString);
10. }
11. publicstaticvoid printCollection(Collection&lt;Object&gt; collection){
12. for(Object obj:collection){
13. System.out.println(obj);
14. }
15. }
16. }

 

 

语句printCollection(listInteger);报错

The method printCollection(Collection&lt;Object&gt;) in the type GernericTest is not applicable for the arguments (List&lt;Integer&gt;)

这是因为泛型的参数是不考虑继承关系就直接报错。

这就得用？通配符

 

**\[java]** [view plain](http://blog.csdn.net/lonelyroamer/article/details/7927212 "view plain")[copy](http://blog.csdn.net/lonelyroamer/article/details/7927212 "copy")

 

01. import java.util.ArrayList;
02. import java.util.Collection;
03. import java.util.List;
04. publicclass GernericTest {
05. publicstaticvoid main(String\[] args) throws Exception{
06. List&lt;Integer&gt; listInteger =new ArrayList&lt;Integer&gt;();
07. List&lt;String&gt; listString =new ArrayList&lt;String&gt;();
08. printCollection(listInteger);
09. printCollection(listString);
10. }
11. publicstaticvoid printCollection(Collection&lt;?&gt; collection){
12. for(Object obj:collection){
13. System.out.println(obj);
14. }
15. }
16. }

 

在方法public static void printCollection(Collection&lt;?&gt; collection){}中不能出现与参数类型有关的方法比如collection.add();因为程序调用这个方法的时候传入的参数不知道是什么类型的，但是可以调用与参数类型无关的方法比如collection.size();

总结：使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量的主要用作引用，可以调用与参数化无关的方法，不能调用与参数化有关的方法。

 

 

**2、泛型中的?通配符的扩展**

1:界定通配符的上边界

Vector&lt;? extends 类型1&gt; x = new Vector&lt;类型2&gt;();

类型1指定一个数据类型，那么类型2就只能是类型1或者是类型1的子类

Vector&lt;? extends Number&gt; x = new Vector&lt;Integer&gt;();//这是正确的

Vector&lt;? extends Number&gt; x = new Vector&lt;String&gt;();//这是错误的

 

2:界定通配符的下边界

Vector&lt;? super 类型1&gt; x = new Vector&lt;类型2&gt;();

类型1指定一个数据类型，那么类型2就只能是类型1或者是类型1的父类

Vector&lt;? super Integer&gt; x = new Vector&lt;Number&gt;();//这是正确的

Vector&lt;? super Integer&gt; x = new Vector&lt;Byte&gt;();//这是错误的

 

提示：限定通配符总是包括自己

 

 

版权声明：本文为博主原创文章，未经博主允许不得转载。