Java ArrayList is a better version of an array where it internally uses an array to store story elements and provides us with the flexibility to resize the list size internally after adding a new element.
ArrayList is a class that implements the List interface and belongs to java.util.ArrayList package.
In an ArrayList, all elements are stored in contiguous locations like arrays.
An ArrayList maintains the insertion order of elements.
The ArrayList size dynamically grows and shrinks. ArrayList also allows us to store and perform different actions on the stored data. It allows us to store all types of data as well as null values.
ArrayList can not be defined using primitive data types such as int, char, float, boolean etc. We need to use wrapper class for the same.
ArrayList is not thread-safe. Hence, it is not synchronized.
List<String> list = new ArrayList<String>();
The above expression will create an array list of type “String”. String and null value can be added in this ArrayList.
Similarly, we can create a list to store data of type int.
List<Integer> list = new ArrayList<Integer>();
Below are the three constructors defined to create ArrayList.
ArrayList list = new ArrayList();
ArrayList list = new ArrayList(Collection c);
ArrayList list = new ArrayList(int capacity);
Below are the list of methods supported by ArrayList class to perform different operations.
Add element in list at specific location or index using add() method:
list.add(1, "first");
list.add(2, "second");
Update element in list at specific location or index using set() method:
list.set(1, "first");
We can use remove() method to remove element from the list:
list.remove("second");
remove element in list from specific location or index using remove() method:
list.remove(1);
Below is the example to understand some of the methods which are defined in ArrayList class.
Please read out the comments also to get better understanding of below given code snippet.
OUTPUT:
Collections class provide us the capability to sort Array list elements alphabetically.
size(): The size() method will return the number of elements present in the list.
clear(): The clear() method will make list empty and remove all the elements from list.
contains(): The contains() method check either the particular element is exist or not in the list.
isEmpty(): returns true if we don’t have any element in the list.
Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.
📝 Blogs
javadoubts.com © All rights reserved