问题
I have two arrays of objects in Java, which contain some fields that I need to compare, but the thing is I need to compare element by element, that means, that I want the compare a field from the first object in my first array with the first object in my second array, my second object from the first array with my second object from the second array and so on. This is what I have done so far, but the idea is that I do not know what should be the limit for my second array. From my point of view the second array should start from the index of the first array like this:
for(int i = 0; i < resultEntries.size(); i++) {
for(int j = i; j < resultColorEntries.size(); j++) {
if(resultEntries.get(i).getColor())...
};
}
Another solution or a solution to my problem would be welcome. Thanks in advance!
回答1:
You can keep check of index that it is less than the size of both arrays.
for(int i=0;i<resultEntries.size() && i<resultColorEntries.size();i++){
if(resultEntries.get(i).getColor()) {
}
}
回答2:
if you want to compare more efficiently with O(N), you need to implement your object hash(), and add your item to a hashset, example hasSetA for arrayA and hashsetB for your arrayB, then compare these two hashsets.
回答3:
You don't have to make 2 loops, you can achieve this only with one:
for(int i = 0; i < resultEntries.size() && i < resultColorEntries.size(); i++) {
if(resultEntries.get(i).getColor().equals(resultColorEntries.get(i).getColor()) {
// Same!
}
}
回答4:
that I want the compare a field from the first object in my first array with the first object in my second array, my second object from the first array with my second object from the second array and so on
You shouldn't have to write nested loop then. One loops will do.
Codes should be
for(int i=0;i<resultEntries.size();i++){
if(resultEntries.get(i).getColor().equals(resultColorEntries.get(i).getColor()) )...
Assuming you have the same size of lists.
回答5:
The whole thing only makes sense when both arrays have equal dimensions; so you could go for:
Whatever a[] = ...
Somthinelse b[] = ...
check for equal length
for (int i=0; i < a.length; i++) {
if (a[i].whatever.equals(b[i].whatever))...
Point is: no need for two loops!
But: there is no nice way of generalizing that (like: writing a method that compares those arrays; but on different fields for example). Well, you could use method references, and using method references, ending up with something like
public void compareArraysOn(Whatever[] a, Other[] b, Function<T,U> extractorForA, ...) {
that could be called like compareArraysOn(a, b, Whatever::getColor(), SomethinElse::getColor())
来源:https://stackoverflow.com/questions/42385835/how-to-compare-two-arrays-element-by-element-in-java