Create an array of ArrayList elements

后端 未结 12 1899
遥遥无期
遥遥无期 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:30

    I have tried this without an error, even though I have putted a limit in the array less than the amount of items added:

    package Testes.src;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Testes {
    
        private List<String> name=new ArrayList<String>(1);
    
        public Testes(){
            for (int i = 1; i <= 100; i++) {
                name.add("Teste"+Integer.toString(i));
            }
            for (int i = 0; i < name.size(); i++) {
                System.out.println(name.get(i));
            }
        }
        public static void main(String [] args)
        {
            Testes t1=new Testes();
        }
    }
    
    0 讨论(0)
  • 2020-12-03 01:32
    ArrayList<ArrayList<String>> name= new ArrayList<ArrayList<String>>(/*capacity*/);
    
    0 讨论(0)
  • 2020-12-03 01:34

    The correct way is:

    ArrayList<String> name[] = new ArrayList[9];
    

    However, this won't work either, since you can't make an array with a generic type, what you are trying to do is a matrix, and this should be done like this:

    String name[][];
    
    0 讨论(0)
  • 2020-12-03 01:34
    // This is the not correct way
    ArrayList<String> name[] = new ArrayList<String>()[];
    
    // This is the correct way
    ArrayList<String> list[] = new ArrayList[2];
    
    list[0] = new ArrayList();
    list[1] = new ArrayList();
    
    list[0].add("Some String 11");
    list[0].add("Some String 22");
    
    list[1].add("Some String 1111");
    list[1].add("Some String 2222");
    
    0 讨论(0)
  • 2020-12-03 01:35

    I know this is an old post, but someone just asked the same question and since nobody has mentioned the following solution, here it is.

    One way to get around it could be something like a 2d array (the recent question was about a 2d array or ArrayLists) of objects and then you should be able to put ArrayList references in the array. I have not tested it, but something like this should work.

    Object [][] data = new Object[5][5];
    data[0][0] = new ArrayList<String>(); // etc . . .
    
    0 讨论(0)
  • 2020-12-03 01:37

    You cannot create an array of a generic type.

    Instead, you can create an ArrayList<ArrayList<String>>.

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