checking two arrayLists
Answered
- Need more info
- Answered
- Working on it
in
Programming Questions
•
3 years ago
hi,
i have two arrayLists and i want to check if they contain the same values, to check if a condition is met.
arrayList1 (1, 2 ,3)
arrayList2 (1,1,1,1,1, 2, 2, 2, 3, 3, 3 )
the condition is that arrayList2 has the same elements as arrayList1.
i thought this could be done in either of two ways;
1) remove duplicate elements of arrayList2, retaining the first instance: arrayList2 then becomes (1, 2, 3);
then condition can be checked either arrayList1 == arralyList2 , or arrayList1.size() == arrayList2.size();
2) count if the same element occurs, to get an int value;
then condition can be checked if int == arrayList1.size();
Happy to do either way but i tried to code the 2nd, but i am counting the number of times an element of arrayList 1 occurs in arrayList 2, not if it occurs - to do this would need move to next element in first array once found and continue checking, but don't know how to do that.
int count = 0;
for(int i=0; i<arrayList1.size(); i++) {
int val = (Integer) arrayList1.get(i);
for(int j=0; j<arrayList2.size(); j++) {
if (arrayList2.contains(val)) {
count++;
}
}
}
for(int i=0; i<arrayList1.size(); i++) {
int val = (Integer) arrayList1.get(i);
for(int j=0; j<arrayList2.size(); j++) {
if (arrayList2.contains(val)) {
count++;
}
}
}
i am sure this has been discussed before but have not been able to find the answer yet on this or the old forum.
thanks for any help.
1