I have an ArrayList<Obj>
and I wish to know how much memory it is using.
The Obj
is variant so, it is not as easy as multiply the number of elements in the array per the size of an object.
Figure 10 shows that when an ArrayList is created, the result is an ArrayList object using 32 bytes of memory, along with an Object array at a default size of 10, totaling 88 bytes of memory for an empty ArrayList This means that the ArrayList is not accurately sized and therefore has a default capacity, which happens ...
The size() method of java. util. ArrayList class is used to get the number of elements in this list. Syntax: public int size()
ArrayList in Java has a get(int index) method. int is a signed 32 bit value, with a maximum value of 2,147,483,647. That is the largest possible value that can be accessed in an ArrayList .
ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space. This is why retrieving an element from an ArrayList is so fast: given the location of the start of the ArrayList, you can know exactly where any element is located in memory.
It's the capacity of the java.util.ArrayList multiplied by the reference size (4 bytes on 32bit, 8bytes on 64bit) + [Object header + one int and one references]
.
The capacity is different (always >=)
than the size but you want to make 'em equal, call trimToSize()
Technically speaking the ArrayList
has an Object[]
where it stores the data.
You can use something like Runtime.getRuntime().totalMemory()
and its counterpart Runtime.getRuntime().freeMemory()
to get an educated guess, but that doesn't account for objects that are GC'ed between calls.
This is what a memory profiler is for. It will tell you for your platform. The minimum size for an empty ArrayList is 64-bytes. It is highly likely you don't need to know this unless you have 100K elements or more.
You can brute force calculate it if you know the content distribution of the objects.
However, the most precise method I can think of is to look at it in a profiler. There are free tools out there, some that come with the JDK. However, the best tool I've used is Yourkit. That doesn't mean it's the only solution, just my favorite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With