java - 在 jList、 vector 或数组中设置 ListData 的更好方法是什么?

标签 java hashmap jlist

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/

相关文章:

c++ - 如何计算包含最大 N 个元素的 std::multiset 的最大数量分配?

Java GUI多项选择程序

java - 有没有办法覆盖 native 加速键?

java - 禁用 JList 单元格选择属性

performance - 如何让这段代码更高效?

java - 如何在 SolrJ 中插入具有多个子 Bean 的 Bean 对象

JavaFX——人们怎么想?

java - Google Cloud 调试无法使用 jar 文件 "File was not found in the executable"

java - Eclipse 插件 : how to modify a file source programatically?

java - 根据键值对HashMap的ArrayList进行排序