2011-04-15 1 views
0

J'ai des problèmes avec les HashMaps de mon programme. J'ai plusieurs déclaré à la première classe comme ceci:Pourquoi HashMap est-il réinitialisé après la sortie de la méthode?

public HashMap<String, Object> hmClass = new HashMap<String ,Object>(); 
     public HashMap<String, Object> hmIns = new HashMap<String, Object>(); 
     public HashMap<String, Object> hmCon = new HashMap<String, Object>(); 
     public HashMap<String, Object> hmParam = new HashMap<String, Object>(); 
     public HashMap<String, Object> hmResult = new HashMap<String, Object>(); 

Dans une méthode distincte, je mets des valeurs en eux comme ceci:

public String newInstanceCreate(Class c3, String classInstance)//void ?? 
    { 
     Class c = c3; 
     String cI = classInstance; 
     Object instance = null; 
     Object con = null; 
     String instanceName = null; 

     try{ 
     instanceName = JOptionPane.showInputDialog(null, "Under what name would you like to store this Instance?", 
               "Create an Instance of a Class", JOptionPane.QUESTION_MESSAGE); 
     }catch(NullPointerException e) 
     { 
      newInstanceCreate(c,cI); 
     } 

     hmClass.put(instanceName, c); //add the name of the instance as key and class as value to the hashmap 
     System.out.println(hmClass);  

      con = JOptionPane.showInputDialog(null,"Choose Constructor for " + c, "Create an Instance of a Class", 3, null, getConstructors(c), JOptionPane.QUESTION_MESSAGE); 


     System.out.println("worked + " + con); 
     hmCon.put(instanceName, con); //add the name of the instance as key and constructor as value to the hashmap 
     System.out.println(hmCon); 


     try { 
      instance = c3.getDeclaredConstructor().newInstance(); //create the instance --KEY 
      hmIns.put(instanceName, instance); 
      System.out.println("23" + instance); 
      hmParam.put(instanceName, getParams(c3, con)); //ask the user for the parameters (doubles) that they want in the instance constructor 
                  // add the name of the instance as key and parameters(array) as value   

     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e){ 
      e.printStackTrace(); 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
     } catch (SecurityException e) { 
      e.printStackTrace(); 
     } catch (InvocationTargetException e) { 
      e.printStackTrace(); 
     } catch (NoSuchMethodException e) { 
      e.printStackTrace(); 
     } 
     System.out.print("hmClass: \n" + hmClass + "hmIns: \n" + hmIns + "hmCon: \n" + hmCon + "hmParam: \n" + hmParam); 
     return classInstance; 
    } 

Mais lorsque je tente d'y accéder à partir d'une autre méthode, il semble qu'ils ont tous été réinitialisés.

public void option4() 
    { 
     System.out.println("hmIns: " + hmIns); 
     String stringInstance = JOptionPane.showInputDialog(null, "Which Instance would you like to stringify? " , 
              "Stringify an Instance of a Class", JOptionPane.QUESTION_MESSAGE); 


     //get all the required info for making the instance 
     /* 
     * needed: name of stored instance 
     *   name of correct and stored constructor 
     *   name of parameters that were created by user (doubles?) 
     */ 
     System.out.println(stringInstance); 
     if(hmIns.isEmpty()) 
      System.out.println("EMPTY"); 
     Object ins = hmIns.get(stringInstance); 
     System.out.println("ins before: " + ins); 
     Object cons = hmCon.get(stringInstance); 
     System.out.println("cons before: " + cons); 
     Object par = hmParam.get(stringInstance); 
     System.out.println("par before: " + par); 

     //construct an instance and run toString() here 
     try { 
      ins = ((Constructor)cons).newInstance(par); 
      System.out.println(" ins: " + ins); 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } catch (InvocationTargetException e) { 
      e.printStackTrace(); 
     } 
     //result from toString 
     /* 
     * stored: name of result 
     *   result itself (stored as string for now) 
     */ 

     JOptionPane.showMessageDialog(null, "result here??--how to get result to double??", "Stringified Instance of: ", 0); 

     mainWindow(); 
    } 

Dans la dernière méthode répertoriée, j'ai testé pour voir si le HashMap avait des valeurs nulles au lieu d'être réellement vide, mais il retourne comme ayant aucune valeur du tout. Pourquoi le HashMap est-il réinitialisé après la sortie de la première méthode?

Merci beaucoup pour votre avis.

Fran

+3

Déclarez la carte 'static'. Est-ce que ça marche? Ensuite, vous accédez simplement aux différentes instances de la carte. – BalusC

+2

Veuillez ne pas utiliser la notation hongroise et les noms cryptiques courts. – sverre

+0

@BalusC, ouais le déclarant statique a fonctionné. Merci. =) – Jordan

Répondre

4

Il n'est pas réinitialisé. Je vous suggère de regarder votre code dans un débogueur et de vérifier s'ils regardent le même objet/carte. Je soupçonne que vous avez deux objets qui contiennent des cartes.

+1

ouais je l'ai fait. Je vous remercie. Déclarer les cartes statiques élaboré. – Jordan

+0

@Fran: Cela ne signifie pas nécessairement que c'est la bonne solution. Mon commentaire était juste un indice pour allumer l'ampoule dans votre tête (qui a apparemment échoué). (Ab) en utilisant 'static' pourrait vous causer des problèmes sérieux, en particulier dans un environnement concurrent (multi-utilisateur). Comment le résoudre à juste titre dépend de l'exigence fonctionnelle qui est tout à fait clair de la question puisque le code n'est pas auto-documenté. – BalusC

+0

@BalusC, je ne serais pas à l'aise en utilisant statique pour résoudre ce problème, mais je soupçonne @ Fran71 a de plus gros problèmes à résoudre. La solution correcte est d'avoir un wrapper pour la carte qui est transmise là où c'est nécessaire. –

Questions connexes