java shuffle shuffle,Java Collections.shuffle()怪异的行为

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 allNumbers = ;

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

Collections.shuffle(allNumbers);

HashSet randomNumbers = new HashSet<>();

for (int i = 0; i < 5000; i++) {

randomNumbers.add(allNumbers.get(i));

}

解决方案

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 allNumbers = new ArrayList<>();

for (long i = 0; i < 2_000; i++) allNumbers.add(i);

Collections.shuffle(allNumbers);

Set 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 ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值