简体   繁体   中英

Removing an item from a list using ListIterator

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 ListIterator documentation you will se that remove :

This call can only be made once per call to next or previous. It can be made only if ListIterator.add has not been called after the last call to next or previous.

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 from List<E> will do the trick:

String c1 = list.remove(rand.nextInt(list.size));

I agree with Jack. In addition you could substitute using the Random class by calling Collections.shuffle(list) . As the name implies it will randomize your list for you. Using your listIterator you can then iterate through the list and pick your cards, storing them in another list. It would look something like:

List<String> list = new ArrayList<String>();
list.add("card1");
list.add("card2");
list.add("card3");

Collections.shuffle(list);

ListIterator<String> listIterator = list.listIterator();
List<String> pickedCards = new ArrayList<String>();

while(listIterator.hasNext()) {
    pickedCards.add(listIterator.next());
}

String c1 = pickedCards.get(0);
String c2 = pickedCards.get(1);
String c3 = pickedCards.get(2);

The values of c1, c2, and c3 would now be something like "card2" , "card1" , and "card3"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM