How do I initialize a two-dimensional List statically?

前端 未结 3 649
孤街浪徒
孤街浪徒 2021-02-05 09:39

How can I initialize a multidimensional List statically?

This works:

List> list = new ArrayList>();
<         


        
3条回答
  •  难免孤独
    2021-02-05 10:04

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

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

    and then you can do (with a static import)

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

提交回复
热议问题