面試題目一:請問如下代碼輸出結(jié)果是什么本姥?
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("helloworld");
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
}
答案:會輸出[world]慨灭。該題目考察的是集合底層是數(shù)組围段,對于集合的remove操作绳匀,底層是將被刪除元素之后的所有元素往前移動一個位置梧却。
面試題目二:問如下程序能否正常執(zhí)行奇颠?并說明為什么?
public class IteratorTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("helloworld");
for (Iterator<String> ite = list.iterator(); ite.hasNext();) {
String next = ite.next();
list.remove(next);
}
}
}
答案:該程序執(zhí)行后會拋出ConcurrentModificationException放航,當(dāng)使用迭代器對ArrayList進(jìn)行迭代的時候烈拒,不能在迭代中使用list.remove方法來刪除元素,否則會拋出ConcurrentModificationException異常。本質(zhì)原因是當(dāng)調(diào)用ite.iterator()
方法后荆几,會生成一個Iterator接口的實(shí)例對象吓妆,該對象內(nèi)部維護(hù)一個變量ExpectedModCount
,該變量的初始值是集合的modCount吨铸,在迭代進(jìn)行中使用集合的remove方法的時候會導(dǎo)致modCount值+1而ExpectedModCount還是原先的值行拢,調(diào)用ite.next()
方法內(nèi)部會對ExpectedModCount
與modCount
進(jìn)行比較操作,如果不等就會拋出ConcurrentModficationException诞吱。
面試題目三:如下程序能否正常執(zhí)行
public class IteratorTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("helloworld");
for (Iterator<String> ite = list.iterator(); ite.hasNext();) {
String next = ite.next();
ite.remove(); //關(guān)鍵看此處
}
System.out.println(list.size());
}
}
答案:能夠正常執(zhí)行舟奠, 在迭代過程中雖然不能使用集合ArrayList的remove操作或者add操作(會致使modCount改變的操作),但是使用迭代器自帶的remove方法是可以的房维,ite.remove
內(nèi)部會對ExceptedModCount
的值進(jìn)行修正沼瘫,所以在調(diào)用ite.next()
方法的時候,ExceptedModCount == ModCount
的判斷結(jié)果為true咙俩,故不會導(dǎo)致拋出ConCurrentModificationException
總結(jié):
- 不使用迭代器對ArrayList進(jìn)行迭代的時候耿戚,可以使用remove等操作,原因是ArrayList并沒有對modCount進(jìn)行判斷
- 使用迭代器對ArrayList進(jìn)行迭代的時候阿趁,不能使用ArrayList的remove等會致使modCount改變的操作膜蛔,否則在調(diào)用迭代器的
next
方法時會拋出ConcurrentModificationException
- 使用迭代器對ArrayList進(jìn)行迭代的時候,可以使用迭代器自帶的remove操作脖阵,因為Iterator中的remove方法會對
ExpectedModCount
的值進(jìn)行修正皂股,在調(diào)用迭代器的next
方法時ExpectedModCount
與modCount
的比較結(jié)果為true,故不會導(dǎo)致拋出ConcurrentModificationException
異常命黔。