wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Comparing List members Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing List members" Watch "Comparing List members" New topic

Comparing List members

Brian Smith
Ranch Hand

Joined: May 20, 2005
Posts: 63
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

Joined: Jul 15, 2003
Posts: 1078
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

Joined: May 20, 2005
Posts: 63
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

Joined: Jul 17, 2006
Posts: 117
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

Joined: May 20, 2005
Posts: 63
Thanks Adam, I really appreciate the detailed response.
I agree. Here's the link: http://aspose.com/file-tools
subject: Comparing List members
Similar Threads
doubt regarding efficiency of hashcode
Whats the easiest way to get certain values out of this list of Objects and add them to a 2nd List
Adding form:option dynamically
Tricky NullPointerException Problem
Raw to <? extends Object>