gpt4 book ai didi

java - Lists>添加到 HashMap

转载 作者:行者123 更新时间:2023-12-01 08:11:46 26 4
gpt4 key购买 nike

所以,在请求编译代码之后,它就在这里。问题是,在添加第二个名为“B”的哈希元素后,输出变得困惑。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) {
Map<String, List<List<Double>>> alphabet = new HashMap<String,List<List<Double>>>();
List<List<Double>> something = new ArrayList<List<Double>>();
List<Double> stuffList = new ArrayList<Double>();
stuffList.add(3.1);
stuffList.add(3.2);
stuffList.add(3.3);
something.add(stuffList);
alphabet.put("A", something);
System.out.println(something);
System.out.println(alphabet);
stuffList.clear();
something.clear();
stuffList.add(3.4);
something.add(stuffList);
alphabet.put("B", something);
System.out.println(something);
System.out.println(alphabet);
}
}

输出为:

[[3.1, 3.2, 3.3]]
{A=[[3.1, 3.2, 3.3]]}
[[3.4]]
{A=[[3.4]], B=[[3.4]]}

在我看来和需要,应该是:

[[3.1, 3.2, 3.3]]
{A=[[3.1, 3.2, 3.3]]}
[[3.4]]
{A=[[3.1, 3.2, 3.3]], B=[[3.4]]}

最佳答案

您仍在引用列表的旧实例。这应该按预期工作:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) {
Map<String, List<List<Double>>> alphabet = new HashMap<String,List<List<Double>>>();
List<List<Double>> something = new ArrayList<List<Double>>();
List<Double> stuffList = new ArrayList<Double>();
stuffList.add(3.1);
stuffList.add(3.2);
stuffList.add(3.3);
something.add(stuffList);
alphabet.put("A", something);
System.out.println(something);
System.out.println(alphabet);
// Create new instances:
something = new ArrayList<List<Double>>();
stuffList = new ArrayList<Double>();
stuffList.add(3.4);
something.add(stuffList);
alphabet.put("B", something);
System.out.println(something);
System.out.println(alphabet);
}
}

关于java - Lists<List<Double>>添加到 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16696876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com