Java中的泛型

案例一,使用泛型可以限制储存的值类型。

package ch9;
import java.util.*;

/**
 * Created by Jiqing on 2016/11/28.
 */
public class GenericList {
    public static void main(String[] args) {
        // 创建一个只想保存字符串的List集合
        List<String> strList = new ArrayList<String>(); // 泛型
        strList.add("疯狂Java讲义");
        strList.add("疯狂Android讲义");
        // 下面代码将引起编译错误
        // strList.add(5);
        strList.forEach(str -> System.out.println(str.length()));
    }
}

案例二,菱形语法,简洁方便

package ch9;
import java.util.*;

/**
 * Created by Jiqing on 2016/11/28.
 */
public class DiamondTest {
    // 泛型的菱形语法
    public static void main(String[] args) {
        // Java自动推断出ArrayList的<>里应该是String
        List<String> books = new ArrayList<>();
        books.add("疯狂Java讲义");
        books.add("疯狂Android讲义");
        books.forEach(ele -> System.out.println(ele.length()));

        Map<String,List<String>> schoolsInfo = new HashMap<>();
        List<String> schools = new ArrayList<>();
        schools.add("三打白骨精");
        schools.add("大闹天宫");
        schoolsInfo.put("孙悟空",schools);
        schoolsInfo.forEach((key,value) -> System.out.println(key + "-->" +value)); //孙悟空-->[三打白骨精, 大闹天宫]
    }
}

案例三,定义类使用泛型声明

package ch9;

import java.util.DoubleSummaryStatistics;

/**
 * Created by Jiqing on 2016/11/28.
 */
public class Apple<T>{ // 定义类使用泛型声明
    // 使用T类型形参定义实例变量
    private T info;
    public Apple() {}
    // 使用T类型定义构造器
    public Apple(T info) {
        this.info = info;
    }

    public void setInfo(T info) {
        this.info = info;
    }

    public T getInfo() {
        return this.info;
    }

    public static void main(String[] args) {
        // 由于传给T形参的是String  所以构造器参数只能是String
        Apple<String> a1 = new Apple<>("苹果");
        System.out.println(a1.getInfo()); // 苹果

        // 由于传给T形参的是Double,所以构造器参数只能是Double
        Apple<Double> a2 = new Apple<>(5.67);
        System.out.println(a2.getInfo()); // 5.67
    }
}

原文地址:https://www.cnblogs.com/jiqing9006/p/6111673.html