【问题标题】:simple Compare for 2 arrays in javajava中2个数组的简单比较
【发布时间】:2012-09-19 20:02:15
【问题描述】:

我想做的是让一个数组将自己与另一个数组进行比较,如果它在比较数组中发现重复项,它将跳过以下语句,这是我目前得到的

for (int count=0; count < userId.length; count++) {
    for (int integer=0; userId[count] != excluded[integer]; integer++) {
        // The arrays hold either string or Long variables in them
        // Continued code to finish off after checking array
    }
}

我想要做的是让它工作,但可能但同时保持它尽可能简单。 如果代码实际上根本不清楚,我想比较两个数组 userId 和排除,我想要的是,如果数组中的任何 userId 值与排除中的任何匹配,那么就像数组状态一样,我想将它们排除在列表。

编辑: 运行时如果(excluded[counts].contains(user))
我得到了我想要的特定输出“很棒!”
但我现在遇到的问题是,如果我像 (!excluded[counts].contains(user))&lt;br&gt; 一样运行 if 我得到了排除的值,然后是一些重复的值减去那些显示的值
示例:

String[] userId = new String [] { "10", "15", "17", "20", "25", "33", "45", "55", "77" }
String[] excluded = new String[] { "15", 20", "55", "77" }

然后我进入我的循环来检查数组

int count=0;
for (String user : userId) {
for (int counts=0; counts < excluded.length; counts++) {
if (!excluded[counts].contains(user)) {
System.out.println("UID = " + userID[count]);
}
count++

!excluded 仍会显示我不想显示的 userId 实例,因此即使我希望它排除它,它仍会显示“UID = 15”,它确实如此,但只有一次看了 4 次,我看了 3 次。

【问题讨论】:

  • 你是说你必须使用这个初始代码设置来解决你的问题,还是你愿意接受更好的方法的建议?
  • 您的意思是:对于userId 中的每个元素,而不是excluded 中的每个元素?

标签: java arrays compare


【解决方案1】:

只需使用集合框架即可。假设您的 ID 是 int 值:

int[] excluded = ... ;
int[] userIds = ... ;
Set<Integer> excludedIds = new HashSet<Integer>(Arrays.asList(excluded));
for (int userId : userIds) {
    if (excluded.contains(userId))
        continue;
    // Do something with ID
}

您也可以这样做,但这假设您不关心 userIds 数组中的重复项:

int[] excluded = ... ;
int[] userIds = ... ;
Set<Integer> excludedIds = new HashSet<Integer>(Arrays.asList(excluded));
Set<Integer> userIdSet = new HashSet<Integer>(Arrays.asList(userIds));
userIdSet.removeAll(excludedIds);
for (int userId : userIdSet) {
    // Do something with ID
}

这是更好的优化,但不是特别必要,除非您有 很多 个 ID。你的算法是O(n) = n2,我这里只是O(n) = n

【讨论】:

  • Set 解决方案当然假设 userIds 不包含重复项(它可能是例如用户进入聊天室的记录...)
  • 它们不是 int 数组,它们都是 String 或 Long
  • @FateAverie 然后只需将Set&lt;Integer&gt; 替换为Set&lt;Long&gt;Set&lt;String&gt;,它就可以在没有任何额外逻辑的情况下工作。
  • 在运行 if (excluded.contains(userId)) 之后,我检查了它跳过的剩余值,并且由于值该数组与当前值不匹配,但它在前一次传递中匹配它。 println 每次都会显示计数检查,例如count=1 counts= 0, 1, 2, 3, 4 它拾取 2 但丢弃所有其他完全相同的东西
  • 您能否澄清一下您的评论在您的问题中意味着什么?也许有一些代码?
【解决方案2】:

将排除的 ID 放入一个集合中。

Set<Integer> excludedSet = new HashSet<Integer>();
for (int i : excluded) {
  excludedSet.add(i);
}

那么你的循环看起来像这样:

for (int id : userId) {
    if (!excludedSet.contains(id)) {
        // process this user
    }
} 

【讨论】:

    【解决方案3】:

    除非您需要多次执行此任务,否则我不会为优化而烦恼。

    否则最好的解决方案是将第二个数组的项目放入Set,并使用它的有效方法(包含)来解决集合是否有项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多