1st Way: -
You can also maintain a List of all the numbers. Then use Collections.shuffle to shuffle the list and get the first element. And remove it.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(4);
list.add(2);
list.add(3);
System.out.println("Original List: " + list);
Collections.shuffle(list);
System.out.println("Shuffled List: " + list);
int number1 = list.remove(0); // Remove the first value
System.out.println("Number removed: " + number1);
Collections.shuffle(list);
System.out.println("Shuffled List: " + list);
number1 = list.remove(0);
System.out.println("Number removed: " + number1);
OUTPUT: -
Original List: [1, 4, 2, 3]
Shuffled List: [4, 3, 1, 2]
Number removed: 4
Shuffled List: [1, 3, 2]
Number removed: 1
2nd Way: -
A better way would be to generate a random number from 0 to the size of the list, and get the value of that index and remove it.
int size = list.size();
Random random = new Random();
for (int i = 0; i < size; i++) {
int index = random.nextInt(list.size());
int number1 = list.remove(index);
System.out.println(number1);
}
NOTE: -
If you want to exclude a fixed set of numbers from being generated, then you can have those numbers in a list. And then remove all elements of that list from your list of numbers. And then use any of the approach above.
Random.nextInt(10)==4generate again4several times before anything else.