简体   繁体   中英

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.

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. 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".

So in the end the map contains the same list twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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