使用arraylist比较两个字符串数组

时间:2013-12-07 21:01:01

标签: java

我想比较两个字符串数组A,B。我想返回和/或显示A,B独有的元素和A& 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

2 个答案:

答案 0 :(得分:1)

你的代码正在我的机器上工作(我必须修复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

答案 1 :(得分:1)

可探测意味着问题出在printArrayListOfStringAsCSV()中。看看吧......