Copying a HashMap in Java

前端 未结 11 1050
灰色年华
灰色年华 2020-11-29 22:02

I am trying to keep a temporary container of a class that contains member :

HashMap myobjectHashMap

A class called my

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 22:37

    There is a small (HUGE) understatement here. If you want to copy a HashMap with nested structures, HashMap.putAll() will copy by reference, because it doesn't know how to exactly copy your object. For example:

    import java.util.*;
    class Playground {
        public static void main(String[ ] args) {
            Map>> dataA = new HashMap<>();
            Map>> dataB = new HashMap<>();
    
            dataA.put(1, new HashMap<>());
            dataB.putAll(dataA);
    
            assert(dataB.get(1).size() == 0);
    
            dataA.get(1).put(2, new ArrayList<>());
    
            if (dataB.get(1).size() == 1) { // true
                System.out.println(
                    "Sorry object reference was copied - not the values");
            }
        }
    }
    

    So basically you will need to copy the fields yourself like here

    List  aX = new ArrayList<>(accelerometerReadingsX);
    List  aY = new ArrayList<>(accelerometerReadingsY);
    
    List  gX = new ArrayList<>(gyroscopeReadingsX);
    List  gY = new ArrayList<>(gyroscopeReadingsY);
    
    Map> readings = new HashMap<>();
    
    Map> accelerometerReadings = new HashMap<>();
    accelerometerReadings.put(X_axis, aX);
    accelerometerReadings.put(Y_axis, aY);
    readings.put(Sensor.TYPE_ACCELEROMETER, accelerometerReadings);
    
    Map> gyroscopeReadings = new HashMap<>();
    gyroscopeReadings.put(X_axis, gX);
    gyroscopeReadings.put(Y_axis, gY);
    readings.put(Sensor.TYPE_GYROSCOPE, gyroscopeReadings);
    

提交回复
热议问题