我想删除一个元素,ArrayList其长度等于作为整数传递的数字.我的代码如下.运行时,程序UnsupportedOperationException在remove()使用方法时会抛出该行.实际上,这是一个编码问题.
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)
| 归档时间: |
|
| 查看次数: |
849 次 |
| 最近记录: |