• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

littlesuccess

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

怎样删除一个集合中的对象

问题:

请问下面的那种方法能正确地把字符"B"从集合stringList中删除掉?

1         List<String> stringList = new ArrayList<String>();
2 stringList.add("A");
3 stringList.add("B");
4 stringList.add("C");
5 stringList.add("B");
6 stringList.add("D");
7 stringList.add("E");
8 stringList.add("B");


方法1:

1          for(Iterator<String> it =stringList.iterator(); it.hasNext();){
2 String s = it.next();
3 if (s.equals("B")) stringList.remove(s);
4 }

方法2:

1         for (String s : stringList) {
2 if (s.equals("B")) stringList.remove(s);
3 }

方法3:

1         for (Iterator<String> it = stringList.iterator(); it.hasNext();) {
2 String s = it.next();
3 if(s.equals("B")) it.remove();
4 }

方法4:

1         List<String> newList = new ArrayList<String>();
2 for(String s : stringList){
3 if (!s.equals("B")) newList.add(s);
4 }
5 stringList = newList;

方法5:

1         stringList.remove("B");



答案:方法3和方法4,方法1和2会抛出ConcurrentModificationException,方法5只能删掉第一个"B"字符


posted on 2011-10-19 18:08  littlesuccess  阅读(581)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3