Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ArrayList actually stores - References to objects or actual objects?

Tags:

java

arraylist

Suppose my code goes like this:

ArrayList list = new ArrayList();
Student s = new Student();    // creating object of Student class

myList.add(s);      // Here am confused ...

/* myList contains just the reference variable to the Student object, OR

   myList contains the actual Student object (memory allocation for name, rollNo etc)  ??   
*/

In Short when adding objects to ArrayList using add():

ArrayList is a list of "References to objects" or its a list of "actual objects" ???

like image 779
Mustafa Avatar asked Sep 17 '13 16:09

Mustafa


People also ask

What does an ArrayList store?

ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.

Can ArrayList only store objects?

Basics of ArrayLists ArrayList<String> B = new ArrayList<String>(); A fundamental limitation of ArrayLists is that they can only hold objects, and not primitive types such as ints. To retrieve items from an ArrayList, use the get() method.

Does ArrayList store primitive types or reference types or both?

Primitive data types cannot be stored in ArrayList but can be in Array. ArrayList is a kind of List and List implements Collection interface.

How is ArrayList stored in memory?

ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space. This is why retrieving an element from an ArrayList is so fast: given the location of the start of the ArrayList, you can know exactly where any element is located in memory.


2 Answers

Objects within the ArrayList themselves are stored on the heap. The ArrayList simply provides references to those objects and the ArrayList instance is also on the heap.

Object references, at the end of the day, are simply addresses to locations within memory where the object is stored. Hence, the ArrayList contains arrays of references to objects stored on the heap (or in memory).

like image 136
blackpanther Avatar answered Oct 20 '22 14:10

blackpanther


In Java, you never pass around actual objects. You are always dealing with a reference, which is essentially just an address to a location within memory where your object is stored.

Since you never work with actual objects, ArrayLists contains arrays of references to objects stored somewhere else (a place in memory called the heap).

like image 31
Johan Henriksson Avatar answered Oct 20 '22 12:10

Johan Henriksson