Java泛型学习二

通配符的使用

  上一篇中知道,Box<Number>和Box<Integer>实际上都是Box类型,现在需要继续探讨一个问题,那么在逻辑上,类似于Box<Number>和Box<Integer>是否可以看成具有父子关系的泛型类型呢?

 

为了弄清这个问题,我们继续看下下面这个例子:

 

复制代码
 1 public class GenericTest {
 2 
 3     public static void main(String[] args) {
 4 
 5         Box<Number> name = new Box<Number>(99);
 6         Box<Integer> age = new Box<Integer>(712);
 7 
 8         getData(name);
 9         
10         //The method getData(Box<Number>) in the type GenericTest is 
11         //not applicable for the arguments (Box<Integer>)
12         getData(age);   // 1
13 
14     }
15     
16     public static void getData(Box<Number> data){
17         System.out.println("data :" + data.getData());
18     }
19 
20 }
复制代码

 

我们发现,在代码//1处出现了错误提示信息:The method getData(Box<Number>) in the t ype GenericTest is not applicable for the arguments (Box<Integer>)。显然,通过提示信息,我们知道Box<Number>在逻辑上不能视为Box<Integer>的父类。那么,原因何在呢?

 

复制代码
 1 public class GenericTest {
 2 
 3     public static void main(String[] args) {
 4 
 5         Box<Integer> a = new Box<Integer>(712);
 6         Box<Number> b = a;  // 1
 7         Box<Float> f = new Box<Float>(3.14f);
 8         b.setData(f);        // 2
 9 
10     }
11 
12     public static void getData(Box<Number> data) {
13         System.out.println("data :" + data.getData());
14     }
15 
16 }
17 
18 class Box<T> {
19 
20     private T data;
21 
22     public Box() {
23 
24     }
25 
26     public Box(T data) {
27         setData(data);
28     }
29 
30     public T getData() {
31         return data;
32     }
33 
34     public void setData(T data) {
35         this.data = data;
36     }
37 
38 }
复制代码

 

这个例子中,显然//1和//2处肯定会出现错误提示的。在此我们可以使用反证法来进行说明。

 

假设Box<Number>在逻辑上可以视为Box<Integer>的父类,那么//1和//2处将不会有错误提示了,那么问题就出来了,通过getData()方法取出数据时到底是什么类型呢?Integer? Float? 还是Number?且由于在编程过程中的顺序不可控性,导致在必要的时候必须要进行类型判断,且进行强制类型转换。显然,这与泛型的理念矛盾,因此,在逻辑上Box<Number>不能视为Box<Integer>的父类。

 

好,那我们回过头来继续看“类型通配符”中的第一个例子,我们知道其具体的错误提示的深层次原因了。那么如何解决呢?总部能再定义一个新的函数吧。这和Java中的多态理念显然是违背的,因此,我们需要一个在逻辑上可以用来表示同时是Box<Integer>和Box<Number>的父类的一个引用类型,由此,类型通配符应运而生。

 

类型通配符一般是使用 ? 代替具体的类型实参。注意了,此处是类型实参,而不是类型形参!且Box<?>在逻辑上是Box<Integer>、Box<Number>...等所有Box<具体类型实参>的父类。由此,我们依然可以定义泛型方法,来完成此类需求。

 

复制代码
 1 public class GenericTest {
 2 
 3     public static void main(String[] args) {
 4 
 5         Box<String> name = new Box<String>("corn");
 6         Box<Integer> age = new Box<Integer>(712);
 7         Box<Number> number = new Box<Number>(314);
 8 
 9         getData(name);
10         getData(age);
11         getData(number);
12     }
13 
14     public static void getData(Box<?> data) {
15         System.out.println("data :" + data.getData());
16     }
17 
18 }
复制代码

 

有时候,我们还可能听到类型通配符上限和类型通配符下限。具体有是怎么样的呢?

 

在上面的例子中,如果需要定义一个功能类似于getData()的方法,但对类型实参又有进一步的限制:只能是Number类及其子类。此时,需要用到类型通配符上限。

 

复制代码
 1 public class GenericTest {
 2 
 3     public static void main(String[] args) {
 4 
 5         Box<String> name = new Box<String>("corn");
 6         Box<Integer> age = new Box<Integer>(712);
 7         Box<Number> number = new Box<Number>(314);
 8 
 9         getData(name);
10         getData(age);
11         getData(number);
12         
13         //getUpperNumberData(name); // 1
14         getUpperNumberData(age);    // 2
15         getUpperNumberData(number); // 3
16     }
17 
18     public static void getData(Box<?> data) {
19         System.out.println("data :" + data.getData());
20     }
21     
22     public static void getUpperNumberData(Box<? extends Number> data){
23         System.out.println("data :" + data.getData());
24     }
25 
26 }
复制代码

 

此时,显然,在代码//1处调用将出现错误提示,而//2 //3处调用正常。

在定义泛型类别时,预设可以使用任何的类型来实例化泛型类型中的类型。

但是如果想限制使用泛型类别时,只能用某个特定类型或者是其子类型才能实例化该类型时,可以在定义类型时,使用extends关键字指定这个类型必须是继承某个类,或者实现某个接口,也可以是这个类或接口本身。

比如下面的例子:  

复制代码
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class ListGenericFoo<T extends List>
{
    private T[] fooArray;

    public T[] getFooArray()
    {
        return fooArray;
    }

    public void setFooArray(T[] fooArray)
    {
        this.fooArray = fooArray;
    }
    
    public static void main(String[] args)
    {
        ListGenericFoo<LinkedList> foo1 = new ListGenericFoo<LinkedList>();
        ListGenericFoo<ArrayList> foo2 = new ListGenericFoo<ArrayList>();
        
        //Error: Bound mismatch
        //ListGenericFoo<HashMap> foo3 = new ListGenericFoo<HashMap>();
        
        LinkedList[] linkedLists = new LinkedList[10];
        foo1.setFooArray(linkedLists);
        
        ArrayList[] arrayLists = new ArrayList[10];
        foo2.setFooArray(arrayLists);
        
    }

}
复制代码

 

  类声明中:public class ListGenericFoo<T extends List>

  这样就规定了T必须是一个List继承体系中的类,即实现了List接口的类。

  此处注意,虽然List是一个接口,但是关键字仍然是extends而不是implements。

  并且这个List也可以后加括号指明类型,如List<String>等。

  当没有指定泛型继承的类型或接口时,默认使用T extends Object,所以默认情况下任何类型都可以作为参数传入。

 

  当不使用泛型时,比如那些声明时带有<T>的集合类型,如果使用时没有指定类型,泛型类别为Object。不会报错,但是会有警告。

  <? extends SomeClass>是一个限界通配符(bounded wildcard),?代表了一个未知的类型,并且它是SomeClass的子类,也可以是SomeClass本身。

  这里面SomeClass是统配符的上界(upper bound of the wildcard)。

  相应的也有限定下界的,使用关键字super。

  通配符所代表的其实是一组类型,但具体的类型是未知的。

类型通配声明

  看下面的代码:

    GenericFoo<Integer> foo1 = null;
     GenericFoo<Boolean> foo2 = null;
     //此时foo1只能接受GenericFoo<Integer>类型的实例,foo2只能接受GenericFoo<Boolean>类型的实例

          

  如果希望有一个变量foo可以指向下面所有的实例:

      //foo = new GenericFoo<ArrayList>();

      //foo = new GenericFoo<LinkedList>();

  可以这样声明:

    GenericFoo<? extends List> foo = null;

    foo = new GenericFoo<ArrayList>();

    foo = new GenericFoo<LinkedList>();

 

  注意这种形式不同于前面的限制泛型可用类型时提到的形式。

  前面提到的形式是在声明泛型的类的时候限制了可以用的泛型类型,而现在这种形式是在使用的时候限制了引用的类型,使得引用指向继承了某一个类或接口的类型。

  如果该应用指向其他类型,则会编译报错:

    //Error:Type mismatch
    foo = new GenericFoo<HashMap>();

 

  也可以限制引用指向某个类或接口的继承层次之上的类或接口:

  比如:        

    //引用指向继承层次之上
   GenericFoo<? super List> ge= null;
   ge = new GenericFoo<Object>();

 

  使用<?>或是<? extends SomeClass>的声明方式,意味着您只能通过该名称来取得所参考的实例的信息,或者是移除某些信息,但不能增加或者改写它的信息。

  因为只知道当中放置的是SomeClass的子类,但不确定是什么类的实例,编译器不让您加入信息,理由是,如果可以加入信息的话,那么您就得记得取回的是什么类型的实例,然后转换为原来的类型方可进行操作,这样就失去了使用泛型的意义。在方法参数中使用万用字符时,编译器会阻止任何可能破坏引用参数所指集合的行为,也就是说你可以操作集合元素,但不能新增集合元素,如此才能保障执行期间的安全性,因为编译器会阻止执行期间的恐怖行动。

  在声明函数时,以下两种声明功能相同:

  

public <T extends Animal> void takething(ArrayList<T> list)
public void takething(ArrayList<? extends Animal> list)

但是如果方法中有两个参数,使用时就会有差别,具体如下:

public <T extends Animal> void takething(ArrayList<T> one,ArrayList<T> two)

public void takething(ArrayList<? extends Animal> one,ArrayList<? extends Animal> two)

 

最后,GenericFoo<? extends Object>等价于GenericFoo<?>,但是它们与GenericFoo<Object>不同,因为GenericFoo<Object>限定了类型为Object。

参考资料:

http://www.cnblogs.com/mengdd/archive/2013/01/21/2869778.html

http://www.cnblogs.com/lwbqqyumidi/p/3837629.html

http://www.cnblogs.com/iyangyuan/archive/2013/04/09/3011274.html

http://www.cnblogs.com/sunwei2012/archive/2010/10/08/1845938.html

http://www.cnblogs.com/Fskjb/archive/2009/08/23/1552506.html

http://www.cnblogs.com/yinhaiming/articles/1749738.html

http://www.cnblogs.com/nerxious/archive/2012/12/21/2828121.html

http://www.cnblogs.com/anrainie/archive/2012/03/09/2387177.html

 

 

posted @ 2016-07-07 20:30  温暖的向阳花  阅读(238)  评论(0编辑  收藏  举报