【问题标题】:How to send value of a list instead of reference(where list is a value of a map)?如何发送列表的值而不是参考(其中列表是地图的值)?
【发布时间】: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() ,或者最好使用复制构造函数。创建列表的副本以创建其第一个元素的副本是没有用的(甚至不会创建其第一个元素的副本)。问题是:你为什么要一份副本?

标签: java reference clone


【解决方案1】:

您使用的代码会创建列表的副本,但它是“浅副本”。这意味着它是一个不同的列表,但它仍然引用相同的对象。因此,如果您获得任一列表的第一个元素,您将获得对同一对象的引用。

您想要实现的是“深拷贝”。您会在那里找到有关该主题的大量信息 - 这是一个示例问题 - 它处理数组而不是列表,但原理相同,希望对阅读有用 Deep copy of an object array

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多