I hope that the function in which you actually created the object is also static otherwise the amount of mess that you can create has no limits. Make static variables only if it means sense that every object of class should be able to use it. Don't use it for the sake of ease of sharing data like a global variable.
Also like Simon said you didn't create the ArrayList
at the first line. You made a reference variable that is capable of holding a reference to that kind of object.
About the line studentList = new ArrayList<Student>();
- The object reference is gone from the current reference variable but whether or not the object reference is completely gone depends on whether you passed it around or not.
Use clear()
instead of making a new object. But be aware that if you use clear()
then there can be side-effects if you have passed the object reference around to some other object which is storing it. If you need to pass it around and want the ArrayList
to be like a new one then it would be better to use new ArrayList<Student>()
. That can help you to avoid side-effects of clearing. So choice is yours. Depends on the situation.
One more thing, if you are just using the list as a global variable only so that you don't have to create a lot of local variables then don't do that. Instead make a lot of local variables which fall out of scope as soon as the function ends. It may seem inefficient to create a lot of objects but if all the objects are short-lived then it will be garbage collected easily as GC
is optimized for it. Also that can help avoid side-effects which can become a headache and break single-responsibility principle
.