Hi i have a problem populating hashmap with a loop, i need to store objects as a value and string as a key and if another element wants to be added to hashmap it should be checked against, if the value already exist, if so it should increment the the string key by 1 for example:
("JButton", JButtonObject);
another element wants to be added if again JButton it should be
("JButton1", JButtonObject);
...
...
...
my code:
Thanks guys
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");
}
}
}
}
Maybe you should use another structure as everybody says. But for doing what you want to:
and…
This way you separate the logic for deciding the key from the rest of the code.
Sidenote: Try to use Map references. Only use HashMap for creating the instance. So your code is not linked to a particular implementation of what you need: a Map.