【问题标题】:Same values for every key in hashmaphashmap 中每个键的值都相同
【发布时间】:2015-09-15 17:20:27
【问题描述】:

我将从我的代码开始

 public void simulateSale(List<IceCream> dailyIceCreamStock) {
    date = LocalDate.now().minusDays(6);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");

    for (int i = 0; i < timeInterval; i++) {
        for(IceCream iceCream: dailyIceCreamStock){
            iceCream.setSoldCount(rand.nextInt(IceCream.AMOUNT + 1));
            iceCream.setStockDate(date);
        }

        //Every day should have different ArrayList of values
        this.weeklyStats.put(date.toString(fmt), dailyIceCreamStock);
        date = date.plusDays(1);
    }

问题出在这一行:this.weeklyStats.put(date.toString(fmt), dailyIceCreamStock);

如您所见,我将随机生成的值添加到类型的哈希图中:

Map<String, List<IceCream>> weeklyStats

问题是,当我迭代这个哈希图时,每个键都有相同的值列表。输出如下所示:

[11, 3, 11, 12, 20]
[11, 3, 11, 12, 20]
[11, 3, 11, 12, 20]
[11, 3, 11, 12, 20]
[11, 3, 11, 12, 20]
[11, 3, 11, 12, 20]
[11, 3, 11, 12, 20]

期望的输出是在这个列表的每一个中都有随机值。 我想,范围有问题,我不明白

【问题讨论】:

  • 循环中没有变量。什么是时间间隔?
  • timeInterval 是全局 int 变量,在这种情况下,它的值为 7
  • 正如其他人回答的那样,dailyIceCreamStock 对于每周的统计数据都是一样的。

标签: java list scope hashmap


【解决方案1】:

您正在向地图中多次添加相同的 List 实例。您应该创建 List 的副本,以便在 Map 中具有不同的值:

for (int i = 0; i < timeInterval; i++) {
    List<IceCream> copy = new ArrayList<>(dailyIceCreamStock); // create a copy
    for(IceCream iceCream: copy){ // modify the elements of the copy
        iceCream.setSoldCount(rand.nextInt(IceCream.AMOUNT + 1));
        iceCream.setStockDate(date);
    }

    //Every day should have different ArrayList of values
    this.weeklyStats.put(date.toString(fmt), copy); // put the copy in the Map
    date = date.plusDays(1);
}

编辑:

实际上,这还不够,您还应该创建 IceCream 实例的副本。否则所有 List 将是不同的实例,但仍将包含相同的 IceCream 对象。

for (int i = 0; i < timeInterval; i++) {
    List<IceCream> copy = new ArrayList<>();
    for(IceCream iceCream: dailyIceCreamStock){ 
        IceCream newIC = new IceCream(); // not sure if you want to copy any
                                         // data from the original IceCream
        newIC.setSoldCount(rand.nextInt(IceCream.AMOUNT + 1));
        newIC.setStockDate(date);
        copy.add(newIC); // add a new IceCream instance to the new List
    }

    //Every day should have different ArrayList of values
    this.weeklyStats.put(date.toString(fmt), copy); 
    date = date.plusDays(1);
}

【讨论】:

    【解决方案2】:

    每次迭代,您修改相同的List&lt;IceCream&gt; dailyIceCreamStock,因此Map 中的所有键都指向同一个列表。

    您可能希望在每次迭代时初始化并引用您的List 的一个新的深层副本,并在执行随机突变后将其放入您的Map

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-16
      • 2012-05-09
      • 2014-08-18
      • 2015-04-10
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多