zoukankan      html  css  js  c++  java
  • 【Java基础总结】泛型

    泛型实现了参数化类型的概念,使代码可以应用于多种类型。

    1. 泛型类

    声明的泛型类型静态方法不能使用

    class Tools<T>{
        private T t;
        public void set(T t){
            this.t = t;
        }
        public T get(){
            return this.t;
        }
    }

    2. 泛型方法

    class GenericTest2<T>{
        //使用类定义的泛型
        public void print1(T t){
            System.out.println("print1:"+t);
        }
        //使用方法定义的泛型
        public <E> void print2(E e){
            System.out.println("print2:"+e);
        }
        //静态方法不能使用类定义的泛型
        public static <E> void print3(E e){
            System.out.println("print3:"+e);
        }
    }

    3. 泛型接口

    //泛型接口
    interface Inter<T>{
        void show(T t);
    }
    //
    class InterImpl2 implements Inter<String>{
        public void show(String t)
        {
            System.out.println("show:"+t);
        }
        
    }
    //
    class InterImpl<T> implements Inter<T>{
        public void show(T t){
            System.out.println("show:"+t);
        }
    }
    class GenericDemo5{
        public static void main(String[] args){
            InterImpl<Integer> i = new InterImpl<Integer>();
            i.show(5);
            //InterImpl i = new InterImpl();
            //i.show("liu");    
        }
    }

    4. 泛型限定

    HashSet<? extends Person> set = new HashSet<? extends Person>();   //限定存储Person或Person子类的对象
    HashSet<? super Person> set = new HashSet<? super Person>();   //限定存储Person或Person父类的对象
  • 相关阅读:
    RabbitMQ
    操作系统复习知识
    计算机网络相关知识复习
    转帖--Linux的文件检索(locate、find、which、whereis)
    go-ioutil
    使用wrk进行压测
    03x01 Java基础语法
    02x03 Hello World!!!
    02x02 环境搭建
    02x01 Java入门
  • 原文地址:https://www.cnblogs.com/lhat/p/6168895.html
Copyright © 2011-2022 走看看