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?

Recommended Answers

All 4 Replies

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.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.