Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize ArrayList

Tags:

I come from a C++ background and I want to have a matrix of

ArrayList<arrayList<E>> javamatrix  

In C++ I would just do

std::vector<std::vector<T> > cppmatrix; std::vector<T>vcol(cols); cppmatrix.resize(rows,vcol); 

I can't seem to find a built-in resize() function for ArrayLists for this task, so should I use another collection? Is no way to do this except using for loops with javamatrix.add()?


P.S I want it to be initialized in the constructor with its size as that size might be queried before I edit elements or add or remove.

like image 256
Ismail Marmoush Avatar asked Nov 13 '10 01:11

Ismail Marmoush


People also ask

Can ArrayList be resized?

ArrayList class is a resizable array, present in java. util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array.

How do you increase the size of an ArrayList dynamically in Java?

The load factor is the measure that decides when to increase the capacity of the ArrayList. The default load factor of an ArrayList is 0.75f. For example, current capacity is 10. So, loadfactor = 10*0.75=7 while adding the 7th element array size will increase.

How do I reduce the size of an ArrayList?

trimToSize() method trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.


1 Answers

There is no resize equivalent that automatically constructs and adds elements. You must do this yourself. However, ensureCapacity is equivalent to vector's reserve. It will ensure you have room, but not change the actual size.

like image 73
Matthew Flaschen Avatar answered Oct 21 '22 00:10

Matthew Flaschen