HashTable的get方法打印所有元素
Method get of HashTable print all the elements
我的数据结构是这样的:
HashMap<String, HashMap<String,String>> map = new HashMap<>();
在这个结构中我必须这样保存数据:
Low 12 1
High 22 0
Low 10 1
Low 11 0
现在,我必须只打印具有第一个参数 "Low" 的数据,但是当我执行 .get("Low")
时,如果我的变量中还有一个 "High" 元素,也会打印这个。
这是我的代码:
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"));
}
我哪里错了?谢谢
您总是将 map2
放入 map
中,您应该在其中第一次创建一个新的 HashMap,然后在第二次和后续时间重复使用该 Hashmap。
伪代码(未经测试):
label2subitems = map.get(label[2]);
if (label2subitems == null)
{
label2subitems = new HashMap();
map.put(label[2],label2subitems);
}
label2subitems.put(...);
我的数据结构是这样的:
HashMap<String, HashMap<String,String>> map = new HashMap<>();
在这个结构中我必须这样保存数据:
Low 12 1
High 22 0
Low 10 1
Low 11 0
现在,我必须只打印具有第一个参数 "Low" 的数据,但是当我执行 .get("Low")
时,如果我的变量中还有一个 "High" 元素,也会打印这个。
这是我的代码:
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"));
}
我哪里错了?谢谢
您总是将 map2
放入 map
中,您应该在其中第一次创建一个新的 HashMap,然后在第二次和后续时间重复使用该 Hashmap。
伪代码(未经测试):
label2subitems = map.get(label[2]);
if (label2subitems == null)
{
label2subitems = new HashMap();
map.put(label[2],label2subitems);
}
label2subitems.put(...);