How can one allocate an object in a function with a new command and add it to a list, and keep it even after the function returns?
To be more precise, here is the C++ equivalent:
void myfunction() { MyClass* myobject = new MyClass(...); mylist.add(myobject); } void someOtherFunction() { MyClass* myobject = mylist.at(2); // The object has not been deleted }
At some point, I would simply callto deallocate my object when I wouldn't need it anymoredelete myobject;
I tried doing the same with Java, but my object must be getting deleted when the function terminates because I get a null reference exception
void myfunction() { MyClass object = new MyClass(); mylist.add(object); }
Does anyone know the way I can do this in Java? Also, how can I delete the object?