ArrayList in java

ArrayList in java is one of the most important parts of the Collection framework. It is the collection that is widely used in programs. Before moving further we will recommend you please read Array in java, because that will help you to understand the concept of ArrayList. In this post, we will discuss what is the java ArrayList class and how we can use it.

Here is the table content of the article we will cover these topics.

1. What is ArrayList in java?
2. Important points about ArrayList in java?
3. Creating an ArrayList in java?
4. How to Initialize arraylist java?

5. The default size of ArrayList in java?
6.
Internal working of ArrayList in java?
7. Best practices to create an ArrayList
8.
How to add elements to an ArrayList?
9. How to replace element in an ArrayList?
10. How to remove elements from an ArrayList?
11. How to access elements from an ArrayList?
12. How to get index of object in ArrayList java?
13. How to Iterate an ArrayList?
14. How to get subList from ArrayList?
15. How to achieve Java sort ArrayList?

16. How to Convert list to array in java?
17. How to convert array to list java?
18. Java ArrayList methods?

19. How to remove duplicates from ArrayList?
20. Difference between ArrayList and array?

21. Difference between ArrayList and LinkedList?
22. Immutable List in Java?
23 CopyOnWriteArrayList in java

24. Performance comparison of ArrayList with for loop and iterator in java?

What is ArrayList in Java?

The ArrayList class is a part of the Java Collection Framework that implements the List interface and extends the AbstractList class. It also implements the Cloneable, RandomAccess, and Serializable interfaces.

arraylist in java

As we have seen the ArrayList class implements the List interface, which means it inherits all the properties from the List interface. An ArrayList is a part of the collection framework that can store any number of elements/objects. Basically, ArrayList is a growable array, unlike Array, it doesn’t have a fixed length. It means the size of the ArrayList can grow or shrink automatically when the object is added or removed. The ArrayList uses the index to store elements like Array. We will read how Arraylist increases or decreases size automatically.

Important points about ArrayList 

1. Like Array, ArrayList also work based on an index. Each element store at a particular position. We can add, get, and remove the element by use of index value.

2. ArrayList can contain duplicate elements Because it stores each element at a particular position by use of the index. So it doesn’t care whether the element is already present in ArrayList or not.

3. It maintains the order of insertion because each element is inserted on its index value.
For example: If you are adding any element in ArrayList in the First position (it means index value 0). So, you can get it anywhere in the program by the use of index value 0, It doesn’t change automatically.

4. An ArrayList can contain any number of null values. In java, some collections are not allowed null like TreeSet.

5. By default, the ArrayList class is non-synchronized. It means multiple threads can access it at the same time. We can make it synchronized by using the synchronized keyword or we can use CopyOnWriteArrayList for multithreading.

6. The initial default capacity of ArrayList is 10.

7. The ArrayList always uses for non-primitive data types. We can’t be used for primitive types (like int, char, etc).
8. Java ArrayList allows us to randomly access the list. We can get any element from ArrayList based on the index value.

Creating an ArrayList in java?

To create an ArrayList we can use the different constructors of ArrayList. As we know ArrayList class is generic in java so we need to provide the data type. Let’s see how to create arraylist java and how to add elements in ArrayList.

There are three constructors that are used to create an ArrayList. We will cover all three constructors and also see the difference.
ArrayList() – Create ArrayList with default capacity
ArrayList(size) – Create an ArrayList of a specific size
ArrayList(Collection) – Creating an ArrayList from another collection

ArrayList()

The default constructor uses to create the default size of ArrayList in java. The ArrayList default size is 10.

ArrayList<E> nameOfArratList = new ArrayList<E>();
ArrayList<String> names = new ArrayList<String>();

Here names denote the name of ArrayList that can store elements of String type. Here we are using the default constructor of ArrayList to create an ArrayList. The ArrayList default size is 10 but it increases when we add elements.

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

class ArrayListExample {

    public static void main(String[] args) {
        // Creating list using the ArrayList class
        List<Integer> arrayListNumber = new ArrayList<Integer>();

        // Add elements to the list
        arrayListNumber.add(123);
        arrayListNumber.add(456);
        arrayListNumber.add(789);
        System.out.println("List: " + arrayListNumber);
    }
}

Output: List: [123, 456, 789]

ArrayList(int capacity)

A parameterized constructor of the ArrayList class that takes an int type of value. It is used to create an empty ArrayList with the specified capacity.

ArrayList<E> NameOfArrayList =  new ArrayList<E>(intValue);

Where E represents the type of elements in ArrayList.
IllegalArgumentException, if the initial capacity is less than zero

ArrayList<String> listOfNames =  new ArrayList<String>(5);

Let’s say you want to create an ArrayList and specify its capacity. If you already know about your data capacity it would be better to declare an ArrayList with capacity.

import java.util.ArrayList;

public class ExampleOfArrayList 
{
        public static void main(String[] args) 
	{
		ArrayList<String> listOfNames = new ArrayList<String>(5);
		listOfNames.add("JAVA");
		listOfNames.add("GOAL");
		listOfNames.add("JAVA");
		listOfNames.add("GOAL");
                for(String name : listOfNames)
			System.out.println(name);
	}
}

Output: JAVA
GOAL
JAVA
GOAL

ArrayList(Collection c)

It uses to create an ArrayList containing the elements in the specified collection. The ArrayList creates with default initial capacity enough to contain the elements in the specified collection.

ArrayList<E> NameOfArrayList = new ArrayList<E>(collectionName);

represents the type of elements in ArrayList.ArrayList<String> listOfNames2 = new ArrayList<String>( listOfNames);

Let’s say you want to create an ArrayList by use of an existing collection:

import java.util.ArrayList;
public class ExampleOfArrayList 
{ 
	public static void main(String[] args) 
	{ 
		ArrayList<String> listOfNames = new ArrayList<String>(); 
		listOfNames.add("JAVA"); 
		listOfNames.add("GOAL"); 
		listOfNames.add("SITE"); 
		ArrayList<String> listOfNames2 = new ArrayList<String>(listOfNames); 
		for(String name : listOfNames2) 
			System.out.println(name); 
	}
}

Output:JAVA
GOAL
SITE

How to Initialize ArrayList java?

We can initialize the ArrayList at the time of creation or after creation. Let’s see how we can initialize the ArrayList in java.

ArrayList<data_type>arraylistName = new ArrayList<data_type>()
{{
	add(Object o1); 
        add (Object o2);
        …
	add (Object n);
}};

Here you can see, we can add the elements in ArrayList during the creation of ArrayList.

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

class ArrayListExample {

    public static void main(String[] args) 
    {
    	ArrayList<String> arraylistName = new ArrayList<String>()
    	{{
    		add("Hi"); 
            add("Hello");
            add("Bye");
    	}};
    	
    	System.out.println("Elements of ArrayList : "+arraylistName);
    }
}

Output: Elements of ArrayList : [Hi, Hello, Bye]

Internal working of ArrayList in java

In this section, we will see how ArrayList increases or decrease the length and Internal working of ArrayList in java

The default size of ArrayList in java

When we create an ArrayList by default constructor of ArrayList class, then JVM creates an ArrayList in heap memory with the default size of ArrayList in java. The default size of ArrayList in java is 10. But an ArrayList is a growable array, unlike an array it doesn’t have a fixed length. It increases the size dynamically whenever we add or remove any element in ArrayList.

ArrayList<Integer> list = new ArrayList<Integer>();
Internal working of ArrayList in java

We can initialize the capacity of ArrayList during the creation of ArrayList. The ArrayList class provides a constructor that takes capacity as an integer value. Suppose we want to create an ArrayList with capacity 15.

ArrayList<Integer> list = new ArrayList<Integer>(15);
Internal working of ArrayList in java

But it can take more than 15 elements because when we add an element it will automatically increase itself. Let’s see it with an example.

import java.util.ArrayList;
public class ArrayListExample
{  
   public static void main(String args[])
   {  
	   ArrayList<Integer> list = new ArrayList<Integer>();
	   for(int i = 0; i < 20; i++)
		   list.add(i);
	   
	   System.out.println("Elements from ArrayList: "+ list);
  }  
}

Output: Elements from ArrayList: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Internal working of ArrayList in java?

The size of ArrayList grows automatically which is fully based on load factor and current capacity. Basically, the load factor is the measure that decides when to increase the capacity of the ArrayList. The default load factor of an ArrayList is 0.75f.

ArrayList increases the capacity after each threshold. Now the question arises how the threshold is calculated?

Threshold = (Current Capacity) * (Load Factor)

For example, if the ArrayList has 10 elements and a load factor of 0.75f, then the threshold will be,

Threshold = 10 * 0.75 = 7

Let’s take an example and understand how ArrayList grows in memory. Suppose we have an ArrayList with a default capacity of 10. We can add more than 10 elements in ArrayList.
Whenever we perform add operation, it checks whether the threshold value is equal to the number of elements present in ArrayList. If the size of the current element is greater than the threshold. The JVM creates a new ArrayList and copies the old ArrayList into the new one. It creates the ArrayList size 10 to 20.

Internal working of ArrayList in java

Best practices to create an ArrayList

Whenever ArrayList reaches its threshold, it creates a new ArrayList object with a new capacity and copies all old elements from the old ArrayList to a new object. This process is space and time-consuming even though it provides flexibility. So, It would be good practice if we choose the initial capacity, by keeping the number of expected elements in mind.

We should take care of this while choosing the load factor. The ArrayList has a default load factor of 0.75f and always gives the best performance in terms of both space and time.

Performance comparison of ArrayList with for loop and iterator in java?

In Java, both the for loop and iterator can be used to iterate over an ArrayList, but the performance of these two approaches depends on the size of the ArrayList.

A for loop is simple to use and provides easy access to elements by index. However, when the ArrayList is large, using the for loop can result in performance degradation. This is because the for loop uses the size() method of the ArrayList to check the size of the ArrayList every time, which can be expensive for large ArrayLists.

On the other hand, an iterator provides a more efficient way to iterate over an ArrayList. It avoids calling the size() method and has its own hasNext() and next() methods to access the elements of the ArrayList. This can result in faster execution, especially for large ArrayLists.

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

public class ArrayListIterationExample {

    public static void main(String[] args) {

        // Create an ArrayList of 10 million integers
        ArrayList<Integer> numbers = new ArrayList<>();
        for (int i = 0; i < 10000000; i++) {
            numbers.add(i);
        }

        // Measure execution time of for loop
        long startTime1 = System.nanoTime();
        for (int i = 0; i < numbers.size(); i++) {
            int num = numbers.get(i);
        }
        long endTime1 = System.nanoTime();
        long duration1 = (endTime1 - startTime1);
        System.out.println("For loop execution time: " + duration1 + " nanoseconds.");

        // Measure execution time of iterator
        Iterator<Integer> iterator = numbers.iterator();
        long startTime2 = System.nanoTime();
        while (iterator.hasNext()) {
            int num = iterator.next();
        }
        long endTime2 = System.nanoTime();
        long duration2 = (endTime2 - startTime2);
        System.out.println("Iterator execution time: " + duration2 + " nanoseconds.");
    }

}

Output: For loop execution time: 24957700 nanoseconds.
Iterator execution time: 26535300 nanoseconds.

In this example, we create an ArrayList of 10 million integers and measure the execution time of iterating over the ArrayList using both a for loop and an iterator. We use the System.nanoTime() method to measure the execution time in nanoseconds.

When we run the program, we can see that the execution time of the for loop is significantly longer than the iterator. This is because the for loop needs to call the size() method for each iteration, which becomes more expensive as the size of the ArrayList increases. In contrast, the iterator does not need to call the size() method and only needs to check whether there are more elements using the hasNext() method.

In summary, if performance is a concern and the ArrayList is large, it is better to use an iterator instead of a for loop. However, for smaller ArrayLists or when accessing elements by index is necessary, a for loop may be a better option.

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.