在this回答我问的一个问题。 Kathy Van Stone说像这样添加一个数组
jList1.setListData(LinkedHashMap.keySet().toArray());
比这样做更好
jList1.setListData(new Vector<String>(LinkedHashMap.keySet()));
我想知道这是否属实,如果属实,其背后的原因是什么。
最佳答案
您需要 Vector
提供的同步吗?类(class)?如果不是,那么您不想使用 Vector
类(class)。 (如果只允许 JList
允许在其位置使用 ArrayList
就好了。)无竞争同步的成本在最近的 JVM 版本中方式要低,比以前低得多。不过,没有理由使用不必要的同步。
看起来 Kathy Van Stone 可能指的是 Vector
中的额外同步.
请仔细注意 public JList(Vector<?> listData)
的 JavaDoc :
The created model references the given Vector directly. Attempts to modify the Vector after constructing the list results in undefined behavior.
不幸的是, public JList(Object[] listData)
的 JavaDoc有相同的警告:
The created model references the given array directly. Attempts to modify the array after constructing the list results in undefined behavior.
您必须决定是否有可能有人决定 Vector
稍后在同一方法中很有用,因此修改代码如下:
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
...或者当然是 Array 构造函数版本的相同更改。
关于java - 在 jList、 vector 或数组中设置 ListData 的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/953843/