Search code examples
javajava-8queueclone

How to clone a BlockingQueue in Java?


In my Java Application I have

BlockingQueue<HashMap<Integer, double[]>> q

How do I clone it?


Solution

    1. Basic copy : copy of the Queue

      BlockingQueue<HashMap<Integer, double[]>> q; // = ...
      BlockingQueue<HashMap<Integer, double[]>> copy = new LinkedBlockingDeque<>(q);
      

    1. Deep copy : copy of the Queue and the Map's

      BlockingQueue<HashMap<Integer, double[]>> q; // = ...
      BlockingQueue<HashMap<Integer, double[]>> copy = new LinkedBlockingDeque<>();//or other
      
      for(HashMap<Integer, double[]> map : q){
          copy.add(new HashMap<>(map));
      }
      

    1. Very deep copy : copy of the Queue, the Map's and the double[]'s

      BlockingQueue<HashMap<Integer, double[]>> q; // = ...
      BlockingQueue<HashMap<Integer, double[]>> copy = new LinkedBlockingDeque<>();//or other
      
      for(HashMap<Integer, double[]> map : q){
          Map<Integer, double[]> mapCopy = new HashMap<>();
          for(Map.Entry<Integer, double[]> entry : map.entrySet()){
              double[] array = entry.getValue();
              mapCopy.put(entry.getKey(), Arrays.copyOf(array, array.length));
          }
          copy.add(mapCopy);
      }