In the following example, the float value 0.5 is accessible outside of the code block in which it was add()ed:
ArrayList<Float> myFloatArray = new ArrayList<Float>();
{
myFloatArray.add( 0.5f );
}
// Data is accessible out of the block
Can someone explain what happens in terms of object instanciation ? Why isn’t the Float object destroyed when we leave the block it was defined ? Is it equivalent to writing
myFloatArray.add( new Float(0.5f) );
The reason I am asking this is that I would like to add a time information to each float value. I thought about creating a class that would enable me to write:
myDataPointArray.add( new dataPoint( new GregorianCalendar(2011, 11, 11), 0.5f );
However, (as expected), the ArrayList is empty outside of the block the data was add()ed. I tried to make my class immutable, as I believe it may help, but it doesn’t work any better. Can someone point me the right place where this behaviour is documented ? I wasn’t able to find it and I think its goes beyond this ArrayList example.
All objects added to your
ArrayListwill reside in memory as long as theArrayListis still in use.As for you second question, the
myDataPointArraywill never loose any object you have added to it unless you remove the object from the list.Are you sure you are not re-assigning a new
ArrayListobject tomyDataPointArraysomewhere else after theaddoperation?