简体   繁体   English

清单 <List<Double> &gt;添加到HashMap

[英]Lists<List<Double>>adding to HashMap

So, after request of compiling code, here it is. 因此,在请求编译代码之后,就在这里。 And the problem is that after adding second Hash element Called "B", the output messes up. 问题是,在添加了第二个称为“ 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);
    }
}

The output is: 输出为:

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

Which in my opinion and needs, should be: 我认为和需要的应该是:

[[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]]}

You are still referencing old instances of the lists. 您仍在引用列表的旧实例。 This should work as expected: 这应该可以正常工作:

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);
    }
}

In Java objects are always taken by reference. 在Java中,对象始终通过引用来获取。 Which means that 意思就是

stuffList.clear();
something.clear();
stuffList.add(3.4);

operates on the same lists you put in the map by the key "A". 通过键“ A”对您放置在地图中的相同列表进行操作。

So in the end the map contains the same list twice. 因此,该地图最后两次包含相同的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM