简体   繁体   English

使用java中的循环填充hashmap

[英]Populating hashmap with a loop in java

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: 嗨,我有一个问题用循环填充hashmap,我需要将对象存储为值和字符串作为键,如果另一个元素想要添加到hashmap,则应该检查它,如果该值已经存在,如果是这样,它应该例如,将字符串键增加1:

("JButton", JButtonObject);

another element wants to be added if again JButton it should be 如果JButton应该是另一个元素想要添加

("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");
             }
        }
    }
}                        

Define a structure: 定义结构:

Map<String,LinkedHashMap<String,Object>> map=new LinkedHashMap<String,LinkedHashMap<String,Object>>();

It looks like: 看起来像:

"Jbutton"--->#####################
             #"Jbutton" , object0#
             #"Jbutton1", object1#
             #"Jbutton2", object2#
             #####################

"JBox"  ---->##################
             #"JBox" , object0#
             #"JBox1", object1#
             #"JBox2", object2#
             ##################

Then use it in your method 'CreateInstance': 然后在你的方法'CreateInstance'中使用它:

LinkedHashMap<String,Object> selectedMap=map.get(substring);
if(selectedMap==null){//First put in this kind of element
    selectedMap=new LinkedHashMap<String,Object>();
    map.put(substring, selectedMap);
}else{
    selectedMap.put(substring+ (selectedMap.size()==0? "":selectedMap.size()), object);
}

将“首选键”(例如“JButton”)的第二个HashMap保持为整数,然后使用整数来确定您当前使用的实际键的下一个后缀。

I don't know your actual requirement. 我不知道你的实际要求。 But maybe this alternative approach to store multiple objects for a single key works too, and if it does, it will make life much easier. 但也许这种为单个键存储多个对象的替代方法也可以工作,如果确实如此,它将使生活变得更加容易。 I wouldn't construct different keys but use one key and a list of instances for that key: 我不会构造不同的密钥,但使用一个密钥和该密钥的实例列表:

HashMap<String, List<Object>> hm = new HashMap<String, List<Object>>();

// ...

try {
  Class classDefinition = Class.forName(sel.toString());
  object = classDefinition.newInstance();
  //create name
  String data = sel.toString();
  String substring = data.substring(12);

  // new code added here:
  List<Object> objects = hm.get(substring);
  if (obejcts == null) {
    objects = new ArrayList<Object>();
    hm.put(substring, objects);
  }
  objects.add(object);

// continue with catches 

It will be a bit different to use, but you may be able to do all you wanted to do: 使用会有所不同,但您可以做所有想做的事情:

if (hm.get(substring) == null) { // no object stored for key substring }
int numberOfObjects = hm.get(substring).size();
Object firstObject = hm.get(substring).get(0);  // the first object for substring
List<Object> objects = hm.get(substring);  // all objects

Maybe you should use another structure as everybody says. 也许你应该使用另一种结构,正如每个人所说。 But for doing what you want to: 但是为了做你想做的事:

String substring = data.substring(12);
//check if name is unique

// add this line
String uniqueKey = findUniqueKey(hm, substring);

//add to map with the calculated value
hm.put(uniqueKey, object);----- HERE IS THE PROBLEM

and... 和...

private String findUniqueKey(Map<String, ?> map, String prefix)
{
   if (!map.containsKey(prefix))
      return prefix;
   int i = 1;
   while(true) { // or check i against a maximum
      String candidate = prefix + i;
      if (!map.containsKey(candidate))
         return candidate;
      i++;
   }
}

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. 仅使用HashMap创建实例。 So your code is not linked to a particular implementation of what you need: a Map. 因此,您的代码不会与您需要的特定实现相关联:Map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM