0

I want to check to see if two arrays share at least one term in common for my program.

I'm not quite sure what the code is to compare two arrays, but here is what I have so far;

if ((modWikiKeyArray).equals(inputArray[0]))
{
   StringBuilder hyperlinkBuilder = new StringBuilder();
   for(int i = 0; i < modWikiKeyArray.length; i++)
   {
      hyperlinkBuilder.append(modWikiKeyArray[i]);  
   }
}

How would I compare the array modWikiKeyArray to inputArray just to check and see if inputArray[0] is equal to any term inside of modWikiKeyArray?

4

3 回答 3

1

Arrays.asList允许您构建一个由任意数组支持的列表,并使用方便的 Java 集合框架功能,如contains方法:

Arrays.asList(oneArray).contains(elementFromAnotherArray)

如果您想查看数组是否至少有一个共同元素,您可以构建HashSet一个并循环另一个以尝试找到一个共同元素:

boolean arraysIntersect(Object[] array1, Object[] array2) {
    Set array1AsSet = HashSet(Arrays.asList(array1));
    for (Object o : array2) {
        if (array1AsSet.contains(o)) {
            return true;
        }
    }
    return false;
}
于 2013-08-04T05:05:16.497 回答
0

您可以执行以下操作

    for(int i=0;i<modWikiKeyArray.length;i++) {
        if(modWikiKeyArray[i].equals(inputArray[0])) {
            System.out.println("Match found");
        }
    }

请注意,您需要覆盖您正在创建的任何数组的 equals() 方法(您正在创建的数组的类)。

于 2013-08-04T05:05:42.390 回答
0

Going by your code snippet, it looks like you need to check the presence of inputArray[0] only, in which case the following is sufficient:

boolean exists = java.util.Arrays.asList(modWikiKeyArray).contains(inputArray[0]);

Alternatively, you might also want to use ArrayUtils from Apache commons-lang:

boolean exists = ArrayUtils.contains(modWikiKeyArray, inputArray[0]);

However, if I read the text of your question, it seems you want to find if modWikiKeyArray contains at least one item from inputArray. For this you may also use retainAll from the Collections API to perform a list intersecion and see if the intersection list is non-empty.

However, the most primitive is still Aniket's method. However, I will modify it to reduce unnecessary operations:

int i = modWikiKeyArray.length - 1;
MyObject inputElement = inputArray[0];
boolean found = false;
for(; i != 0; i--) {
    if(modWikiKeyArray[i].equals(inputElement)) {
        found = true;
        break;
    }
}
于 2013-08-04T06:23:05.427 回答