从ArrayList中删除对象

h-r*_*rai 4 java arraylist

我想删除一个元素,ArrayList其长度等于作为整数传递的数字.我的代码如下.运行时,程序UnsupportedOperationExceptionremove()使用方法时会抛出该行.实际上,这是一个编码问题.

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;       
}
Run Code Online (Sandbox Code Playgroud)

tru*_*ity 10

返回的列表asList不是ArrayList- 它不支持修改.

你需要这样做

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;       
}
Run Code Online (Sandbox Code Playgroud)

所以有两件事:

  • asList使用ArrayList构造函数创建返回的数组的可修改副本.
  • 使用迭代器remove来避免使用ConcurrentModificationException.

有人指出,这可能效率低下,因此更好的选择是:

List<String> l = new ArrayList<String>(str.length());
                                   //  ^^ initial capacity optional
for( String str : words )
    if( str.length()!=len)
        l.add(str);

return l;
Run Code Online (Sandbox Code Playgroud)

  • 我认为创建新列表并向其添加项目更清晰. (2认同)