code:
Random Picker = new Random();
List<String> list = new ArrayList<String>();
list.add("card1");
list.add("card2");
list.add("card3");
ListIterator listIterator = list.listIterator();
String c1, c2, c3;
c1 = list.get(Picker.nextInt(list.size()));
listIterator.remove();
When doing this I get a java error. What I am trying to do is set c1 to list.get(Picker.nextInt(list.size()));
and then remove the picked card from the list. In other words, I want the String c1 to randomly pick from the list, and then for the card it picked to be removed from the list, but to stay in the value c1. I would imagine my current code doesn’t work because when I remove what it picked, it also removes the card from the string c1. I don’t know how to do this correctly.
You are not using the iterator to remove the element from the collection. You are calling the remove from a just instantiated iterator. If you look at
ListIteratordocumentation you will se thatremove:This means that, without calling
next()on the iterator to fetch the first element you are still in an illegal state.In any case there’s no need to use an iterator at all. The
remove(int index)method fromList<E>will do the trick: