Java Collections.shuffle() weird behaviour [closed]

笑着哭i 提交于 2019-12-23 01:59:03

问题


I am experiencing something weird.

I have a big ArrayList of Long numbers. It contains about 200k numbers in ascending order. These numbers are always distinct; they are not necessarily consecutive, but some groups of them usually are.

I want to extract a sorted sample of 5k from this list, so basically this is my approach:

  • I call java.util.Collections.shuffle(list);
  • I extract the first 5k elements from the now shuffled list
  • I sort the extracted elements in ascending order

My result is somewhat weird, though. Many of my extracted random Longs seem suspiciously close to each other, if not even consecutive. For instance, I got:

...
38414931,
38414932,
38414935,
38414937,
38414938,
38414939,
38414941,
...

This does not definitely look random :/

There is an even stranger thing. While debugging this, I tried to write into files both the initial list and the extracted sample in order to compare them. If I do this, my problem seems to disappear, and my extracted Longs look like proper random numbers.

I have repeated this many times, of course, and every time I did I experienced these two behaviours.

Am I missing something?

EDIT: Here is the code I am using:

List<Long> allNumbers = <getting my list>;

---> if here I write allNumbers into a file, it seems to work fine

Collections.shuffle(allNumbers);
HashSet<Long> randomNumbers = new HashSet<>();
for (int i = 0; i < 5000; i++) {
   randomNumbers.add(allNumbers.get(i));
}

回答1:


Here is a Minimal, Complete, and Verifiable example for you, that outputs some random, increasing numbers, as you expect. Note that my code is the same as yours, except for the input part. So either your problem is in the code you haven't shown yet or the output is fine even if there are sequences of consecutive numbers, which you would expect even with a random distribution.

public static void main(String[] args) {
  List<Long> allNumbers = new ArrayList<>();
  for (long i = 0; i < 2_000; i++) allNumbers.add(i);

  Collections.shuffle(allNumbers);
  Set<Long> randomNumbers = new HashSet<>();

  for (int i = 0; i < 50; i++) randomNumbers.add(allNumbers.get(i));

  randomNumbers.stream().sorted().forEach(n -> System.out.print(n + " "));
}

Example output:

30 149 233 255 301 357 361 391 412 413 423 480 481 ...



来源:https://stackoverflow.com/questions/49154257/java-collections-shuffle-weird-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!