天天看點

Java 選擇題

  1. 執行時候傳回的結果是什麼 ?
List<String> aa = new ArrayList<String>();
        aa.add("F1");
        aa.add("F2");
        aa.add("F3");
        for (String temp : aa) {
            if ("F3".equals(temp)) {
                aa.remove(temp);
            }
        }
         
        for (String temp : aa){
             System.out.println(temp);
        }
           

解答:

Exception in thread "main" java.util.ConcurrentModificationException

在對集合疊代的時候,如果同時對其進行修改就會抛出

java.util.ConcurrentModificationException

異常;

  1. 下面程式的運作結果()
List<String> aa = new ArrayList<String>();
        aa.add("F1");
        aa.add("F2");
        aa.add("F3");
        for (String temp : aa) {
            if ("F3".equals(temp)) {
                aa.remove(temp);
            }
        }
         
        for (String temp : aa){
             System.out.println(temp);
        }

           

Java集合中有一種被稱為fail-fast的錯誤機制,當多線程對集合進行操作時(一個線程使用疊代器周遊集合;另一個線程修改集合内容)會抛出ConcurrentModificationException異常。

就這麼說吧,對于集合的三種周遊方式删除:

1.普通for循環:可以删除

注意每次删除之後索引要–

2.Iterator周遊:可以删除

不過要使用Iterator類中的remove方法,如果用List中的remove方法會報錯

3.增強for循環foreach:不能删除

強制用List中的remove方法會報錯

int