简体   繁体   中英

Method get of HashTable print all the elements

I have a data structure that is this:

HashMap<String, HashMap<String,String>> map = new HashMap<>();

In this structure I must save the data in this way:

Low 12 1
High 22 0
Low 10 1
Low 11 0

Now, I must print only the data that have how first parameter "Low" but when I do .get("Low") if in my variable there is also an "High" element print also this. This is my code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    HashMap<String, HashMap<String,String>> map = new HashMap<>();
    HashMap<String,String> map2 = new HashMap<>();
    String label[];
    JCheckBox casella=new JCheckBox();


    if(jList2.getModel().getSize()>0){ //Se sono state selezionate PAD
        for(int i=0; i<jPanel2.getComponentCount(); i++){ //Controlla se le PAD hanno i prode             
            if( (casella=(JCheckBox) jPanel2.getComponent(i)).isSelected() ){ //Si
                label=(casella.getText()).split(" ");
                map2.put(label[4], "1");
                map.put(label[2],map2);

            }
            else{ //No
                label=(casella.getText()).split(" ");
                map2.put(label[4], "0");                    
                map.put(label[2], map2);

            }
        }


        System.out.println(map.get("Low"));

    }

Where I wrong? Thanks.

You're always putting map2 into map where you should create a new HashMap for the first time and then reuse the Hashmap second and subsequent times.

Pseudo code (untested):

label2subitems = map.get(label[2]);
if (label2subitems == null)
{
    label2subitems = new HashMap();
    map.put(label[2],label2subitems);
}
label2subitems.put(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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