且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

生成2个数字之间的唯一的随机数

更新时间:2023-02-10 12:10:06

生成编号从1到120的整个列表随机播放列表。就拿第一个元素(和删除)

Generate the whole list of numbers from 1 to 120. Shuffle the list. Take the first element (and remove it)

List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 120; i++) {
    list.add(i)
}
Collections.shuffle(list);
...
int random = list.remove(0);
...
int otherRandom = list.remove(0);

为您在你用完了数字的情况下,list.empty()。如果为空,再创建列表,并将它洗。

Check for list.empty() in case you run out of numbers. If empty, create the list again and shuffle it.