2D dynamic array using ArrayList in Java

后端 未结 9 1589
执笔经年
执笔经年 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:26
    ArrayList<ArrayList<SomeObject>> twodlist = new ArrayList<ArrayList<SomeObject>>();
    ArrayList<SomeObject> row = new ArrayList<SomeObject>();
    row.add(new SomeObject(/* whatever */));
    // etc
    twodlist.add(row);
    row = new ArrayList<SomeObject>();
    // etc
    
    0 讨论(0)
  • 2021-01-06 07:27
    List<ArrayList<SomeObject>> twoDList = new ArrayList<List<SomeObject>>(n);
    for( int i=0; i<n; i++ )
        twoDList.add( new ArrayList<SomeObject>() );
    

    Use as:

    twoDList.get(rownumber).add(newElementInColumn);
    
    0 讨论(0)
  • 2021-01-06 07:29

    You can either use a array for the rows since this dimenstion is fixed:

    @SuppressWarnings("unchecked")
    ArrayList<T>[] arr = new ArrayList[ fixedsize];
    

    or use nested ArrayLists:

    List<List<T>> list = new ArrayList<List<T>>( fixedsize );
    
    0 讨论(0)
提交回复
热议问题