我需要搜索存儲在LinkedHashMap中的匹配值對。我嘗試了以下代碼,但它為存在的任何值都給出了true,但我只希望當相應的值與鍵值匹配時返回true。bt2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if(CheckValueExample.checkRelationship(txtKey.getText(),txtValue.getText())==true) System.out.println("Pair Match"); else System.out.println("No-Pair Match"); } catch (Exception ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); } }});匹配對的方法:public static boolean checkRelationship(String key, String value) { HashMap<String, String> hashmap = new LinkedHashMap<String, String>(); // Adding Key and Value pairs to HashMap hashmap.put("Bus","Land_Vehicle"); hashmap.put("SchoolBus","Bus"); hashmap.put("Truck","Land_Vehicle"); hashmap.put("Land_Vehicle","Vehicle"); boolean flag=false; if(hashmap.containsKey(key)&&hashmap.containsValue(value)) flag=true; else flag=false; return flag;}假設輸入密鑰時為“Bus”,輸入的值為“Land_Vehicle”;只有這樣,它才應該返回 true。任何其他替代方法來做到這一點也是可觀的,基本上我必須匹配存儲在json文件中的對。
1 回答

慕桂英4014372
TA貢獻1871條經驗 獲得超13個贊
只是用來檢查關系。hashmap.containsKey(key) && hashmap.get(key).equals(value)
它獲取 是否存在 的值,并將其與給定的 進行比較。keyvalue
這是完整的方法:
public static boolean checkRelationship(String key, String value) {
return hashmap.containsKey(key) && hashmap.get(key).equals(value);
}
您還應該只初始化一次(例如在塊中),而不是每次調用該方法時。HashMapstatic {}
添加回答
舉報
0/150
提交
取消