泛型、泛型类、泛型方法相关问题解读

泛型是在JDK5中引入的特性,它提供了编译时类型安全检测机制,该机制允许在编译时检测到非法的类型。其本质是参数化类型,也就是说所操作的数据被指定为一个参数,将类型由原来的具体的类型参数化,然后在使用/调用时传入具体的类型。这种参数可以使用在类、方法、接口中,分别称为泛型类、泛型方法、泛型接口。

一、泛型类

/*
* 泛型 generic
* 修饰符 class 类名 <范型变量>{
* 范型变量一般用E,K,V,T;
* */
public class Student< E > {
    public  E e;

    public Student(E e) {
        this.e = e;
    }
    public Student() {
    }
    public E getE() {
        return e;
    }

    public void setE(E e) {
        this.e = e;
    }

    @Override
    public String toString() {
        return "学生{" +
                "编号=" + e +
                '}';
    }
}

public class GenericTest {
    public static void main(String[] args) {
       //使用String型
        Student<String> s1 = new Student<String>();
        s1.setE("abc");
        System.out.println(s1);
        //使用Integer
        Student<Integer> s2 = new Student<Integer>();
        s2.setE(123);
        System.out.println(s2);
    }
}

二、泛型方法
在这里插入图片描述
在使用不同变量使用同一个方法时,可以使用重写写出队形参数类型的类,但需要一一对应,不好,使用泛型类可以解决这个问题,但是泛型类在创键对象时便确定了参数类型,这就需要不断的创建所需类型的对象,也不好,这里我们引入泛型方法来解决这个问题。

public class Student1 {
    public <E> void show(E e){
        System.out.println(e);
    }

    public static void main(String[] args) {
        Student1 s1 = new Student1();
        s1.show("tom");
        s1.show(123);
        s1.show(true);
        s1.show(12.21);
    }
}

三、泛型接口
在这里插入图片描述

/*
* 泛型接口
* 格式
* public interface Generic<E>{}
* */
public interface Studentapi<E> {
    void show(E e);
}

public class StudentImpl<E> implements Studentapi<E> {
    public void show(E e){
        System.out.println(e);
    }

    public static void main(String[] args) {
        Studentapi<String> s1 = new StudentImpl<String>();//多态
        s1.show("abc");
        Studentapi<Integer> s2 = new StudentImpl<Integer>();//多态
        s2.show(123);
    }
}

四、可变参数(参数个数可变)
在这里插入图片描述

/*
* 可变参数
* 格式
* public static int sum(int...a){}
* 注意,如多参数,则把可变参数放在所有参数的后面
* */
public class Demo1 {
    public static void sum(String str,int...a){
        int sum = 0;
        for (int i:a
             ) {
            sum = sum+i;
        }
        System.out.println(str+":"+sum);
    }
    public static void main(String[] args) {
        Demo1 demo1 = new Demo1();
        demo1.sum("answer1",2,3,4,5,10,21);
        demo1.sum("answer2",2,3,4,5,54,2);
        demo1.sum("answer3",2,3,4,5,6);
    }
}

五、类型通配符

在这里插入图片描述
在这里插入图片描述
四、泛型优点
1.可以统一数据类型,便于操作。
2.将运行时的异常提前到了编译时,提高了效率。
3.避免了强制类型转换
4.实现代码的模板化,把数据类型当作参数传递,提高了可重用性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值