开发者社区> 问答> 正文

如何用随机不可变值填充数组?

private void create(){
    byte[] arr = new byte[20];
    new Random().nextBytes(arr);
}

始终生成随机值。

如何创建不可变的随机值?

问题来源:Stack Overflow

展开
收起
montos 2020-03-26 22:43:07 391 0
1 条回答
写回答
取消 提交回答
  • 您需要种子值才能返回相同的字节集。

    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

    2020-03-26 22:43:39
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载