尝试使用LinkedHashSet<Integer>
(请参阅documentation)。
定期中存储一组Integer
小号有效地:将一个新的号码,并检查一个数是否已经存在在一定时间(在阵列中存储的号码时,如你所提到的,这些查找采取线性的时间内完成去检查)。现在
,因为你说你要号码的列表,我们使用具有普通的所有属性LinkedHashSet<Integer>
,也garantees,如果您遍历所有的元素,你总是会通过他们在同一个迭代订购。
的代码会是这个样子:
Set<Integer> randomNumberList = new LinkedHashSet<Integer>();
int r;
// Make sure the number is not present in the list, and then add it:
do {
r = ... // Generate your next random number
} while(randomNumberList.contains(r));
// At this point, we know r is not in the list, so add it:
randomNumberList.add(r);
// Do the previous as many times as you want.
// Now, to iterate over the list:
for(Integer number : randomNumberList) {
// Do something...
}
注意,do
- 如果你想确保你实际上是一个号码添加到列表中while
循环是必要的。
啧啧,我不记得今天已经看到这个问题了,现在已经接近午夜了!新纪录! –