Java—泛型

  • 泛型

  集合中的元素,可以是任意类型的对象(对象的引用),如果把某个对象放入集合,会忽略他的类型,而把他当做Object处理。

  泛型则是规定了某个集合只可以存放特定类型的对象,会在编译期间进行类型检查,可以直接按 指定类型获取集合元素。

  ChildCourse.java

package com.test.collection;

public class ChildCourse extends Course {

}

  GenericTest.java

package com.test.collection;

import java.util.ArrayList;
import java.util.List;

public class GenericTest {
    public List<Course> courses;
    
    public GenericTest() {
        courses = new ArrayList<Course>();
    }
    
    public void testAdd() {
        Course c1 = new Course("1", "大学物理");
        courses.add(c1);
        //泛型集合中,不能添加泛型规定的类型及其子类型以外的对象,否则会报错!
        //courses.add("能否添加一些奇怪的东西?");
        Course c2 = new Course("2", "复变函数");
        courses.add(c2);
    }
    
    public void testChild() {
        Course c1 = new ChildCourse();
        c1.id = "3";
        c1.name = "信号与系统";
        courses.add(c1);
    }
    
    public void testForEach() {
        for (Course c : courses) {
            System.out.println("课程:" + c.id + ":" + c.name);
        }
    }

    public static void main(String[] args) {
        GenericTest g = new GenericTest();
        g.testAdd();
        g.testForEach();
        g.testChild();
        g.testForEach();
    }

}

  执行结果:

  课程:1:大学物理
  课程:2:复变函数
  课程:1:大学物理
  课程:2:复变函数
  课程:3:信号与系统

  注:泛型集合中的限定类型不能为基本数据类型;可以使用包装类限定允许存入的基本数据类型

public void testBasicType(){
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    System.out.println("基本数据类型必须使用包装类作为泛型!" + list.get(0));
}
原文地址:https://www.cnblogs.com/tianxintian22/p/6683422.html