views:

891

answers:

2

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.

+1  A: 

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)

eugener
+3  A: 

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.

Eddie
Probably better to always be on the safe side and instantiate that new Vector/object ... unless you really really can't afford to create one extra object
matt b
Either way you are making an object - an array or a vectory, it is just a question of which one is more efficient to iterate over and to create. Intuition says array, but really a test is in order.
Yishai
@Yishai: True, if you really care about timing, then profile it. But since Vectors are synchronized (and internally backed by an array, right?), I'd be surprised if the pure array was slower.
Eddie