开发者

What is the generally recommended way of creating a collection of objects in Java?

I want to create a collection of objects that implement a given interface (in C# it would be something like Collection<IMyInterface>). I don't care about sorting or indexed access but would like to easily iterate over the collection with foreach (or the Java equivalent). It also needs to hav开发者_开发百科e as small a memory footprint as possible (and ideally be threadsafe).

What do you recommend?

Thanks


You should read Java Collections tutorial and choose what fits your needs most.


Check out the Java Collection Tutorial. That will introduce you to the Java collection idioms, the generics support, and what's available (briefly, Lists, Sets and Maps - it's not clear how you want to store this data).

Without any further info, and in the most trivial scenario, you may want something like:

List<IMyInterface> list = new ArrayList<IMyInterface>();
// populate and then iterate...
list.add(new MyObject());
for (IMyInterface o : list) {
   // do something...
}

(ignoring thread-safety issues)

Once you're au fait with the standard collections, it's worth looking at more advanced options like Google Collections and Apache Commons Collections. These both offer more powerful collections and tools for iteration/manipulation.

Note (finally) that Vector and the like are advertised as being thread-safe. That (of course) only applies per-method-call. A collection inspection/addition operation will not be thread-safe natively and will require some extra synchronisation surround multiple operations.


You might want to use Vector which is thread-safe and will do your purpose in this case.

Collection<Integer> collection = new Vector<Integer>();

collection.add(1); //add something to the collection

//iterate over the collection
for(Integer test : collection) {
  //do something with 
}


Your best bet it to do one of these:

import java.util.*;
import java.util.concurrent.*;

// ...

// Thread-safe, but creates a new copy on write... so writers can write new
// values that readers won't see
List<IMyInterface> = new CopyOnWriteArrayList<IMyInterface>();

or

import java.util.*;

// ...

// also thread-safe, collection is locked during writes
List<IMyInterface> = Collections.synchronizedList(new ArrayList<IMyInterface>());

Edit: Another answer points out that the Vector class also implements the List interface and is thread-safe, so you could use that instead of the second option here.


Java Collections Framework contains many of the classes you may find useful. They have both threadsafe and non-threadsafe candidates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜