为什么这张地图会更新? (JAVA)

时间:2014-05-28 10:46:29

标签: map hashmap

我一直在浏览java的Map的地图,这可能是因为当我更新另一张地图(map2)时,我的代码中的某个Map(map1)也会被更新,或者我的写作方式可能出错了它。

void process(Object superObject) {

      Map<Date, Object> map1 = superObject.getValuesForMap();
      Map<Date, Object> map2 = map1;

      updateValueOf(superObject,map2);
}

这就是我更新map2值的方法。

updateValueOfMap(Object superObject,Map<Date, Object> map2){

      List<Object> objects = getTheObjectsFromASource;
      for (Object obj : objects) {
         List<Triple<Date, Double, Object>> triples = superObject.getSomeEntriesWithThisAttribute(obj.getCertainAttrib());
         for (Triple<D,D,O> t : triples) {
            Object cache = map2.get(t.first)
            if (cache == null) {
               cache = new Object();
               cache.setThis(t.second);
               cache.setThat(t.third);
            } else {
               Double value = cache.getThis() + t.second; // add the double value from triple to the current cache Object's value
               cache.setThis(value);                      // and update the Object's value in the map
            }
            map2.put(t.first, cache);
         }
  }

}

问题是superObject.getValuesForMap()中的某些条目也会在for(Triple ..)的每次迭代中使用与map2中相应条目相同的值进行更新。为什么会这样? 回应将不胜感激。提前谢谢!

1 个答案:

答案 0 :(得分:0)

Map map1 = superObject.getValuesForMap(); map map2 = map1;

以上三点都指向相同的内存位置,因此确实会更新。

尝试这种方式:

Map map2 = new HashMap();

map2.putAll(MAP1);

更新:下面的示例程序(map1未更新MAP2更改。)

public class BaseClass {

Map<String,String> xx = new HashMap<String,String>();

public BaseClass(){
    xx.put("1", "One");
    xx.put("2", "Two");
    xx.put("3", "Three");
}

public Map<String,String> getValuesForMap(){
    return xx;
}

}

公共类TestProgram扩展了BaseClass {

void process() {

      Map<String, String> map1 = getValuesForMap();
      Map<String, String> map2 = new HashMap<String,String>();
          map2.putAll(map1);
      updateValueOf(map1, map2);
}

public void updateValueOf(Map<String, String> map1, Map<String, String> map2){
    String str1 = map2.get("1");
    str1 = str1+"Item";
    map2.put("1", str1);

    String str2 = map2.get("2");
    str2 = str2+"Item";
    map2.put("2", str2);

    String str3 = map2.get("3");
    str3 = str3+"Item";
    map2.put("3", str3);

    System.out.println("Printing Map1 ");
    printit(map1);
    System.out.println("Printing Map2 ");
    printit(map2);
    System.out.println("Printing Map1 Again");
    printit(map1);
    System.out.println("Printing Map2 Again");
    printit(map2);
}


public void printit(Map<String,String> map){
    Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
        Map.Entry pairs = (Map.Entry)iter.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
}

public static void main(String[] args){
    TestProgram ts = new TestProgram();
    ts.process();
}

}

相关问题