嘗試使用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
循環是必要的。
嘖嘖,我不記得今天已經看到這個問題了,現在已經接近午夜了!新紀錄! –