您好我有一個問題,使用循環填充hashmap,我需要將對象存儲爲值並將字符串存儲爲鍵,如果另一個元素想要添加到散列表中,應該對其進行檢查,如果該值已經存在,如果是的話,應該由1例如遞增的字符串鍵:在Java中使用循環填充hashmap
("JButton", JButtonObject);
另一個元素想如果再JButton的應該是添加
("JButton1", JButtonObject);
...
...
...
我的代碼: 謝謝你們
private void CreateInstance(java.awt.event.ActionEvent evt) {
// add code here
Object object = null;
if (evt.getSource() == CreateInstance)
{
int[] selectedIx = ClassList.getSelectedIndices();
for (int i=0; i<selectedIx.length; i++) {
Object sel = ClassList.getModel().getElementAt(selectedIx[i]);
try {
Class classDefinition = Class.forName(sel.toString());
object = classDefinition.newInstance();
//create name
String data = sel.toString();
String substring = data.substring(12);
//check if name is unique
//add to map
hm.put(substring, object);----- HERE IS THE PROBLEM
System.out.println();
}
catch (InstantiationException e) {
System.out.println(e);
}
catch (IllegalAccessException e) {
System.out.println(e);
}
catch (ClassNotFoundException e) {
System.out.println(e);
}
if(object instanceof java.awt.Component){
DesignWindow.add((java.awt.Component)object);
DesignWindow.validate();
}
else{
System.out.println("Error");
}
}
}
}
非常感謝你的幫助伴侶,現在我弄明白了 – HAMID 2010-08-26 06:36:03