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?