【发布时间】:2015-07-19 22:54:32
【问题描述】:
我觉得我在引用 VS 值中缺少一些基本的东西。在下面的代码中,getRecentProduct 正在返回对列表的引用。
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
我遵循了不同的 SO 答案,大多数情况下建议使用以下内容,但这也是返回参考。
List<ProductInformation> productinfoListCopy = new ArrayList<ProductInformation>(productInfoList);
return productinfoListCopy.get(0);
克隆对我有用。但我想知道我在哪里失踪。有人可以帮忙吗?
【问题讨论】:
-
它不返回对列表的引用。它返回对列表的第一个 ProductInformation 对象的引用(并无缘无故地创建列表的副本)。你想达到什么目的?有什么问题?
-
@JB Nizet 这不是我打算做的。我想做这个 productInfoList.get(0);所以对对象的引用意味着,如果没有克隆,我无法获得 productList 的第零个对象的副本,对吗?
-
您无法从返回类型为 ProductInformation 的方法中获取“无法获取 productList 的副本”。如果您希望该方法返回 List
,则其返回类型应为 List 。我还是不明白你想要什么。 -
对不起,我更正了。我想要的是第 0 个对象的副本。当我获取对象并克隆它时,它对我有用。但我觉得我在设计中缺少一些可以在没有克隆的情况下实现的东西。
-
如果你想要一个副本,你需要创建一个副本。使用 clone() ,或者最好使用复制构造函数。创建列表的副本以创建其第一个元素的副本是没有用的(甚至不会创建其第一个元素的副本)。问题是:你为什么要一份副本?