【问题标题】:loop through and compare 2 array lists and find a match循环并比较 2 个数组列表并找到匹配项
【发布时间】:2017-07-29 10:51:07
【问题描述】:

我有 2 个数组列表。我想返回两者之间的唯一值。这是怎么做到的?

String[] s1 = {10, 1};
String[] s2 = {10, 1, 13};

//loop through and compare element of s1 to s2     
//switch varialbe used to indicate whether a match was found
boolean matchFound = false;

//outer loop for all the elements in s2
for (int i = 0; i < s2.lenght; i++) {
  //inner loop for all the elements in s1
  for (int i = 0; i < s1.lenght; i++) {
     matchFound = true;
     System.out.println("This " + s2[i] + "was found");
  }
}
if(matchFound == false) {
  System.out.println("This " + s2[i] + "was not found");
}
//set matchFound bool back to false
matchFound = false;
}

【问题讨论】:

  • 101 这样的文字不是 String 文字
  • 您的代码无法编译。如果您将整数更改为字符串("10"10),则效果很好。
  • 很抱歉我没有包含整个代码。这些字符串从我的 servlet 传递,我将它传递给 DAO。我更新了我的代码。

标签: java arraylist removeall


【解决方案1】:

如果您的数组没有重复值,或者您只对不在出现中的元素感兴趣,那么您可以使用 Set。

将数组转换为两组:

Set&lt;T&gt; one = new HashSet&lt;T&gt;(Arrays.asList(s1));

Set&lt;T&gt; two = = new HashSet&lt;T&gt;(Arrays.asList(s2));

one.removeAll(secondSet);

two.removeAll(firstSet);

如果两个集合都是空的,那么两个集合相等,否则每个集合都有唯一的元素。

【讨论】:

    【解决方案2】:

    我用正确的答案更新了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多