zoukankan      html  css  js  c++  java
  • java 泛型

    1.泛型的定义

    Java 泛型(generics)是 JDK 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型

    public class Hello{
    
        // 泛型在返回类型之前
        public static <E> void printArray(E[] inputArray) {
            for (E element:inputArray) {
                System.out.printf("%s",element);        
            }
            System.out.println();
        }
    
        // 定义泛型
        public static <T> T printT (T name) {
            return name;
        }
        // 有界的类型参数
        public static <T extends Comparable<T>> T maxImun (T x, T y) {
            if (y.compareTo(x) > 0) {
                return y;
            } else {
                return x;
            }
        }
    
        public static void main(String[] args) {
            Integer[] intArray = {1,2,3,4,5};
    
            printArray(intArray);
            Integer x = 2;
            Integer y = 3;
            int c = 20;
            System.out.println(maxImun(x,c));
        }
    
    }

    2.泛型类

    class Box<T> {
        private T t;
    
        public void add(T t){
            this.t = t;
        }
    
    }

    3.泛型通配符

    class GenericTest {
        // 类型通配符
        public static void getData (List<?> data) {
            System.out.println(data.get(0));
        }
    
        // 类型通配符上界
        public static void getUperNumber (List<? extends Number> data){
            System.out.println(data.get(0));
        }
    }
  • 相关阅读:
    文件IO学习
    简单哈希表学习
    关于二叉树的遍历
    关于多点共线问题
    关于线程
    时间复杂度O()与KMP算法
    单链表相关
    拷贝构造函数与深浅拷贝
    在windows把python写成bat文件的坑
    python学习手册:第二十五章——oop
  • 原文地址:https://www.cnblogs.com/myvic/p/8990220.html
Copyright © 2011-2022 走看看