• JAVA高级复习-泛型类、泛型方法的使用情景举例


    public class Student<T> {
        private T studentT;
    
        //静态方法中不能使用泛型
    //    public static void show(T studentT) {
    //        System.out.println(studentT);
    //    }
    
        public void read() {
            //泛型数组的错误写法,编译不通过,报错(Type parameter 'T' cannot be instantiated directly)
    //        T[] arr = new T[10];
    
            //泛型数组的正确写法,编译通过
            T[] objects = (T[]) new Object[10];
        }
    }
    
    package com.winson.example;
    
    import java.util.List;
    
    /**
     * 共性操作的DAO
     * 因为不清楚是操作那个具体的类,所以DAO定为使用泛型结构的泛型类
     */
    public class DAO<T> {
        //添加一条记录
        public boolean add(T t) {
            return false;
        }
    
        //删除一条记录
        public boolean delete(Integer id) {
            return false;
        }
    
        //修改一条记录(根据ID)
        public boolean update(T t, Integer id) {
            return false;
        }
    
        //查询一条记录(根据ID)
        public T selectOne(Integer id) {
            return null;
        }
    
        //查询所有记录
        public List<T> selectAll(Integer id) {
            return null;
        }
    
        /**
         * 泛型方法:使用情景:获取表中有多少条记录;获取最晚入职时间的人员
         */
    
        public <E> E getValue() {
            return null;
        }
    }
    
    
    package com.winson.example;
    
    import com.winson.Student;
    
    /**
     * @description:
     * @date: 2020/9/11 21:40
     * @author: winson
     */
    public class StudentDAO extends DAO<Student> {
    }
    
    
    public class DAOTest {
    
        @Test
        public void test01() {
            StudentDAO studentDAO = new StudentDAO();
            //参数为具体的类
            boolean res = studentDAO.add(new Student());
            //参数为具体的类
            boolean update = studentDAO.update(new Student(), 1);
    
            boolean delete = studentDAO.delete(1);
            //返回值为具体的类
            List<Student> students = studentDAO.selectAll(1);
            //返回值为具体的类
            Student student = studentDAO.selectOne(1);
        }
    
    }
    
  • 相关阅读:
    springboot+maven+thymeleaf配置实战demo
    报错AbstractStandardExpressionAttributeTagProcessor
    IllegalStateException: Unable to find a @SpringBootConfiguration
    Java装饰模式
    Java容器类解析
    jdk之object源码理解
    osx brew mysql
    java String[] 初始化
    date 常用
    mac mysql
  • 原文地址:https://www.cnblogs.com/elnimo/p/13654587.html
Copyright © 2020-2023  润新知