日期:2014-05-20  浏览次数:20904 次

泛型里面的<T> List<T>前面的<T>代表是什么意思?为什么要加<T>?
如下面源代码,为什么前面要加上<T>呢?

Java code

 private <T> List<T> cashFutures(List<Future<T>> futures) {

        List<T> values = new ArrayList<T>();

        for (Future<T> future : futures) {
            try {
                values.add(future.get());
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }

        return values;
    }



------解决方案--------------------
是这样的,楼主,有了泛型的好处就是在编绎期你的代码就能被检测出问题来。
比如你有一个类是水果类class Fruit{...}
然后你的代码中把T全换成Fruit,那么以后你往ArrayList里面就只能加入Fruit及子类(如苹果,梨等),不然会直接报错。也就是你告诉编绎器说:在我的这个容器里面我只要加水果类,如果我误加了别的类(如铁类,人类,球类)请马上告诉我。
------解决方案--------------------
Java code
import java.util.*;

class Fruit {     public String toString() {    return "Fruit"; } }

class Apple extends Fruit {    public String toString(){ return "Apple";    } }

class Person {    public String toString(){    return "Person";    } }

class ClassName<T> {//主类,把你文件名改成ClassName.java
     

     void show_1(T t){
        System.out.println("show_1  "+ t.toString());
    }
    
    <E> void show_2(E e){
        System.out.println("show_2  "+e.toString());
    }
    
    <T> void show_3(T t){
        System.out.println("show_3  "+t.toString());
    }
    
    

    public static void main(String[] args) {
        ClassName<Fruit> o = new ClassName<Fruit>();
        Fruit f = new Fruit();
        Apple a = new Apple();
        Person p = new Person();
        System.out.println("show_1 演示________________________");
        o.show_1( f );
        o.show_1( a );
//        o.show_1( p );  楼主把这行代码去掉注释看一下,是不能编译通过的。因为在
//        ClassName<Fruit>中已经限定了全局的T为Fruit,所以不能再加入Person;
        System.out.println("show_2 演示________________________");
        o.show_2( f );
        o.show_2( a );
        o.show_2( p );
        System.out.println("show_3 演示________________________");
        o.show_3( f );
        o.show_3( a );
        o.show_3( p );
        
    }
}
[color=#800080]程序输出:
show_1 演示________________________
show_1  Fruit
show_1  Apple
show_2 演示________________________
show_2  Fruit
show_2  Apple
show_2  Person
show_3 演示________________________
show_3  Fruit
show_3  Apple
show_3  Person[/color]