泛型

本博参考:http://baike.baidu.com/item/java%E6%B3%9B%E5%9E%8B?fr=aladdin

java泛型是1.5之后提出来的一个概念,它具有以下特性

  1.泛型的类型参数只能是类类型,不可以是简单类型或基本类型;

  2.泛型的类型参数可以有多个;

  3.泛型可以使用extends跟super关键字

    比如:<T extends Collection>表示泛型必须为Collection的子类,比如ArrayList等

    比如:<T super String> 表示泛型必须是String的超类,比如Object类

  4.泛型还可以使用通配符

    比如:Class<?> clazz = String.getClass();

  5.泛型依然存在单继承类,多继承接口,多继承接口的原则:

    比如:<T extends SomeClass & interface1 & interface2 & interface3>

案例一:基本发型案例

package com.wyw;
/**
 * Created by wuyawei on 2017/4/20.
 */
public class Test {
    public static void main(String[] args) throws Exception {
        Hello<Integer> hello = new Hello<>();
        hello.setT(45);
        System.out.println(hello.getT());
        hello.showType();

        Hello<String> hello1 = new Hello<>();
        hello1.setT("sssssssss");
        System.out.println(hello1.getT());;
        hello1.showType();
    }

}
class Hello<T>{
    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

    public void showType(){
        System.out.println("这个泛型的类名称为:"+t.getClass().getName());
    }
}

运行结果

45
这个泛型的类名称为:java.lang.Integer
sssssssss
这个泛型的类名称为:java.lang.String

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

案例二:extends & super

package com.wyw;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by wuyawei on 2017/4/20.
 */
public class Test {
    public static void main(String[] args) throws Exception {
        CollectionTool<ArrayList<String>> collectionTool = new CollectionTool<>(new ArrayList<String>());
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("a");
        arrayList.add("b");
        arrayList.add("c");
        collectionTool.setT(arrayList);
        for (int i = 0;i<collectionTool.getT().size();i++){
            System.out.println(collectionTool.getT().get(i).toString());
        }
    }

}
class CollectionTool<T extends Collection>{
    private T t;
    public CollectionTool(T t){
        this.t = t;
    }
    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}

案例三:泛型方法

package com.wyw;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by wuyawei on 2017/4/20.
 */
public class Test {
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.getSomething(1);
        test.getSomething("a");
        char c = 'c';
        test.getSomething(c);
        test.getSomething(new Object());
    }

    public <T> void getSomething(T t){
        System.out.println(t.getClass().getName());
    }

}

运行结果

java.lang.Integer
java.lang.String
java.lang.Character
java.lang.Object

posted @ 2017-05-16 11:02  青春不打烊  阅读(171)  评论(0编辑  收藏  举报