首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >list.removeAll()问题

list.removeAll()问题
EN

Stack Overflow用户
提问于 2013-10-30 11:08:48
回答 2查看 114关注 0票数 0

我使用数组查找两个字符串(即str2str3 )之间的差异。当我使用下面的代码时,它完美地工作,并返回预期的输出。但当我取代

代码语言:javascript
复制
str2 = #19, 6th cross, 7th main road, townname, cityname-560036
str3 = #19, 6th cross, 17th main road, townname, cityname-560036  

预期的输出应该是: al1: 1的内容

但是我得到的输出是: al1:[]的内容

有人能解释我哪里出了问题吗?

提前谢谢。

下面是我的doPost方法:

代码语言:javascript
复制
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
            str2="Hello";
    str3="Hallo";
    System.out.println("-------");
    System.out.println("This is first string:"+""+str2);
    System.out.println("This is second string:"+""+str3);


    ArrayList al = new ArrayList();
    ArrayList al1=new ArrayList(); 

      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      for (int i = 0;i < str2.length(); i++)
        {
            al.add(str2.charAt(i));
        }
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);



      for (int i = 0;i < str3.length(); i++)
        {
            al1.add(str3.charAt(i));
        }

      System.out.println("Contents of al1: " + al1);

      System.out.println("Size of al1 after additions: " + al1.size());
        boolean hg=al1.removeAll(al);
        System.out.println("Remove All:"+hg);


      System.out.println("Contents of al: " + al);
      System.out.println("Contents of al1: " + al1);

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-30 11:31:16

要解决问题,请使用String .split()方法

代码语言:javascript
复制
str2 = #19, 6th cross, 7th main road, townname, cityname-560036
str3 = #19, 6th cross, 17th main road, townname, cityname-560036

String[] s2 = str2.split(",");
String[] s3 = str3.split(",");

for (int i = 0; i < s2.length; i++) {
    al.add(s2[i]);
}

for (int i = 0; i < s3.length; i++) {
    al1.add(s2[i]);
}

al.retainAll(al1);

System.out.println("Size of a1 is " + a1.size());

而且,我认为你想要的是retainAll(),而不是removeAll()retainAll()是返回boolean,而不是removeAll()

票数 1
EN

Stack Overflow用户

发布于 2013-10-30 11:36:53

从我看到的地方:看起来您需要比较用逗号分隔的标记。创建strs的字符串列表(按',‘拆分),然后您可以删除类似的字符串,剩余的字符串可以比较不同。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19680572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档