12
OctWebinar Alert : Mastering Manual and Automation Testing! - Reserve Your Free Seat Now
Java ArrayList is an important part of Java collection framework and a class of java.util package. It helps dynamic arrays and is built upon array data structure. Unlike in-built arrays, ArrayLists in Java don’t have a size limit. I.e., the ArrayLists in Java are resizable; in other words, these arrays can grow and shrink in real time when we add or remove elements.
Java ArrayList is comparatively slower than built-in arrays but could be of higher use in numerous array manipulation programs. The ArrayList in Java might contain duplicate elements. It deploys a List interface so that we can utilize each and every method of the interface there. The ArrayList in Java also manages the intersection order internally.
Java ArrayList inherits the AbstractList class and deploys the List interface. Some of the crucial points about the ArrayList are:
Online Java training will give you a strong foundation in Java and let you grow in your career. Let’s get started.
Java ArrayList is the resizable array or the implementation of List interface that grows automatically as requirement grow, so performance is always better in the case of the single-threaded environment. As the name implies, ArrayList in Java offers capabilities of a dynamic array where the size of an array isn’t fixed. Similarly, being a part of the Java Collection Framework, it contains several features unavailable with in-built arrays.
Syntax- public class ArrayList extends AbstractList Implements List, RandomAccess, Cloneable, java.io.Serializable
Java ArrayList
Example
How does it internally Work?
Java ArrayList could modify its size when adding or removing a new element. Inside, the real deployment of elements is plenty of complex work , still the fundamental idea behind how ArrayList in Java world when it gets full and we need to add new elements are described below.
When a Java ArrayList is created, its default capacity is 10 if not given or mentioned by the user. The capacity or the size of the ArrayList in Java increases based on the load factor and existing size.
Threshold = (Load Factor) * (Current Capacity)
For instance, if a user creates a Java ArrayList of capacity 10
Threshold = Load Factor * Current Capacity
= 0.75 * 10
≅ 7
Simply put, once a 7th element is added to the list, the capacity will grow as it reaches the threshold value. Inside a new Java ArrayList with a new size is developed, and the existing elements present in the old Java ArrayList are copied to the new Java ArrayList, as described below -
In Java 8 or in later versions, the new size of the ArrayList is determined to be 50% higher than its earlier capacity.
new_capacity = old_capacity + (old_capacity >> 1)
In the previous formula, the new size is determined as 50% higher than the earlier size. This place (old_capacity >> 1) gives us half the old size. Continue reading to learn more about how the right shift operator works -
For instance, if the size of an array is 10 and reaches the threshold value, we should increase its size to add new elements. The new size will be 10 + (10 >> 1) => 10 + 5 => 15. Thus the capacity is elevated from 10 to 15.
Important Note:
Even though ArrayList in Java provides scalability, this procedure levitates plenty of space and time. Because of this, selecting an earlier size at the same time and remembering the no. of anticipated elements in mind will be a smart strategy.
The default load factor value of the ArrayList, i.e., 0.75f, assures that the Java ArrayList always offers excellent performance with respect to time and space.
Key takeaway -
Let’s move on to the next section -
As discussed earlier, Java ArrayList is used for storing dynamic-sized collections of elements. Unlike built-in arrays with fixed sizes, an ArrayList's size grows automatically when a new element is added.
Let's have a look at a few important facts related to Java ArrayList –
In the next section, we’ll explore some of the important features of Java ArrayList
Besides the following features that allow us to create Java ArrayList, this class in Java also offers a fully grown function API that contains methods that can be utilized to manipulate objects in ArrayList.
Computational complexities of major Java ArrayList operations -
Now let's learn about the
The following diagram represents the hierarchy of a Java ArrayList where the array list increases the Abstract class, and then it deploys the List first, then collection and iterable objects at the end. The Java collection frameworks were non-generic prior to JDK 1.5, and afterward, they became generic.
Within a generic collection, you can state just a single type of element or object in the program.
Presently, it has become safe, so there is no requirement for typecasting. ArrayList created in the older version i.e. Non-Generic was as follows -
ArrayLists created in generic version -
Nowadays, data types used in modern ArrayLists are mentioned in angular braces. They’re required to store a specific kind of object only. If you try to add a new data type, it’ll indicate a compile-time error.
As Java ArrayList is a generic class, you can configure it with the help of any data type of your choice and the compiler will make sure that you cannot add Integer values in a collection of strings. Additionally, when accessing any element from the array list, you don’t have to cast them.
It contains three constructors majorly – ArrayList (), ArrayList (Collection c), and ArrayList (int initialCapacity).
ArrayList () – This is the most frequently used Java constructor that will return an empty array with a capacity of 10.
Syntax -
//Creating an object of ArrayList class //ArrayList created is empty, and its size is 10 by default. // It can hold elements of String class ArrayList arr = new ArrayList<>(); ArrayList (Collection c) – It creates an empty Java ArrayList using the initial size as given by the user.
Syntax
// Creating an ArrayList with initial capacity equal to 50. ArrayList arr = new ArrayList(50); ArrayList (int initialCapacity) – It creates a Java ArrayList and stores the elements that are present inside the collection list.
Syntax
// Creating an ArrayList with the elements that are present in the Collection list. List list = Arrays.asList(new String[]{"foo", "bar"}); List arr = new ArrayList<>(list);
There are plenty of methods that can be used along one array list. Here, we’ve listed only a few that are used frequently by programmers and necessary to learn by aspirants. Refer to our how-to-call method in Java to learn more about it.
Sr.No. |
Method & Description |
1 |
boolean add(E e) This method appends the particular element at the end of the list. |
2 |
boolean addAll(Collection c) This method appends all of the elements in the given collection to the end of the list, so that they’re returned by the specified collection's Iterator |
3 |
void clear() This method deletes all of the elements from the list. |
4 |
Object clone() This method returns a shallow copy of the ArrayList instance. |
5 |
boolean contains(Object o) This method returns true if the list consists of the specified element. |
6 |
void ensureCapacity(int minCapacity) This increases the capacity of this ArrayList. |
7 |
E get(int index) This method returns the element at the specified position in the list. |
8 |
int indexOf(Object o) This method returns the index of the first occurrence of the specified element in the list, or -1 if the list doesn’t contain the element. |
9 |
boolean isEmpty() This method returns true if the list contains no elements. |
10 |
Iterator This method returns an iterator over the elements in the list in the proper sequence. |
11 |
int lastIndexOf(Object o) This method returns the index of the last occurrence of the specified element in the list, or -1 if the list doesn’t contain the element. |
12 |
ListIterator This method returns a list iterator over the elements in the list in the proper sequence. |
13 |
E remove(int index) This method removes the element at the specified position in the list. |
14 |
boolean removeAll(Collection c) Removes from the list all of its elements that are contained in the specified collection. |
15 |
protected void removeIf(int fromIndex, int toIndex) This method Removes all of the elements of the collection that satisfy the given predicate. |
16 |
boolean retainAll(Collection c) Retains from the list all of its elements that are contained in the specified collection. |
17 |
E set(int index, E element) This method replaces the element at the specified position in this list with the specified element. |
18 |
int size() This method returns the number of elements in the list. |
19 |
Spliterator This method creates a late-binding and fail-fast Spliterator over the elements in the list. |
20 |
List This method returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. |
21 |
Object[] toArray() This method returns an array containing all of the elements in the list in the proper sequence (from first to last element). |
22 |
void trimToSize() This method trims the capacity of the ArrayList instance to be the list's current size. |
To add a new element in a Java ArrayList, you can use the add() method, which is overstuffed to carry out several operations depending on the various parameters, as follows -
// Java Program to Add elements to An ArrayList // Importing all utility classes import java.util.*; // Main class class GFG { // Main driver method public static void main(String args[]) { // Creating an Array of string type ArrayList al = new ArrayList<>(); // Adding elements to ArrayList // Custom inputs al.add("JanBask"); al.add("Training"); // Here we are mentioning the index // at which it is to be added al.add(0, "Hello"); // Printing all the elements in an ArrayList System.out.println(al); } } |
[Hello, JanBask, Training]
Once you add an element, if you want to change it, you can do it by using the set() method. As Java ArrayList is indexed, the specific element which you want to change is mentioned by the index of that element. Hence, this method gets the index and the updated element that is to be added at that position. Here’s an example-
import java.util.*;
class SetMethod { public static void main(String[] args) { ArrayList num = new ArrayList(); num.add(15); num.add(9); num.add(20); num.add(35); System.out.println("ArrayList num : " + num); //Replacing element present at 0th index with 40 num.set(0, 40); System.out.println("ArrayList num after updating : " + num); } }
ArrayList num : [15, 9, 20, 35]
ArrayList num after updating : [40, 9, 20, 35]
You can use the remove() method to remove an element from the Java ArrayList. This method is overwhelmed to carry out several operations depending on the various parameters as follows -
Here’s an example:
import java.util.*;
class RemoveMethod { public static void main(String[] args) { ArrayList colors = new ArrayList(); colors.add("red"); colors.add("orange"); colors.add("blue"); colors.add("pink"); colors.add("black"); colors.add("green"); System.out.println("ArrayList colors : " + colors); // removing element pink from the ArrayList colors.remove("pink"); System.out.println("ArrayList colors : " + colors); // removing 3rd element from the ArrayList colors.remove(2); System.out.println("ArrayList colors : " + colors); } }
ArrayList colors : [red, orange, blue, pink, black, green]
ArrayList colors : [red, orange, blue, black, green]
ArrayList colors : [red, orange, black, green]
There’re several ways to iterate through the Java ArrayList and the most commonly used methods are - the fundamental for loop in association with a get() method in order to get the object at a particular position and the advanced for loop. Here’s an example
import java.util.*;
public class ArrayListExample2{ public static void main(String args[]){ ArrayList list=new ArrayList();//Creating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); //Traversing list through Iterator Iterator itr=list.iterator();//getting the Iterator while(itr.hasNext()){//check if iterator has the elements System.out.println(itr.next());//printing the element and move to next } } }
Mango
Apple
Banana
Grapes
Let's see an example to iterate the Java ArrayList elements with the help of the for-each loop
import java.util.*;
public class ArrayListExample3{ public static void main(String args[]){ ArrayList list=new ArrayList();//Creating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); //Traversing list through for-each loop for(String fruit:list) System.out.println(fruit); } }
Mango
Apple
Banana
Grapes
The get() method returns an object at the particular index, whereas the set() method changes the object. Here’s an example:
import java.util.*;
public class ArrayListExample4{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add("Mango"); al.add("Apple"); al.add("Banana"); al.add("Grapes"); //accessing the element System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, because index starts from 0 //changing the element al.set(1,"Dates"); //Traversing list for(String fruit:al) System.out.println(fruit); } }
Returning element: Apple
Mango
Dates
Banana
Grapes
A utility class collections is provided by java.util package, which contains static method known as sort(), using which you can easily sort Java ArrayList. Here’s an example:
import java.util.*;
class SortArrayList{ public static void main(String args[]){ //Creating a list of fruits List list1=new ArrayList(); list1.add("Mango"); list1.add("Apple"); list1.add("Banana"); list1.add("Grapes"); //Sorting the list Collections.sort(list1); //Traversing list through the for-each loop for(String fruit:list1) System.out.println(fruit); System.out.println("Sorting numbers..."); //Creating a list of numbers List list2=new ArrayList(); list2.add(21); list2.add(11); list2.add(51); list2.add(1); //Sorting the list Collections.sort(list2); //Traversing list through the for-each loop for(Integer number:list2) System.out.println(number); } }
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Here’s an example of how ro add elements between two numbers-
// Java program to add the elements // between two numbers in ArrayList import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { ArrayList list.add(1); list.add(2); list.add(4); System.out.println(list); // insert missing element 3 list.add(2, 3); System.out.println(list); } } |
[1, 2, 4]
[1, 2, 3, 4]
You can use the size() method to find the length of a Java ArrayList.
Syntax:
size(): This method returns the no. of elements present in a Java ArrayList. Here’s an example: import java.util.*; class SizeMethodExample { public static void main(String[] args) { ArrayList colors= new ArrayList(); colors.add("red"); colors.add("orange"); colors.add("blue"); colors.add("pink"); // Printing elements System.out.println("colors : " + colors); // Printing the size of ArrayList System.out.println("Number of elements present in colors : " + colors.size()); } }
Number of elements present in colors : 4
**Important note:
The size of Java ArrayList doesn’t necessarily equal to its capacity.
You can use isEmpty() method to find out whether the ArrayList in Java is Empty.
Syntax:
public boolean isEmpty(): This method returns true if a Java ArrayList is empty. Here’s an example- import java.util.*; class IsEmptyMethod { public static void main(String[] args) { ArrayList num = new ArrayList<>(); num.add(1); num.add(2); // Printing elements System.out.println("ArrayList num : " + num); // Checking out if ArrayList is empty or not System.out.println("ArrayList is empty : " + num.isEmpty()); // Removing all the elements from the ArrayList num.clear(); // Checking out if ArrayList is empty or not after removing // all the elements System.out.println("ArrayList is empty : " + num.isEmpty()); } }
ArrayList num : [1, 2]
ArrayList is empty : false
ArrayList is empty : true
As mentioned above, Java ArrayLists aren’t synchronized, i.e., the list should be synchronized externally if a thread changes it structurally and several threads try to access it simultaneously.
Java ArrayList can be synchronized using the following methods -
It is important to remember that under this kind of synchronization, the iterator should be in a synchronized block, as shown in the following example
import java.util.*;
class SynchronizeExample { public static void main(String[] args) { List arr = new ArrayList(); // adding elements to the list arr.add("Hello"); arr.add("World"); arr.add("in"); arr.add("Java"); // Synchronizing the ArrayList externally using // synchronizedList() method arr = Collections.synchronizedList(arr); synchronized (arr) { // It should be in synchronized block Iterator it = arr.iterator(); // Iterating through the elements while (it.hasNext()) System.out.println(it.next()); } } }
Hello
World
in
Java
The following code shows how to synchronize ArrayList in Java externally using CopyOnWriteArrayList.
import java.io.*;
import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; class SynchronizeUsingCopyOnWriteArrayList { public static void main(String[] args) { // creating a thread-safe ArrayList using // CopyOnWriteArrayist. CopyOnWriteArrayList arr = new CopyOnWriteArrayList(); // Adding elements to synchronized ArrayList arr.add("Hello"); arr.add("World"); arr.add("in"); arr.add("Java"); System.out.println("Elements of synchronized ArrayList :"); // Iterating on the synchronized ArrayList using an iterator. Iterator it = arr.iterator(); while (it.hasNext()) System.out.println(it.next()); } }
Elements of synchronized ArrayList:
Hello
World
in
Java
The discussion is incomplete if you don’t know the differences between an array and an ArrayList in Java and which one to choose among the two. Here, both are compared on eight major points - performance, resizable, primitives, traversal, length, type safety, add elements, and multi-dimensional.
Resizable –
Performance –
Primitives –
Iteration – To iterate through the array list, an iterator is required. We can use either for loop or each loop to iterate through array elements.
Type Safety – In Java, safety is embedded through Generics. At the same time, array lists are a homogeneous data structure. Thus, it contains values of a particular data type only. If you try to store any different value, it will show the compile-time error, Java command not found, in that case.
Length – To give the size of an array list, use the size () method. Each array has a variable-sized object that will return the fixed length in the end.
Integer arrayobject[] = new integer[3]; Arraylength = arrayobject.length; //uses arrayobject length variable Arraylist arraylistobject = new arraylist(); Arraylistobject.add(12); Arraylistobject.size();
Add the Elements – To insert elements in the array list, add () method is used, and it will insert new elements in the list with the assignment operator.
Multi-dimensional – The array could be multi-dimensional, but array lists are always one-dimensional.
Both are useful for storing groups of objects. Earlier, we saw the difference between Java ArrayList and array. Let’s now explore the benefits of Java ArrayList over arrays -
With this discussion, we come to the end of this blog. Now you have enough information about ArrayList in Java and how to print the list and add or remove elements to an existing array list based on requirements. To know more, you should join the online Java training program for practical experience and be an established Java programmer.
1. What is a Java ArrayList?
Ans:- Java ArrayList is a part of the Collection framework, which is used for storing elements, and its size is resizable.
2. How is data stored in Java ArrayList?
Ans:- You can store data in Java ArrayList till the ArrayList size is full; after that, the size of ArrayList in Java is doubled if we need to store more elements.
3. Does Java ArrayList allow duplicates?
Ans:- Yes, Java ArrayList does allow duplicate values to be stored.
4. What ArrayList in Java is used for?
Ans:- ArrayList in Java is used for storing elements. When we’re not certain about the no. of elements to be stored but we also need to preserve their insertion order, we could use ArrayList.
5. Is Java ArrayList and List the same?
Ans:- No, they aren’t similar!
The List is an interface, whereas Java ArrayList is a class that deploys the List interface. An ArrayList in Java is a non-generic collection of objects, while a List is the generic version of the ArrayList; it contains elements of a particular type.
6. Is Java ArrayList a list or array?
Ans:- ArrayList is primarily a class in Java Collection Framework that deploys the List interface and depends upon the array data structure. Internally, it utilizes a backing array for storing elements or objects.
7. Which is faster, List or ArrayList in Java?
Ans:- Lists are faster as compared to ArrayLists in Java because it avoids boxing. A List doesn’t have to box the values added to them. In contrast, ArrayList only "accepts" objects. Thus it means when you add any object or any element to the ArrayList in Java, it’ll have to be boxed (completely), and then it has to be unboxed again (partially) whenever you need the values.
8. What is the objective of the Java course online?
Ans:- Our online Java training course aims to provide you with experiences similar to offline classrooms. It redeems you from the turmoil of traveling daily to the physical classes by incurring expenses, energy & time. It helps you complete Java discipline preparation by covering basic to advanced concepts, skills, and techniques required by Java certifications & job roles.
9. What skills will I learn in this best Java course online?
Ans:- Here’s a quick forecast of the skills/areas you will learn through our immersive & comprehensive Java online training course.
10. Can I get a free demo class for Java development certification courses?
Ans:- We do provide a Java course free online demo class for a quick roadmap of our Java certification training program. Our Java demo class aims to enlighten you with all the aspects we cover in our online Java certification training program.
FaceBook Twitter LinkedIn Pinterest EmailA dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
Receive Latest Materials and Offers on Java Course
Interviews