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" ???
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.
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.
Primitive data types cannot be stored in ArrayList but can be in Array. ArrayList is a kind of List and List implements Collection interface.
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.
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).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With