Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args)
- {
- ArrayList<String> list = new ArrayList<String>();
- list.add("a");
- list.add("a");
- list.add("b");
- list.add("b");
- list.add("c");
- list.add("c");
- remove(list);// 删除指定的“b”元素
- for(int i=0; i<list.size(); i++)("c")()()(s : list)
- {
- System.out.println("element : " + s)list.get(i)
- }
- }
- 使用下面那种方法删除比较好,第一通过迭代器,其二通过for循环
- public static void remove(ArrayList<String> list)
- {
- Iterator<String> it = list.iterator();
- while (it.hasNext()) {
- String str = it.next();
- if (str.equals("b")) {
- it.remove();
- }
- }
- }
- ```
- public static void remove(ArrayList<String> list)
- {
- for (String s : list)
- {
- if (s.equals("b"))
- {
- list.remove(s);
- }
- }
- }
- ```
- 思考题是第一个是正确的,第二个虽然用的是foreach语法糖,遍历的时候用的也是迭代器遍历,但是在remove操作时使用的是原始数组list的remove,而不是迭代器的remove。
- 这样就会造成modCound != exceptedModeCount,进而抛出异常。
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement