A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

@iRen盾

中级黑马

  • 黑马币:

  • 帖子:

  • 精华:

* 一个ArrayList对象aList中存有若干个字符串元素,
*  现欲遍历该ArrayList对象,删除其中所有值为"abc"的字符串元素,
*  请用代码实现。
public class Demo17 {
   public static void main(String[] args) {
      ArrayList<String> al = new ArrayList<String>();
      String s = "abc"; //需要删除的指定字符串
      al.add("abcd");
      al.add("abc");
      al.add("abcded");
      al.add("abcdabc");
      ArrayList<String> newList = remove(al,s);  
      System.out.println(newList);
   }

   public static ArrayList<String> remove(ArrayList<String> al, String s) {
      for(int x = 0; x < al.size(); x ++)
      {
         if(al.get(x).equals(s))
         {
            al.remove(al.get(x));
         }
      }
      return al; //返回需要的集合
   }
}

2 个回复

倒序浏览
角标有问题,一移除后角标就变了~
for(int x = 0; x < al.size(); x ++)
这个改为:
for(int x = al.size()-1; x >=0; x --)
回复 使用道具 举报
同意楼上的
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马