0

In java I have this function:

public List<String> seperatekeys(String text) {
    String[] keys = text.split("and");
    List<String> words = Arrays.asList(keys);

    ListIterator<String> iter = words.listIterator();
    while (iter.hasNext()) {
        String currentWord = iter.next().trim();
        if (currentWord.equals("")) {
            iter.remove();
        } else {
            iter.set(currentWord);
        }
    }

    return words;
}

But when I do a remove(), it crashes saying unsupportedoperationerror.

Anyone know how to fix it?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

5

The issue is that Arrays#asList() returns an ArrayList implementation that inherits remove() from AbstractList. The implementation of remove() in AbstractList is this:

public E remove(int index) {
    throw new UnsupportedOperationException();
}

And because the iterator uses the list's iterator to perform its remove() method, you end up with the exception.

You have a few solutions here. You can either pass the result of Arrays#asList() to an ArrayList constructor:

List<String> words = new ArrayList<>(Arrays.asList(keys));

Now, you can iterate over the resulting List and remove the elements you want.

Or, asMadProgrammer stated, you can take the opposite approach and iterate over the array and add the elements you want to keep:

List<String> words = new ArrayList<>();
for (String s : keys) {
    String currentWord = s.trim();
    if (!currentWord.equals("")) {
        words.add(currentWord);
    }
}
awksp
  • 11,764
  • 4
  • 37
  • 44