• 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));
    }
  • 相关阅读:
    树莓派上使用docker部署aria2,minidlna
    在Ubuntu上部署一个基于webrtc的多人视频聊天服务
    解决.net core3.1使用docker部署在Ubuntu上连接sqlserver报error:35的问题
    .Net Core in Docker
    .Net Core in Docker
    SQL Server in Docker
    使用Docker运行SQL Server
    Spring Boot 2.x(四):整合Mybatis的四种方式
    Spring Boot 2.x (一):HelloWorld
    yarn (npm) 切换设置镜像源
  • 原文地址:https://www.cnblogs.com/tianxintian22/p/6683422.html
Copyright © 2020-2023  润新知