我正在使用arraylists来查找两个字符串之间的差异,即str2
和str3
。
当我使用下面的代码时,它完美地工作并返回预期的输出。
但当我更换
str2 = #19, 6th cross, 7th main road, townname, cityname-560036
str3 = #19, 6th cross, 17th main road, townname, cityname-560036
预期输出应为:al1的内容:[1]
但我获得的输出是:al1的内容:[]
有谁可以解释我哪里出错?
提前致谢。
这是我的doPost方法:
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);
}
答案 0 :(得分:3)
你已经将“1”字符设置为“#19”所以当你调用全部删除时,所有'1'都会被移除,包括你期望保留的那个。 我认为你应该遍历字符并提取差异,否则比较将不会非常准确。
答案 1 :(得分:1)
要解决您的问题,请使用String .split()
方法
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()
答案 2 :(得分:1)
从我看到的地方:看起来你需要比较用逗号分隔的标记。创建strs的字符串列表(由','拆分),然后你可以删除类似的字符串,剩余的可以比较差异。