This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I create new lists all over the place. Typically due to firing events and trying not to do it from inside a synchronized block, and not wanting to iterate across an accessible list while i am firing an event.
Typically I see that Sun uses clone. And I suppose that makes sense in a way. You know what your implementation is so you can use clone(). Is clone faster or cheaper than new ArrayList(oldlist)??? i use new ArrayList now.
Mmmm, I don't think javap tells us much useful here. The number of steps isn't really relevant unless we know what the steps are. Is it quicker to do A and B, or just C? Who knows; we'd need to analyze what A, B, and C really involve. If we really care I think it would be far more productive to run some timed tests. However I will go out on a limb here and guess that it's unlikely there will be a significant difference.
I prefer to avoid clone() here because I try to use the most general type I can to refer to classes I'm working with. If I've got an ArrayList instance, I prefer to declare it as a List, Collection, or Iterable (my first choice in many cases nowadays) unless I really need to declare a more specific type. And the thing is, none of those types declare a public clone() method. (Or copy() or whatever you prefer.) If I need to make a copy of a list, I can always use an ArrayList() constructor for that, since it's defined to work on any Collection. I don't have to require the pre-existing list to be an overly specific type. So that's the main reason I would avoid clone() here. [ November 03, 2005: Message edited by: Jim Yingst ]
Back to your original problem... If you are using the current version of Java (1.5), you can use CopyOnWriteArrayList -- with it, you can safely iterator on the list while modifying it concurrently. [ November 03, 2005: Message edited by: Jeff Albrechtsen ]