I have written the following code that takes two arrays and searches the index of the first occurrence of each value from the first array in the second one. For example if first = {15, 10, 18, 17, 15}
and second = {10, 15, 10, 17}
then the output would be an array with an equal length to first
which contains the indices output = {1, 0, -1, 3, 1}
, as e.g. 15 occurs in index 1 of the second
array, 10 occurs at the 0th index, etc. The index will be -1 if the value in first
doesn't occur in second
. The code I've written to loop through the arrays is as follows:
public static int[] searchIndexes(int[] first, int[] second) {
int[] indices = new int[first.length];
int index = -1;
for (int i = 0; i < first.length; i ++) {
for (int j = 0; j < second.length; j ++) {
if (first[i] == second[j])
index = j;
}
indices[i] = index;
}
return indices;
}
However, for the given example the output is instead {1, 2, 2, 3, 1}
. I think I do understand the issue; since 10 occurs twice in second
then the index of the second occurrence is recorded, but I don't know how to get around this. Putting a break;
statement after the if
clause doesn't seem to fix it.
This would be straightforward by using the
ArrayUtils.indexOf()
utility method. Moving through the second array, callArrayUtils.indexOf()
for each of its elements in reference to the first array, storing the results in the indices array. This will also mean that there would be a single loop, not a nested loop.The
ArrayUtils
class is a part of theorg.apache.commons.lang3
library.A different option, not requiring an external library, would be to convert your arrays to
List
s and then take advantage of theList.indexOf()
method.希望对您有所帮助!
您的代码中有两个问题:
index
is set to any value at all, it can never again become-1
break
.更新的代码: