Home / Java Patterns and Pitfalls     frequal.com

The Parallel List Pitfall

Summary

Parallel lists, two lists with paired elements, are a Java pitfall to watch out for. It is almost always preferable to replace them with a single list of pair objects. This prevents the lists getting out of sync and makes the code cleaner.

Details

Sometimes you will see code in which someone has fallen into the anti-pattern of parallel lists (or arrays). Usually one list has the main object, and another list has input for the main object or status from the main object. These two lists need to be kept in sync and looped over in parallel. It is all too easy for the lists to get out of sync if they aren't updated simultaneously, and difficult to remove or sort the items.

All these problems can be easily solved by creating a new object that encapsulates both the main object and the extra data. Then create a single list for the wrapper object. The benefits are many:

  • Only one loop needed to iterate over both the main object and the auxiliary data
  • Only one list to pass around the code
  • No chance that the lists can get out of sync -- there is just one list.

Last modified on 24 Jun 2009 by AO

Copyright © 2016 Andrew Oliver