Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing List members

 
Brian Smith
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, not really. Though if there's a unique key you can use and retrieve you could make use of a map.
 
Brian Smith
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Adam Nace
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

- Adam
 
Brian Smith
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Adam, I really appreciate the detailed response.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic