Sarang
Sarang

Reputation: 349

Is it required to nullify ArrayList before recreating an object?

I am not sure if it is going to consume more & more memory while working with the arraylist. I am confused when going through following block of code:

headerRow = new ArrayList<>();
headerRow.add("");
xlHeader.add(headerRow);

// headerRow = null;                     //<----- This is the line of confusion.
headerRow = new ArrayList<>();

Should the headerRow be nullified ?

What will happed to the Blank String Object ("") added to headerRow ?

Upvotes: 0

Views: 157

Answers (5)

Suresh Atta
Suresh Atta

Reputation: 122006

You just use

headerRow = new ArrayList();

No need to nullify it before ,JVM manages it.

And in the first two lines of code

List<String> headerRow = new ArrayList<String>();
headerRow = new ArrayList();

That second line is redundant.There is no need to write headerRow = new ArrayList();

Since you already initialized in the before line.

Upvotes: 1

This operation do not have any affect on performance what so ever.

We can set null to reference when we use it in form of control to not perform a action again.

For example

   Closable stream = getStream();

  try {
    stream.close();
    stream = null;
  catch(Exception e) {
    log(e);
  } finally {
    if(stream != null) {
      try { stream.close(); } catch(Exception empty) {}
    }
  }

Upvotes: 0

duffymo
duffymo

Reputation: 308958

I have no idea why you do this:

List<String> headerRow = new ArrayList<String>();
// First one is correct; lose the line that follows.
headerRow = new ArrayList();

Upvotes: 0

TheKojuEffect
TheKojuEffect

Reputation: 21101

headerRow will have reference to newly created ArrayList and the old one will be registered to garbage collection.

So, nullification is not required.

Also,

headerRow = new ArrayList<>(); // in JDK 7

rather than

headerRow = new ArrayList();

is a correct syntax for instantiation.

Upvotes: 3

Prasad Kharkar
Prasad Kharkar

Reputation: 13566

This is not required, It will refer to the newly created object. The variable headerRow will refer to the newly created ArrayList.

So you can directly use headerRow = new ArrayList();

Upvotes: 2

Related Questions