我正在編寫一個程序,在其中創建一個ArrayList,并且我想使用迭代器遍歷列表:ArrayList<Person> flightAttendants = new ArrayList<Person>();Iterator<Person> itr = flightAttendants.iterator();這是我嘗試遍歷數組列表元素的方式:我也定義了一個toString方法:while(itr.hasNext()){ System.out.println(itr.next());}public String toString(){ System.out.println("name of the passenger : "+name); System.out.println("Age of the passenger : "+age); System.out.println("Seat number of the passenger : "+seatNumber); return "\n"; }每當我嘗試運行它時,它都會給我錯誤:java.util.ConcurrentModificationException這里的錯誤在哪里?
1 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
您提供的代碼應該可以正常工作,因為我已經嘗試過了。除非您表明您的代碼正在處理其他事情,否則我們無法進一步嘗試解決。我建議你檢查問題Iterators 和 concurrentmodificationexception也為了更好地理解你的代碼可能在某個地方陷入了那里提到的錯誤。
正如 Andrew 所提到的,將迭代器帶入您的 while 循環中,現在檢查工作正常。我嘗試過這個。
添加回答
舉報
0/150
提交
取消