Java语言读取打开一个字典的时候,字典的条目一旦出现了重复就出错了

Java语言读取打开一个字典的时候,字典的条目一旦出现了重复就出错了,怎么避免这种情形呢

字典在任何语言里key确实唯一,java里我们用HashMap来避免字典中出现重复的条目,需要注意的是添加新的键值时,如果键已经存在会更新对应的值,在通过getEntry可以根据键获取对应的值。

import java.util.HashMap;

public class Dictionary {
    private HashMap<String, String> entries;

    public Dictionary() {
        entries = new HashMap<>();
    }

    public void addEntry(String key, String value) {
        if (!entries.containsKey(key)) {
            entries.put(key, value);
        } else {
            System.out.println("Error: Duplicate entry!");
        }
    }

    public String getEntry(String key) {
        return entries.get(key);
    }

    public static void main(String[] args) {
        Dictionary dictionary = new Dictionary();
        dictionary.addEntry("apple", "a fruit");
        dictionary.addEntry("banana", "a fruit");
        dictionary.addEntry("apple", "a tech company"); 
        System.out.println(dictionary.getEntry("apple")); 
        System.out.println(dictionary.getEntry("banana")); 
    }
}

  Java字典避免“条目重复出错”:在添加key前,检查字典中是否已存在该key,不存在才添加。


<hr>

dict.containsKey();判断字典是否包含指定key,返回true/false;

  我仅会点儿python ,但感觉字典在任何语言中,key都应该是唯一的。因为C+V了一段Java关于字典的代码,其注释也说的key是唯一,同python dict差不多的。(在python 中的字典向其添加已存在的key不会抛出报错异常,添加的key新值会重写原有key的值,就是key的最新值会覆盖原有值。)看起来,Java也一样啊。

  • 我C+V的Java代码
哈希表(字典)
Map<Integer,String> dict = new HashMap<>();
Map<String,Integer> dict = new HashMap<>();
dict.put(key,value);无序添加,key重复则覆盖掉;
dict.get(key);通过key获取对应的value;
dict.remove(key);删除指定key;
dict.size();返回数组长度;
dict.replace(key,value);修改指定键的值;
dict.keySet();返回包含所有key值的hashSet数组;
dict.isEmpty();判断字典是否为空;
dict.containsKey();判断字典是否包含指定key,返回true/false;