當前位置:首頁 > IT技術(shù) > 編程語言 > 正文

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("三等獎:?現(xiàn)金999元");
????????prizes.addPrizes("優(yōu)秀獎:?代金券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

開通會員,享受整站包年服務立即開通 >