如何在Java';这是下一个很长的时间

如何在Java';这是下一个很长的时间,java,random,Java,Random,在Java中,我希望在一个排他上界内生成一个随机选取的长数 通常,如果它是一个Int,我可以这样做 int nextInt = new SecureRandom.nextInt(500); 为什么我不能也这样做 long nextLong = new SecureRandom.nextLong(4294967296L); 有办法解决这个问题吗 可能要感谢您,作为解决方法,您可以使用Java8中引入的方法。因此,如果需要获取范围[minLong,maxLong]中的SecureRandomlo

在Java中,我希望在一个排他上界内生成一个随机选取的长数

通常,如果它是一个
Int
,我可以这样做

int nextInt = new SecureRandom.nextInt(500);
为什么我不能也这样做

long nextLong = new SecureRandom.nextLong(4294967296L);
有办法解决这个问题吗


可能要感谢您,作为解决方法,您可以使用Java8中引入的方法。因此,如果需要获取范围
[minLong,maxLong]
中的
SecureRandom
long值,一种方法是:

long minLong = -1L;
long maxLong = 4294967296L;

long boundedLong = 
     new SecureRandom()
        .longs(minLong, maxLong + 1)
        .findFirst()
        .getAsLong();


它必须是安全随机的吗

如果没有,那么您有两个简单的选项,使用
nextLong​(长装订)
属于或:


更新

如果必须是
SecureRandom
,则始终可以复制这两种方法的代码,这两种方法的实现方式相同(下面是从Java 11复制的):

public static long nextLong(SecureRandom,long-bound){
如果(绑定>>1;
u+m-(r=u%结合)<0L;
u=random.nextLong()>>>1)
;
}
返回r;
}

这应该可以回答问题“是否有解决方法?”,因为编写自己的代码是一种有效的解决方法。

Java的可能重复:0中的随机长数也:重复问题的公认答案无效,但第二个答案无效(Java:random long number in 0感谢您的所有输入。但是,我对加密安全的方法更感兴趣。我认为
ThreadLocalRandom
不是加密安全的。如果我错了,请纠正我。@Tom如评论所说,该版本不是统一分发的。如果您想要安全,您肯定想要统一。Wh如果
SecureRandom
API已经有了绑定版本,我就不必麻烦复制方法实现了,如?有关详细信息,请参见下文。@Zgurskyi,因为您已经给出了答案,所以我提供了使用流的替代方案。
long nextLong = new SplittableRandom().nextLong(4294967296L);

long nextLong = ThreadLocalRandom.current().nextLong(4294967296L);
public static long nextLong(SecureRandom random, long bound) {
    if (bound <= 0)
        throw new IllegalArgumentException(BadBound);
    long r = random.nextLong();
    long m = bound - 1;
    if ((bound & m) == 0L) // power of two
        r &= m;
    else { // reject over-represented candidates
        for (long u = r >>> 1;
             u + m - (r = u % bound) < 0L;
             u = random.nextLong() >>> 1)
            ;
    }
    return r;
}