Java 遍歷Map時 刪除元素
來源:易賢網(wǎng) 閱讀:3627 次 日期:2014-09-05 10:41:54
溫馨提示:易賢網(wǎng)小編為您整理了“Java 遍歷Map時 刪除元素”,方便廣大網(wǎng)友查閱!
* 會引發(fā) 并發(fā)修改異常,可以通過迭代器的remove():

* 從迭代器指向的 collection 中移除當前迭代元素

* 來達到刪除訪問中的元素的目的。

* */

public static void main(String[] args) {

map.put(1,"one");

map.put(2,"two");

map.put(3,"three");

map.put(4,"four");

map.put(5,"five");

map.put(6,"six");

map.put(7,"seven");

map.put(8,"eight");

map.put(5,"five");

map.put(9,"nine");

map.put(10,"ten");

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while(it.hasNext()){

Map.Entry<Integer, String> entry=it.next();

int key=entry.getKey();

if(key%2==1){

System.out.println("delete this: "+key+" = "+key);

//map.put(key, "奇數(shù)"); //ConcurrentModificationException

//map.remove(key); //ConcurrentModificationException

it.remove(); //OK

}

}

//遍歷當前的map;這種新的for循環(huán)無法修改map內(nèi)容,因為不通過迭代器。

System.out.println("-------nt最終的map的元素遍歷:");

for(Map.Entry<Integer, String> entry:map.entrySet()){

int k=entry.getKey();

String v=entry.getValue();

System.out.println(k+" = "+v);

}

}

}

更多信息請查看IT技術專欄

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:Java 遍歷Map時 刪除元素

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網(wǎng)