I want to remove an element from the ArrayList
whose length is equal to the number passed as an integer. My code is as follows. When run, the programs throws UnsupportedOperationException
in the line when remove()
method is used. Actually, it is a codingbat problem.
public static List<String> wordsWithoutList(String[] words, int len) {
List<String> list = new ArrayList<String>();
list = Arrays.asList(words);
for(String str : list) {
if(str.length() == len) {
list.remove(str);
}
}
return l;
}
The list returned by asList
isn't an ArrayList
-- it doesn't support modification.
You need to do
public static List<String> wordsWithoutList(String[] words, int len) {
List<String> l = new ArrayList<String>( Arrays.asList(words) );
for( Iterator<String> iter = l.iterator(); iter.hasNext(); ){
String str = iter.next();
if(str.length()==len){
iter.remove();
}
}
return l;
}
So two things:
asList
using the ArrayList
constructor.remove
to avoid a ConcurrentModificationException
.It was pointed out that this can be inefficient, so a nicer alternative is:
List<String> l = new ArrayList<String>(str.length());
// ^^ initial capacity optional
for( String str : words )
if( str.length()!=len)
l.add(str);
return l;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With