这是我的示例代码:
人类:
public class Person {
private String firstName;
private String lastName;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
public Person(String firstName,String lastName){
this.setFirstName(firstName);
this.setLastName(lastName);
}
public String getFirstName() {
return firstName;
}
private void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
private void setLastName(String lastName) {
this.lastName = lastName;
}
}
测试/主要:
ConcurrentHashMap<Integer,Person> storage = new ConcurrentHashMap<Integer, Person>();
storage.put(1, new Person("Sally","Solomon"));
storage.put(2, new Person("Harry","Solomon"));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jButton1 = new JButton("Button");
Person [] personArr= storage.values().toArray(new Person[0]);
String [] names = new String[personArr.length];
System.out.println(personArr.length);
for(int i=0; i<personArr.length; i++){
System.out.println(personArr[i].getFirstName());
names[i] = personArr[i].getFirstName() + " " + personArr[i].getLastName();
}
final JList jList1 = new JList(names);
问题: 获取ConcurrectHashMap中的值并将它们添加到JList的正确方法是什么?我完成它的方法是将所有值读入字符串数组并将其添加到JList。
答案 0 :(得分:0)
每ConcurrentHashMap's documentation:
类似地,Iterators和Enumerations在迭代器/枚举的创建时或之后的某个时刻返回反映哈希表状态的元素。它们不会抛出ConcurrentModificationException。但是,迭代器被设计为一次只能由一个线程使用。
因此,如果您是唯一一个遍历地图的人,那么即使另一个线程正在更新它,您也会很好。但请注意,在使用Swing时,主要在访问GUI小部件时提及线程安全性 - 必须从事件调度线程完成。 因此,上面的代码应该从传递给EventQueue#invokeLater
的runnable运行