• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using the contains method on an ArrayList of ArrayLists  RSS feed

 
Matthew Busse
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Java ranchers,

I'm in a pickle. I need to check if an ArrayList of ArrayLists contains a string, and if it does, continue onto the next iteration of a for loop. However, I don't think using the .contains method on the ArrayList of ArrayLists checks through all the individual items of the individual ArrayLists, at least it doesn't appear to do do in the tests I've run. So I tried using the contains method on the individual ArrayLists, but to do that, I need to put it within an iterator or a for loop or something, and then the continue method only continues that small for loop, not the bigger for loop, so I don't know how to do this.

Here's what I want to do, the problem line is pointed out with comments:


These following lines work for checking the elements of the ArrayLists contained in the ArrayList, but they have to be inside of some kind of loop, so a continue statement only continues that smaller loop:



Does anyone know a way around this?

Thanks,
Matt
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matt,
You are correct that you need to loop through the outer ArrayList. What if you used a helper method? Then you could use return instead of continue. (The alternative is a labeled continue which is horrible to read/maintain.)

For example:
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"continue" without an argument will jump to the next go-round of the immediately enclosing loop. But it can actually be used to continue an outer loop, too, if you label the loop and then add the name of the label as an argument:



 
Matthew Busse
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your responses Jeanne and Ernst.

Labeling the outer for loop seems like a really simple fix, is it really that bad to use labeled for loops?

This works:
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Labelled break and labelled continue are equivalent to "goto". Many people believe goto is a potent source of errors in programming, but that is by no means a universal opinion.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!