怎么理解Java泛型?

76 阅读1分钟

1 泛型概念

泛型的本质是类型参数化,允许在定义类、接口或方法时使用类型参数,在实例化或者调用的时候在指定具体的类型。

e.g. List接口的使用,实例化时指定具体类型即可。

List<Integer> numList = new ArrayList<>();

2 泛型语法

class myClass<类型参数T> {
    T data;
}

3 泛型实践

以简单的抽奖动作为例。

步骤1:创建奖品实体类

@Data
@Builder
@AllArgsConstructor  
@NoArgsConstructor
public class Prize {
    private String id;  // 奖品ID
    private String name; // 奖品名称
}

步骤2:实现泛型抽奖箱

public class LotteryBox<T> { 
    private List<T> prizes = new ArrayList<>();
    private Random random = new Random();

    // 添加奖品
    public void addPrize(T prize) {
        if (prize == null) {
            throw new IllegalArgumentException("奖品不能为null");
        }
        prizes.add(prize);
    }

    // 执行抽奖
    public T performLottery() throws IllegalStateException {
        if (prizes.isEmpty()) {
            throw new IllegalStateException("奖品池已空");
        }
        return prizes.get(random.nextInt(prizes.size()));
    }
}

步骤3:主程序

public class Lottery {
    public static void main(String[] args) {
        // 1. 创建奖品池
        LotteryBox<Prize> prizeBox = new LotteryBox<>();
        
        // 2. 添加奖品
        prizeBox.addPrize(new Prize("P001", "一等奖:oppoA5"));
        prizeBox.addPrize(new Prize("P002", "二等奖:京东购物卡"));
        prizeBox.addPrize(new Prize("P003", "三等奖:再来一次"));

        try {
            // 3. 执行三次抽奖
            System.out.println("=== 抽奖结果 ===");
            for (int i = 0; i < 3; i++) {
                Prize wonPrize = prizeBox.performLottery();
                System.out.println((i+1) + ". 抽中: " + wonPrize);
            }
        } catch (IllegalStateException e) {
            System.err.println("抽奖失败: " + e.getMessage());
        }
    }
}