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

Allways generate random values.

How to create immutable random values?

IMBABOT
  • 121
  • 2
  • 12
  • 1
    Does this answer your question? [Immutable array in Java](https://stackoverflow.com/questions/3700971/immutable-array-in-java) – 3x071c Mar 13 '20 at 17:55

2 Answers2

1

You need a seed value in order to return the same set of bytes.

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);
    }
}

A sample run:

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]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

We have generated the random numbers in the array of bytes. If we want to make it immutable we can pack the generated byte array into unmodifiable list as shown below.

   private List<Integer> create(int capacity){
      byte[] arr = new byte[capacity];
      Random random = new Random();
      random.nextBytes(arr);
      List<Integer> randNumbers = new ArrayList<>(capacity);
      for(int i = 0 ; i < arr.length ; i ++){
        randNumbers.add(Integer.valueOf(arr[i]));
      }
      return Collections.unmodifiableList(randNumbers);
  }

  // Called with size 20
  List<Integer> immutableList = create(20);
Ravi Sharma
  • 160
  • 4