IMBABOT :
private void create(){
byte[] arr = new byte[20];
new Random().nextBytes(arr);
}
Allways generate random values.
How to create immutable random values?
Arvind Kumar Avinash :
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]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=237300&siteId=1