Search code examples
javareferenceclone

How to send value of a list instead of reference(where list is a value of a map)?


I feel I'm missing something basic in references VS values.In the following code, getRecentProduct is returning a reference to the list.

   public class ProductMapWrapper { 
    Map<String, List<ProductInformation>> productMap = new  HashMap<String, List<ProductInformation>>();

  public void putObject(ProductInformation productInfo, String key){
    List<ProductInformation> productInfoList = productMap.get(key);
    if (null == productInfoList)
        productInfoList = new ArrayList<ProductInformation>();
    productInfoList.add(productInfo);
    productMap.put(key, productInfoList);   
   }

  public ProductInformation getRecentProduct(String key){
    List<ProductInformation> productInfoList = productMap.get(key);
     productInfoList.get(0); //returns reference
    // the following is also returning reference
    List<ProductInformation> productinfoListCopy =  new ArrayList<ProductInformation>(productInfoList);
    return productinfoListCopy.get(0);
    }   
}
    // main function 
    ProductInformation productInfo = new ProductInformation();
    productInfo.setProdID("2323");
    ProductMapWrapper mapWrapper = new ProductMapWrapper();
    mapWrapper.putObject(productInfo, "MEDICAL");
    ProductInformation getObj =  mapWrapper.getRecentProduct("MEDICAL");
    System.out.println(getObj.getProdID());
    ProductInformation getObj1 =  mapWrapper.getRecentProduct("MEDICAL");
    getObj1.setProdID("test");
    System.out.println(getObj.getProdID()); // prints test

I followed different SO answers and mostly it has been suggested to use the following, but this is also returning reference.

  List<ProductInformation> productinfoListCopy =  new ArrayList<ProductInformation>(productInfoList);
    return productinfoListCopy.get(0);

Clone is working for me. But I wanted to know where I'm missing. Can someone help?


Solution

  • The code you're using creates a copy of the list, but it's a "shallow copy". That means that it's a different list, but it's still referencing the same objects. And so if you get the first element of either list, you're getting a reference to the same object.

    What you're trying to achieve is a "deep copy". You'll find a lot of information on the topic out there - here's an example question - it deals with arrays rather than lists but it's the same principle, and hopefully it's some useful reading Deep copy of an object array