# Thread: Comparing two ArrayLists elements but getting in correct result.

1. Member
Join Date
Oct 2013
Posts
2
Rep Power
0

## Comparing two ArrayLists elements but getting in correct result.

Hello All,

I am traing to comparing two list elements on below case's
But getting incorrect resul for case3.

List<Integer> a1 = new ArrayList<Integer>();

List<Integer> a2 = new ArrayList<Integer>();

Case1:

Result :Working correct!

Case2:

Result :Working correct!

Case2:

Result :Not Working
Getting our put like below:

Both are equal
Both are equal
Both are equal
Both are equal
Both are equal
Both are equal

But expected here is 3 results is equal and 3 results is not equal

for (Integer fistList : a1) {
for (Integer secondList : a2) {

if (fistList == secondList) {
matchFound = true;
break;
}
}

if (matchFound) {
System.out.println("Both are equal");
} else {
System.out.println("Both are not equal");
}

}
Please any one suggest what is the mistk in above code ?

2. ## Re: Comparing two ArrayLists elements but getting in correct result.

[code]
[/code]
to get highlighting and preserve formatting.

The logic needs to look at ALL of the elements of the arraylists BEFORE deciding that the contents of the two lists are the same. How many items does the code look at before the boolean is set to true.

A technique: assume the lists are equal, look at each pair of elements and fail the test at the first pair that are not equal.
If you don't find a mismatch after looking at the whole list, then your assumption was correct.

3. Member
Join Date
Oct 2013
Posts
2
Rep Power
0

## Re: Comparing two ArrayLists elements but getting in correct result.

Finally i solved my problem below are correct code.

Java Code:
```import java.util.ArrayList;

public class TwoListCompare {

public static void main(String[] args) {

ArrayList<Integer> aList1 = new ArrayList<Integer>();
ArrayList<Integer> aList2 = new ArrayList<Integer>();

// boolean matchFound = false; //Commented to fix the problem

for (Integer list1 : aList1) {
boolean matchFound = false; // Added after fix
for (Integer list2 : aList2) {

if (list1 == list2) {
matchFound = true;
break;
}

}

if (matchFound) {
System.out.println("Both elements are equal");
} else {
System.out.println("Both elements are not equal");
}
}

}

}```
Thanks and Regards,

4. ## Re: Comparing two ArrayLists elements but getting in correct result.

I guess I missed what the objective of the program is.

Is the program supposed to find if the last element in the first list is in the second list?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•