Question

In this answer to a question I asked. Kathy Van Stone says that adding an array like so

jList1.setListData(LinkedHashMap.keySet().toArray());

is a better way than to do it like this

jList1.setListData(new Vector<String>(LinkedHashMap.keySet()));

I am wondering if there was any truth to this and if so what the reason behind it was.

Was it helpful?

Solution

Do you need the synchronization afforded by the Vector class? If not, then you don't want to use the Vector class. (If only JList allowed using an ArrayList in its place.) The cost of uncontended synchronization is way lower in recent JVM versions, way lower than it used to be. Still, there's no reason to use unnecessary synchronization.

It looks like Kathy Van Stone may be referring to that extra synchronization in Vector.

Note carefully the JavaDoc for public JList(Vector<?> listData):

The created model references the given Vector directly. Attempts to modify the Vector after constructing the list results in undefined behavior.

Unfortunately, the JavaDoc for public JList(Object[] listData) has the same warning:

The created model references the given array directly. Attempts to modify the array after constructing the list results in undefined behavior.

You have to decide if there is any likelihood that someone decides that the Vector is useful later in the same method and thus modifies the code like this:

Vector vec = new Vector<String>(LinkedHashMap.keySet());
jList1.setListData(vec);
// Other stuff with Vector
vec.add( .... ); // Adding some data type that fits in the Vector

... or of course the same change with the Array constructor version.

OTHER TIPS

Take a look at implementation of both setListData methods in JList class and you will see that it really doesn't matter. I would prefer the first one, simply because there is no need to involve yet another collection (Vector)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top