【问题标题】:Comparing two ArrayLists in Java比较 Java 中的两个 ArrayList
【发布时间】:2013-01-15 07:09:37
【问题描述】:

我正在尝试编写一个方法,该方法采用 2 个双精度数组列表并返回 set1 中未在 set2 中找到的所有值。这些数字应在 set3 中返回。通常我只会使用 set.contains 但我只能使用 set.get set.size 和 set.add。谁能指出我正确的方向?

例如:

如果 set1 的数字是 1,2,3,4,5

set2 的数字是 1,7,9,5,3

set3 应该只包含 2,4,5

ArrayList<Double> setDiff(ArrayList<Double> set1, ArrayList<Double> set2){
    ArrayList<Double> set3 = new ArrayList<Double>();
    for(int i = 0; i < set1.size(); i++){
        for(int x = 0; x < set2.size(); x++){
            if(set1.get(i) != set2.get(x)){
                set3.add(set1.get(i));
            }
        }
    }
    return set3;
}

【问题讨论】:

标签: java loops methods arraylist compare


【解决方案1】:

问题是,您根据第一次失败将号码添加到set3。因此,如果set2 的第一个元素与set1 的当前元素不匹配,则将其添加到set3

鉴于您的工具包中的限制,我怀疑这是您的作业。所以,我只是给你一个如何接近的想法。

您可以使用boolean 变量并切换它(例如将其设置为false),一旦您在set2 中找到当前元素,然后突破inner loop

因此,您在内部循环中的条件将从:-

if(set1.get(i) != set2.get(x))

到:-

if(set1.get(i) == set2.get(x)) {
    // The current element in set1 is present in set2. 
    // toggle the boolean variable
    // break out of loop. As you no more want to check for further elements.
}

然后在inner loop 之外,检查boolean 变量的状态。并且根据状态,您可以将当前项目添加或不添加到set3。例如如果布尔变量为false,则表示你在set2中找到了该元素,所以不要将它添加到set3,否则添加它。

您还需要每次在外循环开始时重置布尔变量。

【讨论】:

    【解决方案2】:

    您可以尝试使用 Apache commons CollectionUtils.removeAll 方法:此方法返回一个集合,其中包含 c 中所有未删除的元素。

    ArrayList commonList = CollectionUtils.removeAll(arrayList1, arrayList2);
    

    【讨论】:

      【解决方案3】:

      试试

      static ArrayList<Double> setDiff(ArrayList<Double> set1, ArrayList<Double> set2) {
          ArrayList<Double> copy1 = (ArrayList<Double>) set1.clone();
          copy1.retainAll(set2);
          ArrayList<Double> copy2 = (ArrayList<Double>) set1.clone();
          copy2.removeAll(copy1);
          return copy2;
      }
      
      public static void main(String[] args) throws Exception {
          ArrayList l1 = new ArrayList(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0));
          ArrayList l2 = new ArrayList(Arrays.asList(1.0, 7.0, 9.0, 5.0, 3.0));
          System.out.println(setDiff(l1, l2));
      }
      

      打印

      [2.0, 4.0]
      

      此外,我建议将方法签名更改为

      <T> List<T> listDiff(List<T> list1, List<T> list2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-23
        • 2012-01-25
        相关资源
        最近更新 更多