Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. public static void main(String[] args)
  2. {
  3. ArrayList<String> list = new ArrayList<String>();
  4. list.add("a");
  5. list.add("a");
  6. list.add("b");
  7. list.add("b");
  8. list.add("c");
  9. list.add("c");
  10. remove(list);// 删除指定的“b”元素
  11.  
  12. for(int i=0; i<list.size(); i++)("c")()()(s : list)
  13. {
  14. System.out.println("element : " + s)list.get(i)
  15. }
  16. }
  17.  
  18.  
  19. 使用下面那种方法删除比较好,第一通过迭代器,其二通过for循环
  20. public static void remove(ArrayList<String> list)
  21. {
  22. Iterator<String> it = list.iterator();
  23.  
  24. while (it.hasNext()) {
  25. String str = it.next();
  26.  
  27. if (str.equals("b")) {
  28. it.remove();
  29. }
  30. }
  31.  
  32. }
  33.  
  34.  
  35. ```
  36. public static void remove(ArrayList<String> list)
  37. {
  38. for (String s : list)
  39. {
  40. if (s.equals("b"))
  41. {
  42. list.remove(s);
  43. }
  44. }
  45. }
  46.  
  47. ```
  48.  
  49. 思考题是第一个是正确的,第二个虽然用的是foreach语法糖,遍历的时候用的也是迭代器遍历,但是在remove操作时使用的是原始数组list的remove,而不是迭代器的remove。
  50. 这样就会造成modCound != exceptedModeCount,进而抛出异常。
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement