有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何更新映射中的值?

我正在使用TreeMap<Integer,Object>()来存储值
现在我的Object有一个组件Object.value(),它根据从文件读取的值不断递增
因此,我评估密钥是否存在,是否需要更新值
我不明白如何在Java中更新Map中的值
我不能仅仅替换整个记录,因为需要将新值添加到现有记录值中
有没有比使用地图更好的方法?我用了一张地图,因为我会一直找钥匙
有什么建议吗


共 (3) 个答案

  1. # 1 楼答案

    如果您希望能够快速访问键值对,那么使用映射是正确的。如果您的值只是MyObjects.value(),您不能获取对象并重置该值吗

    MyObject myObj = treeMap.get(key);
    myObj.setValue(myObj.getValue()++);
    

    我在这里使用MyObject,因为海报使用Object表示示例类型

  2. # 2 楼答案

    我不知道你想做什么,但是如果你只想用键存储对象,你应该使用哈希表。它允许将关键点映射到对象

    //create a hashtable
    //the first template type is the type of keys you want to use
    //the second is the type of objects you store (your Object)
    Hashtable <Integer,MyObject> myHashtable = new Hashtable <Integer,MyObject> ();
    
    //Now you create your object, and set one of its fields to 4.
    MyObject obj = new MyObject();
    obj.setValue(4);
    
    //You insert the object into the hashtable, with the key 0.
    myHashtable.put(0,obj);
    
    //Now if you want to change the value of an object in the hashtable, you have to retrieve it from its key, change the value by yourself then re-insert the object into the hashtable.
    MyObject obj2 = myHashtable.get(0);
    
    obj.setValue(obj.getValue() + 2);
    
    //This will erase the previous object mapped with the key 0.
    myHashtable.put(0,obj);
    

    希望这有帮助

  3. # 3 楼答案

    您的“对象”需要有一个更新值的setter。因此,您只需从映射中检索有问题的对象,调用该对象上的setter,et voila。您必须注意的唯一障碍是,无论您在setXXX方法中做什么,都不会改变equalshashCode方法的结果,因为这违反了TreeMap所隐含的不变量,并将导致不可预测的行为。您的对象可能如下所示:

    class AnObject {
       private int cnt;
       public void increment() { this.cnt++ };
    }
    

    您可以将它从TreeMap中拉出,调用increment(),而不必更改TreeMap本身的内容