As Sara Seppola already mentioned, you need to use the smallest of the two sizes to compare the elements in the two lists. Currently, you're using the biggest of the two, which guarantees that you'll go out of bounds on the smaller list.
Also, you should be using ArrayList1.size()
and not ArrayList1.size()-1
in your loop limits, as the strictly less than check in your loop condition currently causes i
to iterate from 0
to ArrayList1.size()-2
- which is one too short. Again, the index-out-of-bounds is not caused by the -1
, but rather because of the incorrect size used in the condition.
Finally, you're not accounting for the case where the lists have equal sizes. Currently, your code gives "The files are the same" since there's not if-test which passes when ArrayList1.size() == ArrayList2.size()
.
if(ArrayList1.size() >= ArrayList2.size())
{
// Here, ArrayList1.size() >= ArrayList2.size()
// Use the smallest size as limit so we stay in bounds for both
// In this case, that's ArrayList2.size()
// When the lists have equal length, both sizes could be used
// as limit so it doesn't really matter whether you use
// > or >= in the test of the above if-statement
for(int i=0; i<ArrayList2.size(); i++)
{
if(ArrayList1.get(i).equals(ArrayList2.get(i)))
{
temp++;
}
}
}
else
{
// Here, ArrayList1.size() < ArrayList2.size()
// so use ArrayList1.size() as the limit
for(int i=0; i<ArrayList2.size(); i++)
{
if(ArrayList2.get(i).equals(ArrayList1.get(i)))
{
temp++;
}
}
}
There's still an error in your code though: you're only comparing corresponding elements. What about the extra elements from the larger list? Those should be counted as differences as well.
A quick fix would be to simply subtract the two sizes to get the number of extra elements in the bigger list, and use that as initial value for the number of difference:
if(ArrayList1.size() >= ArrayList2.size())
{
temp = ArrayList1.size() - ArrayList2.size();
// [for loop]
}
else
{
temp = ArrayList2.size() - ArrayList1.size();
// [for loop]
}
Of course, you could still simplify your code. You could use Math.min(ArrayList1.size(), ArrayList2.size())
to get the smallest of the two sizes and remove the duplicated loop. You could also use Math.abs(ArrayList1.size() - ArrayList2.size())
to get the number of extra elements, regardless whether ArrayList1
or ArrayList2
is the largest. I'll leave that as an exercise for the reader. ;-)