正如标题所解释的,我希望生成一系列随机空值。因为没有 Random.nextShort() 函数,所以做我想做的最简单的方法似乎是将整数转换为短整数,使用:
Random rand = new Random(int seed);
(short) rand.nextInt()
但是,我不完全理解这种转换是如何发生的,因此我不能确定生成的 short 值是否仍然是随机的。是这样吗?提前致谢。
最佳答案
int 的短类型转换通过按位截断工作。只要整数是随机分布的,short 值也应该是 - 是的。
来自 Java 语言规范 5.1.3 :
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.
int
有 32 位,short
有 16 位。本质上,转换与添加(或减去)65536(即 2 的 16 次方)相同,直到该值在 short
可表示的范围内。因此,正好有 65536 个 int
值映射到每个可能的 short
值。
关于java - 将随机整数转换为 short 会给出均匀分布吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37922338/