0% found this document useful (0 votes)
6 views13 pages

Arraylist in Java: Java Arraylist Is A Part of Collections Framework and It Is A Class of

Uploaded by

Sunil Mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Arraylist in Java: Java Arraylist Is A Part of Collections Framework and It Is A Class of

Uploaded by

Sunil Mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithrea

ArrayList in Java
Last Updated : 18 Nov, 2024

Java ArrayList is a part of collections framework and it is a class of


java.util package. It provides us with dynamic arrays in Java. Though, it
may be slower than standard arrays but can be helpful in programs
where lots of manipulation in array is required. The main advantage of
ArrayList is, unlike normal arrays, we don’t need to mention the size
when creating ArrayList. It automatically adjusts its capacity as
elements are added or removed.

Example:

Java

1 // Java Program to demonstrate ArrayList


2 import java.util.ArrayList;
3
4 class Main {
5 public static void main (String[] args) {
6
7 // Creating an ArrayList
8 ArrayList<Integer> a = new ArrayList<Integer
();
9
10 // Adding Element in ArrayList
11 a.add(1);
12 a.add(2);
13 a.add(3);
14
15 // Printing ArrayList
16 System.out.println(a);
17

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 1/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

18 }
19 }

Output

[1, 2, 3]

ArrayList in Java Visit Course

ArrayLists provide dynamic resizing, making them an essential tool in


Java for handling collections. To explore their full potential, including
best practices for performance optimization, the Java Programming
Course offers exercises and examples that will help you master
ArrayLists.

Table of Content
Syntax of ArrayList
Constructors in ArrayList in Java
Operations in ArrayList
Java ArrayList Methods

ArrayList is a Java class implemented using the List interface. Java


ArrayList, as the name suggests, provides the functionality of a dynamic
array where the size is not fixed as an array. Also, as a part of
Collections framework, it has many features not available with arrays.

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 2/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Syntax of ArrayList

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

Note: You can also create a generic ArrayList


Important Features of ArrayList in Java
ArrayList inherits AbstractList class and implements the List
interface.
ArrayList is initialized by size. However, the size is increased
automatically if the collection grows or shrinks if the objects are
removed from the collection.
Java ArrayList allows us to randomly access the list.
ArrayList can not be used for primitive types, like int, char, etc. We
need a wrapper class for such cases.
ArrayList in Java can be seen as a vector in C++.
ArrayList is not Synchronized. Its equivalent synchronized class in
Java is Vector.

Let’s understand the Java ArrayList in depth. Look at the below image:

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 3/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

In the above illustration, AbstractList, CopyOnWriteArrayList, and


AbstractSequentialList are the classes that implement the list interface.
A separate functionality is implemented in each of the mentioned
classes. They are:

1. AbstractList: This class is used to implement an unmodifiable list, for


which one needs to only extend this AbstractList Class and
implement only the get() and the size() methods.
2. CopyOnWriteArrayList: This class implements the list interface. It is
an enhanced version of ArrayList in which all the modifications(add,
set, remove, etc.) are implemented by making a fresh copy of the list.
3. AbstractSequentialList: This class implements the Collection
interface and the AbstractCollection class. This class is used to
implement an unmodifiable list, for which one needs to only extend
this AbstractList Class and implement only the get() and the size()
methods.

Constructors in ArrayList in Java

In order to Create an ArrayList, we need to create an object of the


ArrayList class. The ArrayList class consists of various constructors
which allow the possible creation of the array list. The following are the
constructors available in this class:

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 4/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Constructor Description Initialize and


Declare
ArrayList

ArrayList() This constructor is used to ArrayList arr =


build an empty array list. new ArrayList();

ArrayList(Collection This constructor is used to


c) build an array list initialized ArrayList arr =
with the elements from the new ArrayList(c);
collection c.

ArrayList(int This constructor is used to


capacity) build an array list with the ArrayList arr =
initial capacity being new ArrayList(N);
specified.

Operations in ArrayList
Now, Using the constructors we have got ArrayList for further
operations like Insertion , Deletion and Updation of the elements in
ArrayList.

Java

1 // Java Program Example to Demonstrate


2 // Addition, Deletion and Updation of Element
3 import java.util.*;
4
5 class Main {
6 public static void main(String args[]){
7
8 // Creating an Array of string type
9 ArrayList<String> al = new ArrayList<>();
10
11 // 1. Addition
12
13 // Adding elements to ArrayList

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 5/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

14 // at the end
15 al.add("Geeks");
16 al.add("Geeks");
17
18 System.out.println("Orignal List : "+al);
19
20 // Adding Elements at the specific
21 // index
22 al.add(1, "For");
23
24 System.out.println("After Adding element
at index 1 : "+ al);
25
26 // 2. Deletion of Element
27
28 // Removing Element using index
29 al.remove(0);
30
31 System.out.println("Element removed from
index 0 : "+ al);
32
33 // Removing Element using the value
34 al.remove("Geeks");
35
36 System.out.println("Element Geeks removed
: "+ al);
37
38 // 3. Updating Values
39
40 // Updating value at index 0
41 al.set(0, "GFG");
42
43
44 // Printing all the elements in an ArrayList
45 System.out.println("List after updation of
value : "+al);
46 }
47 }

Output

Orignal List : [Geeks, Geeks]


After Adding element at index 1 : [Geeks, For, Geeks]

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 6/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Element removed from index 0 : [For, Geeks]


Element Geeks removed : [For]
List after updation of value : [GFG]

Let us understand how the three operations performed in above


Program works.
1. Adding Elements in ArrayList
Adding elements seems bit complex when the size of ArrayList is not
defined:

Creates a bigger-sized memory on heap memory (for example


memory of double size).
Copies the current memory elements to the new memory.
The new item is added now as there is bigger memory available now.
Delete the old memory.

Set initial capacity when possible: Each time the list exceeds its
capacity, it resizes by 50%. This resizing can be costly.
Avoid Frequent Resizing: Each resize involves creating a new
array and copying all existing elements to it.

2. Changing Elements in ArrayList


After adding the elements, if we wish to change the element, it can be
done using the set() method. Since an ArrayList is indexed, the element
which we wish to change is referenced by the index of the element.
Therefore, this method takes an index and the updated element which
needs to be inserted at that index.
3. Removing Elements in ArrayList
In order to remove an element from an ArrayList, we can use the
remove() method. This method is overloaded to perform multiple
operations based on different parameters.

Java ArrayList Methods

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 7/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Method Description

add(int index, Object This method is used to insert a specific element at


element) a specific position index in a list.

This method is used to append a specific element


add(Object o)
to the end of a list.

This method is used to append all the elements


from a specific collection to the end of the
addAll(Collection C)
mentioned list, in such an order that the values
are returned by the specified collection’s iterator.

Used to insert all of the elements starting at the


addAll(int index,
specified position from a specific collection into
Collection C)
the mentioned list.

This method is used to remove all the elements


clear()
from any list.

This method is used to return a shallow copy of


clone()
an ArrayList in Java.

Returns true if this list contains the specified


contains(Object o)
element.

Increases the capacity of this ArrayList instance, if


ensureCapacity(int necessary, to ensure that it can hold at least the
minCapacity) number of elements specified by the minimum
capacity argument.

Performs the given action for each element of the


forEach(Consumer<?
Iterable until all elements have been processed or
super E> action)
the action throws an exception.

Returns the element at the specified position in


get(int index)
this list.

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 8/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Method Description

The index the first occurrence of a specific


indexOf(Object O) element is either returned or -1 in case the
element is not in the list.

isEmpty() Returns true if this list contains no elements.

The index of the last occurrence of a specific


lastIndexOf(Object
element is either returned or -1 in case the
O)
element is not in the list.

Returns a list iterator over the elements in this list


listIterator()
(in proper sequence).

Returns a list iterator over the elements in this list


listIterator(int index) (in proper sequence), starting at the specified
position in the list.

Removes the element at the specified position in


remove(int index)
this list.

Removes the first occurrence of the specified


remove(Object o)
element from this list, if it is present.

removeAll(Collection Removes from this list all of its elements that are
c) contained in the specified collection.

removeIf(Predicate Removes all of the elements of this collection


filter) that satisfy the given predicate.

removeRange(int Removes from this list all of the elements whose


fromIndex, int index is between fromIndex, inclusive, and
toIndex) toIndex, exclusive.

retainAll(Collection<? Retains only the elements in this list that are


> c) contained in the specified collection.

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 9/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Method Description

set(int index, E Replaces the element at the specified position in


element) this list with the specified element.

size() Returns the number of elements in this list.

Creates a late-binding and fail-fast Spliterator


spliterator?()
over the elements in this list.

subList(int Returns a view of the portion of this list between


fromIndex, int the specified fromIndex, inclusive, and toIndex,
toIndex) exclusive.

This method is used to return an array containing


toArray()
all of the elements in the list in the correct order.

It is also used to return an array containing all of


toArray(Object[] O) the elements in this list in the correct order same
as the previous method.

This method is used to trim the capacity of the


trimToSize()
instance of the ArrayList to the list’s current size.

Some Key Points of ArrayList in Java

1. ArrayList is Underlined data Structure Resizable Array or Growable


Array.
2. ArrayList Duplicates Are Allowed.
3. Insertion Order is Preserved.
4. Heterogeneous objects are allowed.
5. Null insertion is possible.

Complexity of Java ArrayList

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 10/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Operation Time Complexity Space Complexity

Inserting Element in
O(1) O(N)
ArrayList

Removing Element
O(N) O(1)
from ArrayList

Traversing Elements
O(N) O(N)
in ArrayList

Replacing Elements in
O(1) O(1)
ArrayList

Below are the advantages and disadvantages of using ArrayList in Java:

Advantages of Java ArrayList

Dynamic size: ArrayList can dynamically grow and shrink in size,


making it easy to add or remove elements as needed.
Easy to use: ArrayList is simple to use, making it a popular choice for
many Java developers.
Fast access: ArrayList provides fast access to elements, as it is
implemented as an array under the hood.
Ordered collection: ArrayList preserves the order of elements,
allowing you to access elements in the order they were added.
Supports null values: ArrayList can store null values, making it
useful in cases where the absence of a value needs to be
represented.

Disadvantages of Java ArrayList

Slower than arrays: ArrayList is slower than arrays for certain


operations, such as inserting elements in the middle of the list.

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 11/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Increased memory usage: ArrayList requires more memory than


arrays, as it needs to maintain its dynamic size and handle resizing.
Not thread-safe: ArrayList is not thread-safe, meaning that multiple
threads may access and modify the list concurrently, leading to
potential race conditions and data corruption.
Performance degradation: ArrayList’s performance may degrade as
the number of elements in the list increases, especially for operations
such as searching for elements or inserting elements in the middle of
the list.

FAQs of ArrayList in Java

How is ArrayList different from an Array in Java?

An ArrayList can resize dynamically, while a traditional array has a


fixed size. ArrayList also provides many useful methods like add(),
remove(), and size().

How to Access elements in an ArrayList?

Elements can be accessed using the get() method:


String element = list.get(0);

How to Remove an element from an ArrayList?

Use the remove() method to remove elements by index:


list.remove(0);

Is ArrayList Synchronized?

No, ArrayList is not synchronized. Use


Collections.synchronizedList(new ArrayList<>()) for thread-safe
operations.

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 12/18
12/24/24, 7:17 PM ArrayList in Java - GeeksforGeeks

Can we Store null elements in an ArrayList?

Yes, ArrayList can store null elements.

How is data stored in ArrayList?

ArrayList can store data till the ArrayList size is full, after that the
size of ArrayList is doubled if we want to store any more
elements.

Want to be a master in Backend Development with Java for building


robust and scalable applications? Enroll in Java Backend and
Development Live Course by GeeksforGeeks to get your hands dirty
with Backend Programming. Master the key Java concepts, server-side
programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or
want to be a Java Pro? This course equips you with all you need for
building high-performance, heavy-loaded backend systems in Java.
Ready to take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.

Comment More info Next Article


Vector Class in Java

Similar Reads
ArrayList vs LinkedList in Java
An array is a collection of items stored at contiguous memory locations.
The idea is to store multiple items of the same type together. However,…
5 min read

https://www.geeksforgeeks.org/arraylist-in-java/?ref=next_article 13/18

You might also like