simple比较java中的2个数组

时间:2012-09-19 20:02:16

标签: java arrays compare

我想要做的是让一个数组与另一个数组进行比较,如果它在比较数组中找到重复,它将跳过以下语句,这是我目前所拥有的

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))时运行时 我得到了我想要的特定输出“太棒了!”
但我现在遇到的问题是如果我运行if (!excluded[counts].contains(user))<br> 我得到排除的值,然后一些,许多值重复减去显示的那些值 例如:

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次。

3 个答案:

答案 0 :(得分:3)

只需使用集合框架即可。假设您的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)= n 2 ,我的这里只是 O(n)= n

答案 1 :(得分: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
    }
} 

答案 2 :(得分:1)

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

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