Java泛型的三种常用方式

Java泛型(generics)是JDK 5中引入的一个新特性,泛型提供了编译时类型安全监测机制。

 

方式一:泛型类

一个泛型类(generic class)就是具有一个或多个类型变量的类。

1、一个类型变量

/*
 * 泛型类
 * Java库中 E表示集合的元素类型,K 和 V分别表示表的关键字与值的类型
 * T(需要时还可以用临近的字母 U 和 S)表示“任意类型”
 */
public class Pair<T> {
    
    private T name;
    private T price;

    public Pair() {
    }

    public Pair(T name, T price) {
        this.name = name;
        this.price = price;
    }

    public T getName() {
        return name;
    }

    public void setName(T name) {
        this.name = name;
    }

    public T getPrice() {
        return price;
    }

    public void setPrice(T price) {
        this.price = price;
    }
}

2、多个类型变量

public class Pair<T,U> { ... }

 

类方法中的类型变量指定方法的返回类型以及域和局部变量的类型。例如:

private T first; //uses the type variable

用具体的类型替换类型变量就可以实例化泛型类型,例如:

Pair<String>

  

方式二:泛型接口

public interface Generator<T> {

    public T next();

}

继承接口:

public class FruitGenerator implements Generator<String> {

    @Override
    public String next() {
        return "Fruit";
    }

}

也可以这样:  

public class FruitGenerator<T> implements Generator<T> {

    private T next;

    public FruitGenerator(T next) {
        this.next = next;
    }

    @Override
    public T next() {
        return next;
    }

    public static void main(String[] args){
        FruitGenerator<String> fruit = new FruitGenerator<>("Fruit");
        System.out.println(fruit.next);
    }

}

 

方式三:泛型方法

public class ArrayAlg {

    public static <T> T getMiddle(T... a) {
        return a[a.length / 2];
    }
    
    public static void main(String[] args){
        System.out.println(ArrayAlg.getMiddle(1,2,3,4,5));
    }
}

  

  

  

  

 

posted @ 2023-03-06 00:08  N!CE波  阅读(200)  评论(0编辑  收藏  举报