Create an array of ArrayList elements

后端 未结 12 1963
遥遥无期
遥遥无期 2020-12-03 01:27

I want to create an array that contains ArrayList elements.

I\'ve tried

ArrayList name[] = new ArrayList()[];
         


        
12条回答
  •  难免孤独
    2020-12-03 01:44

    I know this is a bit old but I am going to respond to this anyway for future views.

    If you really want an ArrayList[] structure, you can simply create a class that extends ArrayList and make an array of that class:

    public class StringArrayList extends ArrayList{}
    

    And in your implementation:

    ArrayList name[] = new StringArrayList[9];
    

    Here is a sample:

    package testspace.arrays;
    
    import java.util.List;
    
    public class TestStringArray {
    
        public static void main(String[] args) {
            List[] arr = new StringArrayList[10];
            for(int i = 0; i < arr.length; i++){
                // CANNOT use generic 'new ArrayList()'
                arr[i] = new StringArrayList(); 
                for(int j = 0; j < arr.length; j++){
                    arr[i].add("list item #(" + j + "|" + i + ")");
                }
            }
    
            StringBuilder sb = new StringBuilder();
            for(final List list : arr){
                for(final String str : list){
                    sb.append(str + " ");
                }
                sb.append("\n");
            }
            System.out.println(sb.toString());
        }
    
    }
    

    NOTE You will get a runtime error if you use this instead : arr[i] = new ArrayList()

提交回复
热议问题