我想比较两个字符串数组A,B。我想返回和/或显示A,B以及A和B中唯一的元素。我按如下所示调用了我的方法,但是结果错误。如何解决?
A = 1,2,3,4,5;
B = 1,2;
compareStringArray(A,B, true);// true means print results
结果-
--Elements in ONLY A -
3, 5
--Elements in ONLY B -
--Elements in both A & B -
2
码-
public static ArrayList<ArrayList<String>> compareStringArray(
String[] arrayA, String[] arrayB, boolean display) {
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
ArrayList<String> ara = new ArrayList<String>(Arrays.asList(arrayA));
ArrayList<String> arb = new ArrayList<String>(Arrays.asList(arrayB));
ArrayList<String> common = new ArrayList<String>();
for(String s : ara){
if (arb.contains(s)) {
common.add(s);
}// if
}//for
for(String s: common){
if (ara.contains(s)) {
ara.remove(s);
}// if
if (arb.contains(s)) {
arb.remove(s);
}// if
}//for
results.add(ara);
results.add(arb);
results.add(common);
if (display == true) {
ArrayList<String> als = null;
als = results.get(0);
System.out.println("\n--Elements in ONLY A - \n");
printArrayListOfStringAsCSV(als);
als = results.get(1);
System.out.println("\n--Elements in ONLY B - \n");
printArrayListOfStringAsCSV(als);
als = results.get(2);
System.out.println("\n--Elements in both A & B - \n");
printArrayListOfStringAsCSV(als);
}// if
return results;
}// compare
最佳答案
您的代码正在我的机器上运行(我必须修复main并实施printArrayListOfStringAsCSV
这样tsk-tsk)-
public static void main(String[] args) {
String[] A = { "1", "2", "3", "4", "5" };
String[] B = { "1", "2" };
compareStringArray(A, B, true);
}
public static void printArrayListOfStringAsCSV(
List<String> al) {
for (int i = 0; i < al.size(); i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(al.get(i));
}
System.out.println();
}
我得到了这个输出(对我来说看起来是100%)。
--Elements in ONLY A -
3, 4, 5
--Elements in ONLY B -
--Elements in both A & B -
1, 2
关于java - 使用arraylist比较两个字符串数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20446587/