简体   繁体   中英

Create a list of single lists for use in a HashMap

I try to implement a hashmap like HashMap<String,MyBigList>

But I can't form my MyBigList. The following is the exact HashMap i'm trying to create.

{word=[ [1, [0, 2] ], [ 2, [2]] ], word2=[ [ 1, [1] ] ]}

I want a big list of single lists like the following

[ [single list], [single list], .. ]

and the single list containing an int and a list of ints

[single list] = [1, [0,2]]

I tried using an ArrayList inside an ArrayList inside an ArrayList, but it didn't work. I even tried creating a new class having as members an int , and a ArrayList<Integer> but it didn't work either.

import java.util.ArrayList;
import java.util.HashMap;

public class NewClass {
    int id;
    ArrayList<Integer> posList;

    public NewClass(){

        this.id = 0;
        this.posList = new ArrayList<Integer>();
    }

    public NewClass(int _id, int a, int b){
        id = _id;
        this.posList = new ArrayList<Integer>();
        posList.add(a);
        posList.add(b);
    }

    public String toString(){
        return "" + this.id + " " + this.posList;
    }
    public static void main(String[] args) {

        NewClass n = new NewClass(1,2,3);
        HashMap<String,ArrayList<ArrayList<NewClass>>> map = new HashMap<String,ArrayList<ArrayList<NewClass>>>();
        ArrayList<ArrayList<NewClass>> bigList = new ArrayList<ArrayList<NewClass>>();
        ArrayList<NewClass> nList = new ArrayList<NewClass>();
        nList.add(n);
        nList.add(n);
        bigList.add(nList);
        map.put("word", bigList);

        System.out.println(map);
    }
}

produces

{word=[[1 [2, 3], 1 [2, 3]]]}

So a Map<String, List<Object>> with no type safety around the sublist (seeing as you have Integers and lists)?

That sounds overcomplicated to put it lightly. They don't have Collections so that you can nest them for all your data, if you really want to make data easy, use a class to represent it, and store that class in a Map using some aspect as a key to get to it:

public class MyClass {

    private final String word;

    public MyClass(String word) {
        this.word = word;
    }

    // Other Data needed

    public String getWord() { return this.word; }

}

//In another class
Map<String, MyClass> words = new HashMap<>();

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