Generic type for Arraylist of Arraylists

前端 未结 5 653
长情又很酷
长情又很酷 2021-01-02 12:54

In normal array list initialization, We used to define generic type as follows,

List list1 = new ArrayList();

B

相关标签:
5条回答
  • 2021-01-02 13:33

    You are talking about an array of lists (ArrayLists to be more specific). Java doesn't allow generic array generation (except when using wildcards, see next paragraph). So you should either forget about using generics for the array, or use a list instead of an array (many solutions proposed for this).

    Quote from IBM article:

    Another consequence of the fact that arrays are covariant but generics are not is that you cannot instantiate an array of a generic type (new List[3] is illegal), unless the type argument is an unbounded wildcard (new List< ?>[3] is legal).

    0 讨论(0)
  • 2021-01-02 13:44

    You can simply do

    List<List<String>> l = new ArrayList<List<String>>();
    

    If you need an array of Lists, you can do

    List<String>[] l = new List[n];
    

    and safely ignore or suppress the warning.

    0 讨论(0)
  • 2021-01-02 13:45

    You are Right: This looks insane. (May its an Bug...) Instead of Using

    ArrayList<String>[] lst = new ArrayList<String>[]{};
    

    Use:

    ArrayList<String>[] list1 = new ArrayList[]{};
    

    will work for the declaration, even if you dont describe an congrete generic!

    0 讨论(0)
  • 2021-01-02 13:57

    If you (really) want a list of lists, then this is the correct declaration:

    List<List<String>> listOfLists = new ArrayList<List<String>>();
    

    We can't create generic arrays. new List<String>[0] is a compiletime error.

    0 讨论(0)
  • 2021-01-02 13:58

    Something like this:

    List<List<Number>> matrix = new ArrayList<List<Number>>();
    for (int i = 0; i < numRows; ++i) {
        List<Number> row = new ArrayList<Number>();
        // add some values into the row
        matrix.add(row);
    }
    

    Make the type of the inner List anything you want; this is for illustrative purposes only.

    0 讨论(0)
提交回复
热议问题