Are primitive types garbage collected in Android?

android, dalvik, garbage-collection

Solution

Primitive types are not objects, so they do not cause any garbage collection. However, you do have to be very careful because due to boxing a primitive type can easily become an object without you explicitly doing so.

For example, if you want a HashMap<> of integer keys, you would use HashMap. Note that because "int" is not an object, it can't be used in a container. Integer is an object version of a primitive int. When you write code like this, an Integer object will automatically be created for you:

HashMap<Integer, Object> map = new HashMap<Integer, Object>();
int someNum = 12345;    // no object created.
map.put(someNum, null); // Integer object created.

Note that the exact same thing will happen if you don't use generics, but even more hidden:

HashMap map = new HashMap();
int someNum = 12345;    // no object created.
map.put(someNum, null); // Integer object created.

For this particular situation, you can use Android's SparseArray class, which is a container of primitive integer keys.

Problem

I know this may be a dumb question, but my background is more in c++ and managing my own memory. I am currently cutting down every single allocation that I can from one of my games to try and reduce the frequency of garbage collection and perceived "lag", so for every variable that I create that is an Object (String and Rect for example) I am making sure that I create it before hand in my constructor and not create temporary variables in simple 10 line functions... (I hope that makes sense) Anyways I was working though it some more tonight and I realized that I may be completely wrong about my assumption on garbage collection and primitive types (int, boolean, float) are these primitive type variables that I create in a 10 line function that gets called 20 times a second adding to my problem of garbage collection? So a year ago every few seconds I would see a message in logcat like GC freed 4010 objects / 484064 bytes in 101ms Now I see that message every 15-90 seconds or so... So to rephrase my question: Are primitive types (int, float, boolean, etc) included when seeing this message?

Original source