Question

Strangely enough, I have a feeling I'm missing something here with using ArrayList.contains(Object o), but it's not coming to me right at the moment, can someone point me in the right direction?

I have two ArrayList that contain a list of values. I want to compare them and get the count of the matches in the files, so I have done this:

ArrayList<String> policyNumbersBene = new ArrayList<String>();
policyNumbersBene.add("YOOHOO");
ArrayList<String> policyNumberDly = new ArrayList<String>();
policyNumberDly.add("YOOHOO");

int count = 0;
for (String policyNumber : policyNumbersBene) { // compare 2 arraylists to each other.
    count += (policyNumberDly.contains(policyNumber) ? count : 0;
}
'SYSO'(count);

I believe I should get 1 in the output of the counter, but I am getting 0 each time. When I slapped a debugger on there, I can see the list of values in the arrays, and I see "YOOHOO" in there. Can someone point out what I am doing wrong? I feel like a complete java newbie asking this.

Was it helpful?

Solution

When you execute this line, count is 0 so you get 0 + 0

count += (policyNumberDly.contains(policyNumber)) ? count : 0;

Fix:

count += (policyNumberDly.contains(policyNumber)) ? 1 : 0;

OTHER TIPS

I would suggest, if you needs to calls the method contains, to use an LinkedHashset instead of an ArrayList.

The call will be in constant time instead of O(n).

   System.out.println(policyNumberDly.contains(policyNumber) ? 1 :0);

it prints 1 so state count=1;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top