JAVA泛型学习

                

泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。

泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。

假定我们有这样一个需求:写一个排序方法,能够对整型数组、字符串数组甚至其他任何类型的数组进行排序,该如何实现?

答案是可以使用 Java 泛型

使用 Java 泛型的概念,我们可以写一个泛型方法来对一个对象数组排序。然后,调用该泛型方法来对整型数组、浮点数数组、字符串数组等进行排序。

java中泛型标记符:

  • E - Element (在集合中使用,因为集合中存放的是元素)
  • T - Type(Java 类)
  • K - Key(键)
  • V - Value(值)
  • N - Number(数值类型)
  •  - 表示不确定的 java 类型

实例:

泛型类:

/**
 * @parm <T>此处的T可以随便写为任意标识,常见的有T、E等形式的参数表示泛型
 *  *       泛型在定义的时候不具体【Object类型】,使用的时候才变得具体。
 *  *       在使用的时候确定泛型的具体数据类型。即在创建对象的时候确定泛型。
 */

public class Pair<T> {
    private  T t;
    public Pair(T t) {
        this.t = t;
    }
    public T getValue() {
        return t;
    }
    public void setValue(T t) {
        this.t = t;
    }
}

使用:

public class Main {
    public static void main(String[] args) {
       Pair<String> pair = new Pair<>("hello");
       String str = pair.getValue();
       System.out.println(str);
       pair.setValue("world");
       str = pair.getValue();
       System.out.println(str);

       Pair<Integer> pair2 = new Pair<>(1);
        Integer i = pair2.getValue();
        System.out.println(i);
        pair2.setValue(2);
        i = pair2.getValue();
        System.out.println(i);

    }
}

泛型接口的定义与使用(直到创建对象再确定泛型的类型)

public interface GenericsInteface <T>{
    public void add(T t);
}
class GenericsIntefaceImpl <T>implements GenericsInteface<T>{
    public void add(T t) {
        System.out.println(t);
    }
}

class GenericsTest {
    public static void main(String[] args) {
        GenericsInteface<Integer>gi=new GenericsIntefaceImpl<>();
        gi.add(100);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值