2D dynamic array using ArrayList in Java

后端 未结 9 1672
执笔经年
执笔经年 2021-01-06 07:02

I need to implement a 2D dynamic array. The number of rows is fixed, say n. But the number of columns for each row is not fixed and equivalent. For instance, the first row h

9条回答
  •  青春惊慌失措
    2021-01-06 07:05

    You could create an array of ArrayList elements because your row count is fixed.

    ArrayList[] dynamicArray = new ArrayList[n]();
    

    Note: You'll need to allocate an ArrayList object in each entry in the array. So...

    for (int loop = 0; loop < n; loop++)
    dynamicArray[loop] = new ArrayList();
    

    OR if you'd like both rows and columns to be dynamic you could create an ArrayList of ArrayLists....

    ArrayList> dynamicArray = new ArrayList>();
    

    Once again, you'll need to create an array list in each new entry to dynamicArray.

提交回复
热议问题