java 之 泛型

浅析理论:

一、概述
	1、编写代码更加方便
	2、增加安全性
二、声明
	1、在类上声明
		类名<泛型>
		如果多个,是用逗号隔开
		在整个类中都可以使用,除了静态方法
	2、在方法上声明
		<泛型> 返回值类型
		如果多个,使用逗号隔开
		在方法上的泛型仅在方法中有效
		方法的返回值,方法参数,方法一次都可以使用泛型
	3、范围约束
		<T extends B> 窄化(用于声明)
三、赋值
	1、在类型上赋值
		在定义引用时
	2、方法上泛型赋值
		在方法调用时
			显示的
				调用时卸载方法名前面
			隐式的
				比如用什么类型的变量接收方法返回值,则返回值的泛型就是什么
四、泛型的使用
	1、不给泛型赋值,则默认是Object,如果是窄化的,则默认是extents后面的
	2、<?> 任意类型 <? super Number> 限定范围 (注:此时是赋值)
	3、泛型信息不会保留到运行时 

  

基础案例:

package com.gongxy.genericity;

import com.sun.org.apache.xml.internal.serializer.ToSAXHandler;

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

/**
 * @author gongyg
 * @date 2020/8/25 10:04
 * @description 泛型类 <泛型单词Genericity>
 */
public class GenericityDemoDo<T> {
    private T data;

    public void setData(T data){
        this.data = data;
    }

    public T getData(){
        return this.data;
    }

    /*
    静态方法不可以使用传入的泛型类参数
    public static T getData(){
        return this.data;
    }
    */

    /**
     * 泛型方法
     */
    public static <K> K compareInteger(K k1, K k2){
        return ((Integer)k1 > (Integer)k2) ? k1 : k2;
    }

    @Override
    public String toString() {
        return "data:" + this.data;
    }

    public static void main(String[] args) {
        GenericityDemoDo<String> demoDo = new GenericityDemoDo<>();
        demoDo.setData("gongxy");
        System.out.println(demoDo.getData());
        System.out.println(GenericityDemoDo.<Integer>compareInteger(1, 2));
    }
}

/**
 * 定义的是一个类,而不是一个对象
 * 范围约束
 */
class GenericityDemo2Do<T extends GenericityDemoDo<String>>{
    public <K> T print(K k1){
        GenericityDemoDo<String> demoDo = new GenericityDemoDo<>();
        demoDo.setData((String)k1);
        return (T)demoDo;
    }

    public static void main(String[] args) {
        GenericityDemo2Do<GenericityDemoDo<String>> demo2Do = new GenericityDemo2Do<>();
        String value = demo2Do.<String>print("123").getData();
        System.out.println(value);
    }
}

class GenericityDemo3Test{
    public static void main(String[] args) {
        List<? super Collection> list = new ArrayList<>();
        list.add(new ArrayList());
    }
}

  

posted @ 2020-08-25 15:16  gygtech  Views(174)  Comments(0Edit  收藏  举报