How to remove and set from List<String> in java? -
in java have 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 remove(), crashes saying unsupportedoperationerror.
anyone know how fix it?
thanks
the issue arrays#aslist() returns arraylist implementation inherits remove() abstractlist. implementation of remove() in abstractlist this:
public e remove(int index) { throw new unsupportedoperationexception(); } and because iterator uses list's iterator perform remove() method, end exception.
you have few solutions here. can either pass result of arrays#aslist() arraylist constructor:
list<string> words = new arraylist<>(arrays.aslist(keys)); now, can iterate on resulting list , remove elements want.
or, asmadprogrammer stated, can take opposite approach , iterate on array , add elements want keep:
list<string> words = new arraylist<>(); (string s : keys) { string currentword = s.trim(); if (!currentword.equals("")) { words.add(currentword); } }
Comments
Post a Comment