I have a question - how mwmory is allocated when any data structure is declared?
Suppose I have declared a list as follows -

List<Integer> lst = new ArrayList<Integer>();

How many bytes will be allocated for that variable or initially no memory will be allocated? Memory will be allocated when the list will be in use?

3 Years
Discussion Span
Last Post by jessicarobort

Nothing will, initially, be created on the heap, except of course, that which ArrayList itself needs. Well, I can't say nothing, the initial "list" will contain 10 "slots" so the memory needed for those references (4 bytes each) as well as the reference for the ArrayList itself (also 4 bytes) will be created, as well as the 8 bytes for the serialVersionUID (but that is static), the 4 bytes for the "size" int, the 4 bytes for the "max_array_size" variable (also static), and another static "max_array_size" (4 bytes) from AbstractCollection. IOW, completely negligable.

Edited by masijade


Don't confuse variables and objects; your example contains both.
List<Integer> lst declares a variable. It's a reference, just a few bytes regardless of what it refers to. If it's a local variable it will be allocated when it comes into scope and released when it goes out of scope. If it's an instance variable it will be allocated and released with the rest of its parent object.
new ArrayList<Integer>() creates an object on the heap (see masijade's post) when that statement is executed. Its memory willl be released by garbage collection when there are no remaining references to it.

Edited by JamesCherrill


You can't know and should not care about the actual amount of memory used. It's not guaranteed anywhere to be any specific amount, and different JVMs can implement things differently, so assuming a specific number is extremely dangerous.

Memory will indeed be allocated with that statement, just enough to instantiate the ArrayList instance with its default settings. See above as to why you shouldn't bother trying to think about how much exactly that is.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.