This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
It seems like there must be a better way than how I am going about this. I have a list of objects and am searching for a paticular object. If I find the object, I edit a property of the object. Right now I am iterating through the list to find the object. Is there a more concise way? wrappedAccounts if of type ArrayList containing WrappedAccount objects
No, not really. Though if there's a unique key you can use and retrieve you could make use of a map.
Joined: May 20, 2005
Thanks for the tip, unfortunately, I can't use a map because this List is being bound to a JSF data table. JSF data tables only accept: Array, List, java.sql.ResultSet, javax.servlet.jsp.jstl.Result, and javax.faces.model.DataModel
Basically, without having a map, or without having a reference to the object already, there is no way to know if the item is in the list except for iterating over the list to find out. This is probably the only safe way.
Under certain circumstances, you *could* attempt to make the search more efficient:
If your list was a Random Access List (i.e. an Array List, as opposed to a Sequential Access List such as a Linked List), you could sort the list, or even better, maintain the list in sorted order, and then use a binary search algorithm to cut the search time to O(log n) rather than O(n)
Now, currenlty, the collections framework is pretty poor for maintain sorted lists or sets that can be randomly accessed (i.e. it provides no ordered list implementation that I'm aware of, and the ordered set implementations are not random access by index, but by object, which you don't necessarily have). However, with a bit of work, I'm sure you could make a collection of your own that would work well enough.
Joined: May 20, 2005
Thanks Adam, I really appreciate the detailed response.