1

Suppose I define a new class, say PhoneBook. I do the following:

Phonebook x = new Phonebook() Phonebook x1=x Phonebook x2=x ... Phonebook x99 =x 

then this won't consume much memory will it since all the 100 variables are pointing to the same phonebook?

Thanks

1
  • 2
    Of course, it also means that you have only on Phonebook, and any modifications made to it will be "seen" through any of the pointers. Folks often make the mistake of filling an array or List with pointers to the same object, expecting (erroneously) that the object will be duplicated for each array entry. Commented Jan 9, 2014 at 3:07

3 Answers 3

5

Correct. Each reference will consume a small amount of memory (usually 4 or 8 bytes on 32 or 64 bit systems) and that's it.

Sign up to request clarification or add additional context in comments.

Comments

0

If those are local variables they do not consume any memory on the heap because they are on stack. The size of Java pointer is JVM implementation specific usually it is 32 bit.

Comments

-1

Yes indeed you can also come to my blog Reference

What really consume memory is the first time you new a phoneBook, and the rest of Reference Phonebook consume just about 4byte each.

4 Comments

is there any problem in my answer?
It's probably the fact that a) it is mostly just a link to an off-site reference that's frowned upon in the guidelines (although you do have a summary answer as well so it's not too bad in this case.) and b) in 64 bit it will consume 8 bytes each
@TimB Got that, which really guide my future action, I will follow SOF's guideline. THX for the explaination!
stackoverflow.com/help/how-to-answer - specifically "Provide context for links Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.