0

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.

4
  • 3
    First iteration, count += count => 0; Commented Apr 2, 2013 at 15:59
  • OMG I'm such an idiot... dude, +1 for you.... I cannot believe I compeltely missed that... :: Face palm :: Commented Apr 2, 2013 at 16:04
  • 1
    How could if (policyNumberDly.equals(policyNumber)) ever return true since those are not instances of same class (ArrayList<String> vs String)? Commented Apr 2, 2013 at 16:04
  • @sp00m, you are absolutely right, I edited the post and removed the evaluation as it will never return true. Commented Apr 2, 2013 at 16:18

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I cannot believe that I missed this... Looks like I threw an id10t Exception somewhere over the weekend and never recovered.
We've all been there, Josh.
1

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).

1 Comment

I actually tried this solution and it ran much faster (12s) than comparing the ArrayLists. Thank you for the heads up!
1
   System.out.println(policyNumberDly.contains(policyNumber) ? 1 :0);

it prints 1 so state count=1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.