Home > Blockchain >  Variable ArrayList and Object ArrayList main difference?
Variable ArrayList and Object ArrayList main difference?

Time:08-13

I wonder, What is the main difference between these, especially location of memory. Where does stand into memory heap,stack . . . ? I mean, when I declared one of them Will I able to use same way or is there a remarkable difference on memory or on code snippets. Coders use as variable arraylist sometimes If I declare always as object what happened What will I gain or loss ?

I am really really confusing.

ArrayList<Integer> mylist;
ArrayList<Integer> mylist = new ArrayList<>();

CodePudding user response:

The variable declaration without initialization (ArrayList<Integer> mylist;) does only take 8 bytes on the stack for the reference (on 64 bit systems).

The initialized variable (ArrayList<Integer> mylist = new ArrayList<>();) effectively creates and points to a new object (the ArrayList). So in addition to the 8 bytes of stack memory, that referenced object takes up some heap memory (I don't know exactly how much that is. I would guess some 50 bytes or so - see What is the memory consumption of an object in Java? for details).

CodePudding user response:

ArrayList<Integer> mylist; isn't intialised - it would point to null and trying to access that array will cause Java to complain about that being a null. It's as if that element doesn't exist at all.

ArrayList<Integer> mylist = new ArrayList<>(); is an empty dynamic array. You can work with that as normal like any other object.

TLDR; it's not about whether they are in the heap or stack - one of them is a null (i.e, useless), while the other is a fully working, but empty, array.

  • Related