item 28) 배열보다 리스트를 사용하라
배열과 제네릭 타입의 차이
Object[] stringArray = new String[3];
stringArray[1]= 251;리스트와 제네릭 사용
List<Object> stringList = new ArrayList<Long>();제네릭을 사용해야 하는 예시
Last updated
Object[] stringArray = new String[3];
stringArray[1]= 251;List<Object> stringList = new ArrayList<Long>();Last updated
public class Chooser {
private final Object[] choiceArray;
public Chooser(Collection choices) {
choiceArray = choices.toArray();
}
public Object choose() {
Random rnd = ThreadLocalRandom.current();
return choiceArray[rnd.nextInt(choiceArray.length)];
}
}public class Chooser<T> {
private final List<T> choiceList;
public Chooser(Collection<T> choices) {
choiceList = new ArrayList<>(choices);
}
public T choose() {
Random rnd = ThreadLocalRandom.current();
return choiceList.get(rnd.nextInt(choiceList.size()));
}
public static void main(String[] args) {
List<Integer> intList = List.of(1, 2, 3, 4, 5, 6);
Chooser<Integer> chooser = new Chooser<>(intList);
for (int i = 0; i < 10; i++) {
Number choice = chooser.choose();
System.out.println(choice);
}
}
}