DEV Community 👩‍💻👨‍💻

Hari Krishna E
Hari Krishna E

Posted on

Java Collections

ArrayList is Collection in java.util package which extends AbstractList class and implements List Interface.
It also implements RandomAccess,Cloneable and Serializable interfaces
RandomAccess ,Cloneable and Serializable interfaces doesnot have any methods to implement.
They are to say that ArrayList can be accessed random with constant time and we can use the clone() method and it can be Serializable

When we add new element for the first time it will have the initial capacity of 10 and then the element will be added.
ArrayList has grow() method which will be called when we start adding more element Arrays.copyOf(elementData,newCapacity) will be returned with the updated Array.
Method in ArrayList :

private void grow(int minCapacity) {

It checks the range so in case the index that we pass exceeds the size it throws IndexOutOfBoundException.
Method in ArrayList

private void rangeCheck(int index) {

It has clear method which will loop through each index and set the value to null and let GC take care of it and set the size to 0.

Method in ArrayList

public void clear() {

writeObject and readObject methods help for Serialization and Deserialization.
Methods in ArrayList
`
private void writeObject(java.io.ObjectOutputStream s){

private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
`

Example to add elements in ArrayList and iterate in multiple ways

package com.corejava.oops.collections;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListTest {

    public static void main(String[] args) {


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

        test.add("Tester1"); //index - 0
        test.add("Tester2"); //index - 1
        test.add("Tester3"); //index - 2
        test.add("Tester4"); //index - 3


        for(int i=0;i<test.size();i++) {

            System.out.println("In For Loop :" +test.get(i));

        }

        for(String a : test) {

            System.out.println("In Enhanced for loop : "+a);

        }

        Iterator<String> it = test.iterator();

        while(it.hasNext()) {
            System.out.println("In While Loop :" + it.next());

        }

        test.stream().forEach(System.out::println);

    }

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

DEV has this feature:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠