private void create(){
byte[] arr = new byte[20];
new Random().nextBytes(arr);
}
始终生成随机值。
如何创建不可变的随机值?
问题来源:Stack Overflow
您需要种子值才能返回相同的字节集。
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
byte[] arr = new byte[20];
// Generating a random seed for demo. You can assign a fixed value e.g. 1 to seed.
int seed = new Random().nextInt();
System.out.println("Going to print the byte array 10 times for the seed " + seed);
for (int i = 1; i <= 10; i++) {
create(arr, seed);
System.out.println(Arrays.toString(arr));
}
}
private static void create(byte[] arr, int seed) {
Random random = new Random(seed);
random.nextBytes(arr);
}
}
运行示例:
Going to print the byte array 10 times for the seed -932843232
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
[74, 4, -46, -54, 49, 14, 32, -61, 20, -5, 1, 49, -64, -98, 68, 2, -74, 56, 28, -31]
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。