Reputation: 449
I have one doubt in java, can we create dynamic ArrayList
or String[]
inside a for-loop. For example in my app there are categories field is there (not static, obtaining from server), I want to create ArrayList
or String[]
object based on size of categories. How can I create a dynamic ArrayList
in side a loop?
My code is as follows:
for(int i =0; i<20; i++)
{
ArrayList <String> list(i) = new ArrayList<String>();
}
can we create an object like this? based on category position, I can call the list items like list(positon), can we do like this java?
Upvotes: 6
Views: 61778
Reputation: 3859
If I understood what you want to do, I'd do as follows. (And btw, if this is correct, the terminology for describing what you want to do is "nested arraylists", not "dynamic arraylists". Arraylists are (like others have pointed out already) dynamic by default).
List<List<String>> lists = new Arraylist<List<String>>();
for(int i = 0; i < getNumCategoriesFromServer(); i++){
lists.add(new ArrayList<String>());
}
Now you can do, e.g.:
lists.get(0).add(someItemFromCategoryZero);
lists.get(j).add(someItemFromCategoryJ);
list.get(i)
will return the list for category i
.
You can also make an array of ArrayLists, but that will not ensure type safety at compile time.
Upvotes: 2
Reputation: 984
Are you trying to create an array with each element being an ArrayList? If so,
ArrayList[] list = new ArrayList[20];
for(int i=0; i<20; i++)
{
list[i] = new ArrayList<String>();
}
Upvotes: -1
Reputation: 40416
ArrayList
is a dynamic array, i.e. you can add new elements like,
ArrayList <String> list = new ArrayList<String>();
for(int i =0; i<20; i++)
{
list.add("string"+i);
}
i can call the list items like list(positon),can we do like this java?
ArrayList have get(position)
method to get Object from position.
String str1 = list.get(0);//0th position
Upvotes: 8
Reputation: 62439
The whole point of ArrayList
is that you don't have to worry about size. It will resize itself dynamically as more items get added. You can see the source code of add
:
410 public boolean add(E e) {
411 ensureCapacityInternal(size + 1); // Increments modCount!!
412 elementData[size++] = e;
413 return true;
414 }
ensureCapacityInternal
:
183 private void ensureCapacityInternal(int minCapacity) {
184 modCount++;
185 // overflow-conscious code
186 if (minCapacity - elementData.length > 0)
187 grow(minCapacity);
188 }
and grow
:
204 private void grow(int minCapacity) {
205 // overflow-conscious code
206 int oldCapacity = elementData.length;
207 int newCapacity = oldCapacity + (oldCapacity >> 1);
208 if (newCapacity - minCapacity < 0)
209 newCapacity = minCapacity;
210 if (newCapacity - MAX_ARRAY_SIZE > 0)
211 newCapacity = hugeCapacity(minCapacity);
212 // minCapacity is usually close to size, so this is a win:
213 elementData = Arrays.copyOf(elementData, newCapacity);
214 }
Upvotes: 5