循環list移除元素-java.lang.UnsupportedOperationException
場景:
在一個codeList
列表中移除指定的元素
常規for循環(根據list下標刪除)
用for循環, 根據循環cursor
來移除在List
指定位置的元素
private boolean removeList(List<String> codeList, String code) {
for (int i = 0; i < codeList.size(); i++) {
String codeFromList = codeList.get(i);
if (StringUtils.equalsAnyIgnoreCase(codeFromList, code)) {
codeList.remove(i);
return true;
}
}
return false;
}
foreach循環(根據元素對象刪除)
在foreach循環中, 根據當前對象來刪除, 如果有多個則刪除第一個(
remove(object)
的實現最終也是通過傳入的object
取得第一個匹配元素的下標, 所以理論上remove
行爲直接根據下標刪除元素性能更好
private boolean removeList(List<String> codeList, String code) {
for (String codeFromList : codeList) {
if (StringUtils.equalsAnyIgnoreCase(codeFromList, code)) {
boolean remove = codeList.remove(code);
return remove;
}
}
return false;
}
迭代器循環刪除元素
利用迭代器的能力來刪除指定的元素(注意: 不要在另外的線程修改原List
)
private boolean removeList(List<String> codeList, String code) {
Iterator<String> iterator = codeList.iterator();
if (iterator.hasNext()) {
String next = iterator.next();
if (StringUtils.equalsAnyIgnoreCase(next, code)) {
iterator.remove();
return true;
}
}
return false;
}
異常分析與解決
異常定位
我使用發現前面3個方法都報java.lang.UnsupportedOperationException
異常…
原來我的List
是使用Arrays.asList()
方法構造出來的…
Arrays.asList()
返回的List
是個普通的List
沒有實現remove
方法…
解決方案
將List
轉成ArrayList
即可
List<String> codeList = new ArrayList<>(Arrays.asList(questionPartEnum.codeList))
ArrayList
中實現了remove
, 所以可以直接使用了