[英]Java - Correct way of add a ConcurrentHashMap to a JList?
这是我的示例代码:
人员类别:
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中。
类似地,迭代器和枚举返回在创建迭代器/枚举时或此后某个时刻反映哈希表状态的元素。 他们不抛出ConcurrentModificationException。 但是,迭代器被设计为一次只能由一个线程使用。
因此,如果您是唯一在地图上进行迭代的人,那么即使有另一个线程正在更新它,也很好。 但是请注意,使用Swing时,在访问GUI窗口小部件时通常会提到线程安全性-必须从事件分发线程中完成。 因此,您上面的代码应从传递给EventQueue#invokeLater的可运行代码运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.