How do I initialize a two-dimensional List statically?

谁说我不能喝 提交于 2021-02-06 08:40:29

问题


How can I initialize a multidimensional List statically?

This works:

List<List<Integer>> list = new ArrayList<List<Integer>>();

But I'd like to init the list with some static lists like: (1,2,3), (4,5,6) and (7,8,9)


回答1:


If you create a helper method, the code looks a bit nicer. For example

public class Collections {
    public static <T> List<T> asList(T ... items) {
        List<T> list = new ArrayList<T>();
        for (T item : items) {
            list.add(item);
        }

        return list;
    }
}

and then you can do (with a static import)

List<List<Integer>> list = asList(
                             asList(1,2,3),
                             asList(4,5,6),
                             asList(7,8,9),
                           );

Why I don't use Arrays.asList()

Arrays.asList() returns a class of type java.util.Arrays.ArrayList (it's an inner class of Arrays). The problem I've found is that it's VERY easy to think that one is using a java.lang.ArrayList, but their interfaces are very, very different.




回答2:


You can do so by adding a static block in your code.

private static List<List<Integer>> list = new ArrayList<List<Integer>>();
static {
  List<Integer> innerList = new ArrayList<Integer>(3);
  innerList.add(1);
  innerList.add(2);
  innerList.add(3);
  list.add(innerList);
  //repeat
}



回答3:


You can do it this way:

import static java.util.Arrays.*;

...

List<List<Integer>> list = asList(
    asList( 1, 2, 3 ),
    asList( 4, 5, 6 ),
    asList( 6, 7, 8 ) );


来源:https://stackoverflow.com/questions/6232986/how-do-i-initialize-a-two-dimensional-list-statically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!