I have an ArrayList that contains numbers (1-50). Now I want to generate random numbers from this ArrayList (each random number must be an item from the ArrayList) and once that item is picked, it will be remove from the ArrayList.
This is what I have tried but the Random object keeps generating numbers that are not in the ArrayList
Random rnd = new Random();
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
while (list2.size() < 50) {
int index = list1.get(rnd.nextInt(list1.size()));
list2.add(index);
list1.remove(index);
}
The above code keeps generating random numbers that are not in the list1 object.
I need only numbers that are in list1 to be generated.
list1.rnd.nextInt()you have there should be returning you a number between 0 and 49. That being said, yourlist1.remove()may be removing the wrong number. In this case, if your random number was 29, you'd be adding a 30 to list2 (because that's what's at index 29 of list1) but removing the 31 from list1 (because that's what's at index 30, which is whatindexis set to now)