java - ensureCapacity() for inner ArrayList -


i have 2-dimensional arraylist object

private arraylist<arraylist<short>> vol_2d = new arraylist<arraylist<short>>(); 

now want call .ensurecapacity() on both outer list , inner lists (the number of inner lists know, not initialized yet). outer list easy, define how many inner lists want fit inside.

is there nice way of calling method on inner lists? or have call every time initialize new inner list?

there's no thing "2-dimensional arraylist object". have arraylist stores arraylist objects inside it. of objects stored in outer list may have different sizes, of them may null or subclasses of arraylist. have explicitly add enough arraylist objects outer array list:

int n = // size of outer list int m = // size of inner lists private arraylist<arraylist<short>> vol_2d = new arraylist<arraylist<short>>(n); for(int i=0; i<n; i++)     vol_2d.add(new arraylist<>(m)); 

please note ensurecapacity not add elements list. resizes internal array fit specified number of elements, subsequent resizes not necessary. creating empty arraylist , calling ensurecapacity right after meaningless: better use arraylist(mincapacity) constructor same in more effective way. anyways ensurecapacity useful improve performance. if want have elements inside these lists, may use:

for(int i=0; i<n; i++) {     arraylist<short> inner = new arraylist<>(m);     for(int j=0; j<m; j++)         inner.add(null); // or other initial value     vol_2d.add(inner); } 

finally if want have two-dimensional arraylist of fixed size, why not create array this?

private short[][] vol_2d = new short[n][m]; 

it more performant.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -