这是我第一次问这个问题.
我想用0到9的10个唯一的int数字制作ArrayList.我接下来的步骤:
我的代码:
public static void main(String[] args) {
Random rd = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
int q = rd.nextInt(10);
list.add(q);
while (true) {
int a = rd.nextInt(10);
for (int b=0;b<list.size();b++){
if (a == list.get(b)) break;
else list.add(a);
}
if (list.size() == 10) break;
}
System.out.println(list);
}
Run Code Online (Sandbox Code Playgroud)
但我在控制台看到的只是无休止的过程.
问题是 - 是否有另一种方法可以使ArrayList具有10个唯一数字(0到9)?
rge*_*man 11
使用数字Collections.shuffle初始化后使用ArrayList.
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
{
list.add(i);
}
Collections.shuffle(list);
Run Code Online (Sandbox Code Playgroud)
因为这将在线性时间运行ArrayList的RandomAccess.