Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an object from an ArrayList

Tags:

java

arraylist

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;       
}
like image 220
h-rai Avatar asked Dec 27 '22 02:12

h-rai


1 Answers

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:

  • Make a modifiable copy of the array returned by asList using the ArrayList constructor.
  • Use the iterator's 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;
like image 50
trutheality Avatar answered Dec 29 '22 16:12

trutheality