码迷,mamicode.com
首页 > 编程语言 > 详细

Java泛型:泛型类、泛型接口和泛型方法

时间:2017-09-02 00:09:57      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:string   style   ace   java   over   return   bsp   int   containe   

原文出自:https://segmentfault.com/a/1190000002646193

泛型类

public class Container<K, V> {
    private K key;
    private V value;

    public Container(K k, V v) {
        key = k;
        value = v;
    }

    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }
}

 

泛型接口

public interface Generator<T> {
    public T next();
}
public class FruitGenerator implements Generator<String> {

    private String[] fruits = new String[]{"Apple", "Banana", "Pear"};

    @Override
    public String next() {
        Random rand = new Random();
        return fruits[rand.nextInt(3)];
    }
}

 

泛型方法(一个基本的原则是:尽量使用泛型方法

    public static <T> void out(T t) {
        System.out.println(t);
    }

 

类型通配符(存在普通方法中,在不使用泛型方法时使用)

  上限:<? extends T> ?是T和T的子类

  下限:<? super T> ?是T和T的父类

Java泛型:泛型类、泛型接口和泛型方法

标签:string   style   ace   java   over   return   bsp   int   containe   

原文地址:http://www.cnblogs.com/m2492565210/p/7465416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!