What is Java's lightest weight non-concurrent implementation of Iterable?

I need a class that implements Iterable, and does not need to be safe for concurrent usage. Of the various options, such as LinkedList, HashSet, ArrayList etc, which is the lightest-weight?

To clarify the use-case, I need to be able to add a number of objects to the Iterable (typically 3 or 4), and then something else needs to iterate over it.

13.10.2009 17:50:49
What does light-weight mean? How do you measure the weight?
Pascal Thivent 13.10.2009 17:57:25
What are your benchmark results?
starblue 13.10.2009 18:14:27
4 ОТВЕТА
РЕШЕНИЕ

ArrayList. From the Javadoc

The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

5
13.10.2009 17:54:27
ArrayList is a workhorse. For even less weight, use the constructor to specify the correct capacity whenever possible.
erickson 13.10.2009 18:04:01

That entirely depends on what you mean by "lightest weight". What operations do you need to do, and how often? Do you know the final size beforehand? Are you trying to save execution time or memory?

I would agree that zkarthik that ArrayList is very often a good choice... but it will behave very badly if you want to create a large collection and then repeatedly remove the first element, for example. There's a good reason for there being so many different collections: they have different performance characteristics for different situations.

2
13.10.2009 17:54:45

They all have very different features and behavior, so you should base your choice on how you will use them. For example, for random access and high locality, use an ArrayList; if you need fast unordered insertion and querying, use a HashSet.

1
13.10.2009 17:55:51

If by 'lightweight', you mean 'best performance' then the question is almost impossible to answer without understanding how the collection will be used. All you've told us so for is that it doesn't need to support concurrent usage, but in order to have any hope of answering the question we'd need to know things like

  • How many objects will be stored in the collection (on average)
  • What is the relative frequency of read and write access
  • Is random-access required
  • Is ordered access required

A number of people have suggested ArrayList may be best. However, I seem to recall reading (possibly in Effective Java 2nd edition), that for certain patterns of usage, Queue performs better than List, because it does not incurr the penalty of random access. In other words, you can add/remove items from a List in any order, but you can only add/remove items in a queue in a specific order (i.e. add to the tail, and remove from the head).

0
13.10.2009 18:07:44