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