Houssam Badri
Houssam Badri

Reputation: 2509

ArrayList declaration and handling

I often use ArrayList in my Java software and i insist that the program has to be as clean as possible.

I have this ambiguity in ArrayList variable declaration and usage.

So, what is, among these three ArrayList usages, the correct way that I have to choose?

CASE 1:

List<Object> l = some_function();

CASE 2:

    List<Object> l  = new ArrayList<Object>();
    l = some_function();
    //staff
    l.clear()

CASE 3:

 List<Object> l = null;
 l = some_function();
 //staff
 l.clear()

Function:

List<Object> some_function(){
List<Object> list = new AyyarList<Object>();
//Staff
return list;
}

My question about the function is: Does java clear the list variable automatically, or have I clean it by using clear() API and how then? }

Upvotes: 1

Views: 109

Answers (2)

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32458

In my opinion, case 1 is better. 2nd case create an unnecessary ArrayList object, which will be lost when you assign the method return value.

Does java clear the list variable automatically, or have I clean it by using clean() API and how then?

Java won't clear your list, you have to clear it, check the API, ArrayList#clear()

how can clear the list manually if it is declared inside the function and i should use it later outside the function(its outputs)

You have to assign the returned list to a temporary list, then you can clear the list.

List<Object> returnedList = some_function();
 //stuff
 returnedList.clear()

List<Object> some_function() {
     List<Object> list = new AyyarList<Object>();
     //Stuff
     return list;
}

Upvotes: 3

Joshua Kissoon
Joshua Kissoon

Reputation: 3309

In my opinion, case 1 is better.

List<Object> l = some_function();

There is no need for the second case in which you assign a value to the variable then overwrite it.

I would not recommend you using clear unless you need to re-use the l variable. Because the memory is cleared asynchronously by the Garbage collector, and not directly by such library functions as clear(). clear would only null them all out, and update the ArrayList state accordingly.

So either way, the memory will only be cleared by the garbage collector.

Upvotes: 2

Related Questions