我有一個簡單的問題。我嘗試從容器RandomList中獲取隨機值。它可以和String和int一起工作,但是不能和double一起工作,以及如何解決它?隨機雙列表不顯示隨機變量
謝謝
import java.util.*;
public class RandomList<T> {
private ArrayList<T> storage = new ArrayList<T>();
private Random rand = new Random(47);
public void add(T item) { storage.add(item); }
public T select() {
return storage.get(rand.nextInt(storage.size()));
}
public static void main(String[] args) {
RandomList<String> rs = new RandomList<String>();
RandomList<Integer> rs1 = new RandomList<Integer>();
RandomList<Double> rs2 = new RandomList<Double>();
double w = 1.23;
for(String s: ("The quick brown fox jumped over " +
"the lazy brown dog").split(" "))
rs.add(s);
for(int i = 0; i < 11; i++)
System.out.print(rs.select() + " ");
for (int i = 0; i < 5; i++)
rs1.add(i);
for (int i = 0; i < 5; i++)
System.out.print(rs1.select() + " ");
for (int i = 0; i < 5; i++)
w = (double)i/5;
rs2.add(w);
for (int i = 0; i < 5; i++)
System.out.print(rs2.select() + " ");
}
}
輸出超狐快速快速狗棕色棕色懶棕色3 0 3 1 1 0.8 0.8 0.8 0.8 0.8棕色,所以它適用於字符串和INT,但不會對雙倍(每次相同的值)。