Java - 自定義泛型的使用 - 抽獎小例子
2022-05-31 17:21:52

Main:

public?class?Main?{

????public?static?void?main(String[]?args)?{
????????Prizes<String>?prizes?=?new?Prizes<>();
????????prizes.addPrizes("一等獎:?榮耀40S手機?一部");
????????prizes.addPrizes("二等獎:?小米掃地機?一部");
????????prizes.addPrizes("三等獎:?現金999元");
????????prizes.addPrizes("優秀獎:?代金券66元?×?5張");
???????//?prizes.addPrizes(123);??//報錯?因為上面已定義String?泛型

????????System.out.println(prizes.getPrizes());?//抽獎
????}
}

Prizes

import?java.util.ArrayList;
import?java.util.List;
import?java.util.Random;

public?class?Prizes<T>?{

????List<T>?list_prizes?=?new?ArrayList<>();
????public?void?addPrizes(T?prizes){
????list_prizes.add(prizes);
????}
????public?T?getPrizes(){
????????Random?random?=?new?Random();
????????return?list_prizes.get(random.nextInt(list_prizes.size()));
????}

}

就是一個簡單的泛型限制?


作者:??咸瑜??


本文摘自 :https://blog.51cto.com/u


更多科技新聞 ......

欧美五月丁香六月综合合_成年在线视频免费观看完整版_交换国产精品视频一区_免费一本色道久久一区