Java hashmap中每个键的值相同
我将从我的代码开始Java hashmap中每个键的值相同,java,list,scope,hashmap,Java,List,Scope,Hashmap,我将从我的代码开始 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(
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);
}
问题是,当我迭代这个hashmap时,每个键都有相同的值列表。输出如下所示:
[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]
期望的输出是在该列表中的每一个中都有随机值。
我想,作用域存在一些问题,我不理解您多次将同一列表实例添加到映射中。您应该创建列表的副本,以便在地图中具有不同的值:
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);
}
for(int i=0;i
编辑:
实际上,这还不够,还应该创建冰淇淋实例的副本。否则,所有列表都将是不同的实例,但仍将包含相同的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);
}
for(int i=0;i
每次迭代,您都会修改相同的列表dailyIceCreamStock
,因此映射中的所有键都指向相同的列表
您可能希望在每次迭代时初始化并引用列表的一个新的深度副本,并在执行随机突变后将其放入映射中 循环中没有变量。什么是timeInterval?timeInterval是全局int变量,在这种情况下,它的值是7,其他人回答时,dailyIceCreamStock对于每个周都是一样的。
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);
}