下面是我的示例代码:
个人类别:
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中。
发布于 2015-01-29 11:59:04
类似地,迭代器和枚举返回元素,这些元素在迭代器/枚举创建后的某个点反映了哈希表的状态。他们不抛ConcurrentModificationException。但是,迭代器一次只能被一个线程使用。
因此,如果您是唯一一个迭代映射,您是很好的,即使另一个线程正在更新它。但是请注意,在使用Swing时,在访问GUI小部件时主要提到线程安全--必须通过事件调度线程来完成。因此,上面的代码应该从传递给EventQueue#invokeLater的可运行程序中运行。
https://stackoverflow.com/questions/28222243
复制相似问题