简体   繁体   English

创建要在HashMap中使用的单个列表的列表

[英]Create a list of single lists for use in a HashMap

I try to implement a hashmap like HashMap<String,MyBigList> 我尝试实现像HashMap<String,MyBigList>这样的hashmap

But I can't form my MyBigList. 但是我无法形成MyBigList。 The following is the exact HashMap i'm trying to create. 以下是我要创建的确切的HashMap。

{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 以及包含一个int和一个int列表的单个列表

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

I tried using an ArrayList inside an ArrayList inside an ArrayList, but it didn't work. 我尝试在ArrayList内的ArrayList内使用ArrayList,但没有用。 I even tried creating a new class having as members an int , and a ArrayList<Integer> but it didn't work either. 我什至尝试创建一个具有intArrayList<Integer>作为成员的新类,但是它也不起作用。

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]]]} {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)? 那么Map<String, List<Object>>在子列表周围没有类型安全性(看到您有整数和列表)?

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: 它们没有Collections,因此您可以将它们嵌套在所有数据中,如果您真的想简化数据,可以使用一个类来表示它,然后使用某个方面作为键将其存储在Map

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

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

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