Java Arraylist is datastructure used to store elements/objects in java. This object can be of same or different type depending on the declaration of arrayList. ArrayList is part of collection framework of java.util
package of java. It is an implementation of List
interface of java which inturn implements Collection
and Iterable
.
Table of Contents
Important points about Java ArrayList
- ArrayList in java was introduced in 1.2 version of java as part of the collection framework.
- ArrayList is a class of java which
extends
AbstractList
class which inturn implementsList
interface as shown in diagram. - Java ArrayList can be used to store heterogenous or homogenous elements.
- ArrayList can grow its size dynamically as its made up of dynamic array.
- Java ArrayList maintains the order of insertion elements.
- ArrayList is randomly accessible as it
implements RandomAccess Interface.
ArrayList
cannot be declared of primitive type (int, long etc). It should be declared using Wrraper classes such asInteger
orLong
Wrong Way :
ArrayList<int> list = new ArrayList();
Correct Way:
ArrayList<Integer> list = new ArrayList();
ArrayList
in java can contain duplicate elements.ArrayList
class in java is not synchronized.- You can Synchronize given array list using
Collections.synchronizedList
List list = Collections.synchronizedList(new ArrayList(...));
ArrayList
are more efficient thanLinkList
while searching an element in the list but are non-efficient thanLinkList
when it comes to insertion and deletion of an element in between the list.ArrayList
works on anindex-based
system that means you can get/delete/add an element at its specific index just like an array.
Now, Let’s learn some technicality of ArrayList in java.
ArrayList Construtors
ArrayList provide 3 constructor.
ArrayList()
It will create a ArrayList of initial size of 10
//create a new list of default size 10 List<Integer> list = new ArrayList<>();
ArrayList(Collection<? extends E> c)
It will create a new ArrayList form the element returned from given collection and order of the element will be in order they are returned from collection’s iterator
List<Integer> list = new ArrayList<>(); //creates a newList with all the elements from list List<Integer> newList = new ArrayList<>(list);
ArrayList(int initialCapacity)
creates a List of size initialCapacity.
//creates a list of initial capacity of 20 List<Integer> list = new ArrayList<>(20);
ArrayList Methods
How to add element to ArrayList in java?
ArrayList in java provides variants of ways to add elements in java.
boolean add(E e) | Adds given element e to ArrayList |
void add( int index, E element) | Add element at given index in given arraylist. If elements exists at given index then will replace it with element. |
addAll(Collection <? extends E>c) | Add all collection to ArrayList in java. |
addAll(int index, Collection <? extends E> c | Add all collection elements to given arraylist at index starting from index |
Examples for adding elements to ArrayList in java
package com.techijournal.collection; import java.util.ArrayList; import java.util.List; public class MyArrayList { public static void main(String atgs []) { arrayListExample(); } private static void arrayListExample() { //Creating a arraylist of default size i.e 10 List<Integer> defaultList = new ArrayList<>(); //Creating a ArrayList of capacity 5 List<Integer> listOfCapaciyFive = new ArrayList<>(5); //Example for add() defaultList.add(33); defaultList.add(54); defaultList.add(66); defaultList.add(12); System.out.print("printing elements of defaultList"); System.out.println("defaultList elements are :"+defaultList); System.out.print("Creating ArrayList from existing list"); List<Integer> listFromExistingList = new ArrayList<Integer>(defaultList); System.out.println("printing element of listFromExistingList"); System.out.println("listFromExistingList elements are : " + listFromExistingList); System.out.println("adding element at index 3 in listFromExistingList"); listFromExistingList.add(3,454); System.out.println("listFromExistingList elements after update are : " + listFromExistingList); System.out.println("Adding listFromExistingList to listOfCapaciyFive"); listOfCapaciyFive.addAll(listFromExistingList); System.out.println("listOfCapaciyFive elements are :"+listOfCapaciyFive); System.out.println("Adding defaultList to listOfCapaciyFive at index 4"); listOfCapaciyFive.addAll(4,defaultList); System.out.println("listOfCapaciyFive elements are :"+listOfCapaciyFive); } }
OUTPUT: printing elements of defaultListdefaultList elements are :[33, 54, 66, 12] Creating ArrayList from existing listprinting element of listFromExistingList listFromExistingList elements are : [33, 54, 66, 12] adding element at index 3 in listFromExistingList listFromExistingList elements after update are : [33, 54, 66, 454, 12] Adding listFromExistingList to listOfCapaciyFive listOfCapaciyFive elements are :[33, 54, 66, 454, 12] Adding defaultList to listOfCapaciyFive at index 4 listOfCapaciyFive elements are :[33, 54, 66, 454, 33, 54, 66, 12, 12]
Removing or Deleting Elements from ArrayList in Java
ArrayList provides different methods to delete or remove elements from the list. These methods are listed bellow.
E remove(int index) | Removes an element from the given index in ArrayList. And returns the removed element. |
boolean remove(Object o) | Removes given Object from ArrayList if present. If removal is successful returns true or else false |
boolean removeAll(Collection<?> c) | Removes all elements of given collection c from ArrayList. And return true is operation is successful |
boolean removeIf( Predicate<? super E> filter) | Removes all elements from ArrayList that satisfies the given predicate. |
protected void removeRange( int fromIndex, int toIndex) | Removes from this list all of the elements whose index is between fromIndex , inclusive, and toIndex , exclusive. |
void clear() | Clear all elements of the ArrayList. |
Object retainAll(Collection c) | Remove all elements other than elements in collection c |
Deleting an element from ArrayList using remove(int index)
List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("Removing element from list using list.remove(index)"); String removedElement = list.remove(3); System.out.println(removedElement+" is element was present at index 3 got removed");
Remove Object element from ArrayList using remove(Object o)
List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("Removing element using list.remove(object)"); list.remove("US"); //returns boolean if successful
Remove an element from ArrayList using remove(Collection c)
list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Re-Initializing List with elements :"+ list); List<String> listToRemoved = new ArrayList<>(); listToRemoved.add("US"); listToRemoved.add("India"); System.out.println("List to be removed from list is "+ listToRemoved); System.out.print("Removing elements from arraylist using list.remove(collection)"); list.removeAll(listToRemoved);
Removing an element from ArrayList using removeIf(Predicte p)
list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Re-Initializing List with elements :"+ list); System.out.println("Removing elements from list using predicate i.e using list.removeIf(predicate)"); list.removeIf(s-> s.equals("Rome") || s.equals("India")); System.out.println("List after removing is "+ list);
Remove all element from ArrayList using clear()
list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Remvoing all elements using list.clear()"); list.clear(); System.out.print("List after calling clear is "+list);
Using retainAll( Collection c)
to remove elements in ArrayList
We can use reatinAll()
method to retain all elements of the passed collection and remove all other collection.
list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("removing elements from list using list.retainAll()"); System.out.println("Re-Initializing List with elements :"+ list); List<String> listToRetain = new ArrayList<>(); listToRetain.add("US"); listToRetain.add("India"); System.out.println(" List to retain is :"+ list); list.retainAll(listToRetain); System.out.println("Now, updated list is "+ list);
Example Code for Removing an Element from ArrayList
package com.techijournal.collection; import java.util.ArrayList; import java.util.List; public class MyArrayList { public static void main(String atgs []) { remove(); } private static void remove() { List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("Removing element from list using list.remove(index)"); String removedElement = list.remove(3); System.out.println(removedElement+" is element was present at index 3 got removed"); System.out.println("Removing element using list.remove(object)"); list.remove("US"); //returns boolean if successful System.out.println("US object got removed"); list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Re-Initializing List with elements :"+ list); List<String> listToRemoved = new ArrayList<>(); listToRemoved.add("US"); listToRemoved.add("India"); System.out.println("List to be removed from list is "+ listToRemoved); System.out.print("Removing elements from arraylist using list.remove(collection)"); list.removeAll(listToRemoved); System.out.println("List after removing collection "+ listToRemoved+ " is "+ list); list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Re-Initializing List with elements :"+ list); System.out.println("Removing elements from list using predicate i.e using list.removeIf(predicate)"); list.removeIf(s-> s.equals("Rome") || s.equals("India")); System.out.println("List after removing is "+ list); System.out.println("Remvoing all elements using list.clear()"); list.clear(); System.out.println("List after calling clear is "+list); list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("removing elements from list using list.retainAll()"); System.out.println("Re-Initializing List with elements :"+ list); List<String> listToRetain = new ArrayList<>(); listToRetain.add("US"); listToRetain.add("India"); System.out.println(" List to retain is :"+ list); list.retainAll(listToRetain); System.out.println("Now, updated list is "+ list); } }
Output of above code :
Initial List :[US, China, India, Rome, Cannada] Removing element from list using list.remove(index) Rome is element was present at index 3 got removed Removing element using list.remove(object) US object got removed Re-Initializing List with elements :[US, China, India, Rome, Cannada] List to be removed from list is [US, India] Removing elements from arraylist using list.remove(collection)List after removing collection [US, India] is [China, Rome, Cannada] Re-Initializing List with elements :[US, China, India, Rome, Cannada] Removing elements from list using predicate i.e using list.removeIf(predicate) List after removing is [US, China, Cannada] Remvoing all elements using list.clear() List after calling clear is [] removing elements from list using list.retainAll() Re-Initializing List with elements :[US, China, India, Rome, Cannada] List to retain is :[US, China, India, Rome, Cannada] Now, updated list is [US, India]
Fetching/Getting Elements from ArrayList
ArrayList in java only two methods required to fetch elements from list. those are
E get( int index) | It returns the element from the given index of the list. |
List<E> subList( int from index, int toIndex) | Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive. |
Example : Code for fetching element from ArrayList
package com.techijournal.collection; import java.util.ArrayList; import java.util.List; public class MyArrayList { public static void main(String atgs []) { fetchingElement(); } private static void fetchingElement() { List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("fetching element from list using list.get(index)"); System.out.println("Element at index 3 of list is : "+list.get(3)); System.out.println("fetching element from list using list.sublist(fromIndex, toIndex)"); System.out.println("Element from index 1 to index 3 of list is : "+list.subList(1, 3)); } }
Output for above code:
Initial List :[US, China, India, Rome, Cannada] fetching element from list using list.get(index) Element at index 3 of list is : Rome fetching element from list using list.sublist(fromIndex, toIndex) Element from index 1 to index 3 of list is : [China, India]
Iterating ArrayList in Java
Java provide multiple way to Iterate ArrayList. like
- We can use
for
loop for iterating in ArrayList - Or from Java 8, ArrayList provides
forEach()
to iterate. Iterator()
orlistIterator()
can be used to iterate over ArrayList in java .- If we want to Iterate from specific index we can use
listIterator(int index)
- From Java 8 We can use
spliterator()
. SplitIterator can help in parallel Processing.
void forEach(Consumer<? super E> action) | It perfom given action for each elements of ArrayList |
Iterator<E> iterator() | It returns Iterator for the given list in the same sequence of elements. |
ListIterator<E> listIterator() | Return ListIterator for all elements |
ListIterator<E> listIterator(int index) | Return ListIterator for given list in the proper sequence of elements from index specified. |
Spliterator spliterator() | Return Spliterator for given ArrayList |
Iterating ArrayList in Java using for loop
Java legacy for loop can be used to traverse array list as show below
List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.print("Using for Loop to Iterate ArrayList"); for(int i = 0; i< list.size(); i++) { System.out.print(list.get(i)+ " "); }
Iterating ArrayList in Java using forEach()
List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("Iterating ArrayList using list.forEach"); list.forEach(country -> System.out.print(country+ " "));
Iterating ArrayList in Java using iterator()
Java ArrayList class provides Iterator which can be used to Iterate over ArrayList
elements as shown in the below code. This method returns Iterator
Interface from java.util package
.
List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("Iterating ArrayList using list.Iterator()"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
Iterating ArrayList in Java using iteratorList()
and iteratorList(int Index)
Java ArrayList listIterator()
and listIterator( int index)
to traverse through list elements. Traversing through list Iterator has many advantages like
- You can traverse reverse direction as well as front direction using
ListIterator's
methodprevious()
andnext()
. - Even you can previous and next Index using ListIterator
previousIndex()
andnextIndex().
- You can add an element or Replace elements to list iterator while traversing using ListIterator’s
add(E e)
orset (E e)
System.out.println("Iterating ArrayList using list.ListIterator()"); ListIterator<String> listIterator = list.listIterator(); System.out.println("Traversing in front direction"); while(listIterator.hasNext()) { String country = listIterator.next(); System.out.println("current element: " +country); } System.out.println("Traversing in backword direction"); while(listIterator.hasPrevious()) { String country = listIterator.previous(); System.out.println("current element: " +country); }
Adding and Updating ArrayList while traversing or Iterating in java
ListIterator
of ArrayList
provides set(E e)
and add( E e)
methods to update or add elements to current ArrayList while traversing. Below code shows adding of country Japan when Us and updating China to Nepal
ListIterator<String> listIterator = list.listIterator(); System.out.println("Traversing in front direction"); while(listIterator.hasNext()) { String country = listIterator.next(); System.out.println("current element: " +country); if(country.equals("US")) listIterator.add("Japan"); if(country.equals("China")) listIterator.set("Nepal"); } System.out.println("Updated List: " + list);
Example code for iterating Arraylist in different ways.
package com.techijournal.collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class MyArrayList { public static void main(String atgs []) { IteratingOverList(); } private static void IteratingOverList() { List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); System.out.println("Iterating ArrayList using list.forEach"); list.forEach(country -> System.out.print(country+ " ")); System.out.println(); System.out.print("Using for Loop to Iterate ArrayList"); for(int i = 0; i< list.size(); i++) { System.out.println(list.get(i)+ " "); } System.out.println("Iterating ArrayList using list.Iterator()"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println("Iterating ArrayList using list.ListIterator()"); ListIterator<String> listIterator = list.listIterator(); System.out.println("Traversing in front direction"); while(listIterator.hasNext()) { String country = listIterator.next(); System.out.println("current element: " +country); if(country.equals("US")) listIterator.add("Japan"); if(country.equals("China")) listIterator.set("Nepal"); } System.out.println("Updated List: " + list); System.out.println("Traversing in backword direction"); while(listIterator.hasPrevious()) { String country = listIterator.previous(); System.out.println("current element: " +country); } } }
Output for above code is:
Initial List :[US, China, India, Rome, Cannada] Iterating ArrayList using list.forEach US China India Rome Cannada Using for Loop to Iterate ArrayList US China India Rome Cannada Iterating ArrayList using list.Iterator() US China India Rome Cannada Iterating ArrayList using list.ListIterator() Traversing in front direction current element: US current element: China current element: India current element: Rome current element: Cannada Updated List: [US, Japan, Nepal, India, Rome, Cannada] Traversing in backword direction current element: Cannada current element: Rome current element: India current element: Nepal current element: Japan current element: US
ArrayList Clone Method in Java
Java ArrayList provide a way to create clone for ArrayList
using shallow Copy using its clone()
method.
Object Clone() | Return Shallow copy of given ArrayList |
A shallow copy of the given ArrayList means that you have created a duplicate of the list, not the elements in it. Example In the below code we have ArrayList of type Country with some countries in it. Now, we will create a clone of it to duplicateList.
Now what is happening is your list is cloned and reference of the country in list is passed to duplicateList elements. Means whenever you update any Country properties it any of the list (duplicateList or list) it will reflected in both list.
In the below code at line no 14 we updated duplicateList’s index 0 country to USD. The changes are reflected in both lists.
Example of clone()
in ArrayList
private static void cloningArrayList() { ArrayList<Country> list = new ArrayList<>(); list.add(new Country("US")); list.add(new Country("China")); list.add(new Country("India")); list.add(new Country("Rome")); list.add(new Country("Cannada")); System.out.println("Initial List :"+ list); List<Country> duplicateList = new ArrayList<>(); duplicateList = (List<Country>) list.clone(); System.out.println("Cloned list is :"+ duplicateList); duplicateList.get(0).setName("USD"); System.out.println("Updated Initial List :"+ list); System.out.println("Updated Cloned List :"+ duplicateList); }
Output for above code:
Initial List :[Country [name=US], Country [name=China], Country [name=India], Country [name=Rome], Country [name=Cannada]] Cloned list is :[Country [name=US], Country [name=China], Country [name=India], Country [name=Rome], Country [name=Cannada]] Initial List :[Country [name=USD], Country [name=China], Country [name=India], Country [name=Rome], Country [name=Cannada]] Cloned List :[Country [name=USD], Country [name=China], Country [name=India], Country [name=Rome], Country [name=Cannada]]
Getting size of ArrayList
ArrayList provide size()
to get size of the arrayList.
int size() | Returns size of the ArrayList |
List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println(list.size());
output for above code is:
5
Converting List to Array
ArrayList provides toArray() method to convert arrayList to array.
Object[] toArray() | Retains object array of the arrayList. Type conversion is required. |
T[] toArray( T[] a ) | Return Array of the given list in T format. |
Example code for Converting ArrayList to Array
private static void toArray() { List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); String [] objectArr = (String[]) list.toArray(new String[10]); System.out.println("Converted arraylist to array is : "); list.forEach(e -> System.out.println(String.valueOf(e)+" ") ); String [] arr = (String[]) list.toArray(new String[10]); System.out.println("Converted arraylist to array is : "); list.forEach(e -> System.out.print(e+" ") ); }
Output for the above code:
Initial List :[US, China, India, Rome, Cannada] Converted arraylist to array is : US China India Rome Cannada Converted arraylist to array is : US China India Rome Cannada
Sorting the ArrayList
From java 8 ArrayList have sort()
which can sort the elements on basis of passed comparator to it.
void sort(Comparator c) | Sorts the given list on basis of comparator |
Example of sorting array list using sort()
private static void sortArrayList() { List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); list.sort((o1,o2) ->{ return o1.compareTo(o2); }); System.out.println("Sorted list is : "+list); }
Output for the above code is:
Initial List :[US, China, India, Rome, Cannada] Sorted list is : [Cannada, China, India, Rome, US]
Extra methods of ArrayList
boolean contains(Object o) | Returns true if this list contains the specified element. |
void ensureCapacity(int minCapacity) | Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. |
void trimToSize() | Trims the capacity of this ArrayList instance to be the list’s current size. |
E set(int index, E element) | Replaces the element at the specified position in this list with the specified element. |
Difference between set() and add() methods of ArrayList
ArrayList set( int index, E element )
is used to replace element at given index in array list. And it return the replaced element.
Where as,
ArraylList add( int index, E element )
is used to add element at given index This method will also update the existing old element at index. But it returns a boolean value.
private static void setAndAdd() { List<String> list = new ArrayList<>(); list.add("US"); list.add("China"); list.add("India"); list.add("Rome"); list.add("Cannada"); System.out.println("Initial List :"+ list); //list.add(5,"Japan"); System.out.println(list.set(4, "Russia")); }
output for above code is:
Initial List :[US, China, India, Rome, Cannada] Cannada
ArrayList Vs Array
Java ArrayList | Java Array |
---|---|
ArrayList is part of collection framework in java | Array is not part of collection frame work in java |
ArrayList is created asArrayList<String> list = new ArrayList<>(); | Array is created as String [] arr = new String[10]; |
ArrayList size increases dynamically | Array are fixed in size. |
Array List cannot be created of primitive type like int, long, etc | Array can be created of primitive type. |
ArrayList Vs LinkedList
ArrayList | LinkedList |
---|---|
ArrayList uses dynamic array as internal data structure | Linked list uses doubly linked list as internal data structure |
Insertion operation at end of the ArrayList takes constant time i.e O(1) | Same goes for LinkedList |
But, Addition of elements in between of ArrayList is hefty operation as it requires shifting the data to and merging of the array | Insertion in linkedList is more efficient than ArrayList as in LinkedList it does not required copying and merging of the Array |
Deletion in ArrayList is also hefty process because it again requires copying and merging of the array | Deletion in Linked list take constant time as it does not requires copying and merging operation like array |
Because of above reasons, ArrayList is not preferred when list manipulation is primary operation. | Because of above reasons, LinkedList is preferred when list manipulation is primary operation. |
ArrayList is index based system means element are randomly accessible. That’s why whenever when fetching element is primary purpose of data structure then ArrayList is preferred over LinkedList | But, Linked list is not index based system and elements of LinkedList are not randomly accessible. |
ArrayList is memory efficient then LinkedList | LinkedList is not memory efficient as it requires extra memory head for story reference of next element. |
Learn about linkedList in more detail here at Java LinkedList
ArrayList Vs Vector
ArrayList | Vector |
---|---|
ArrayList is coming from Java 1.3 | Vector is legacy system |
ArrayList methods are not synchronized | Whereas Vector methods are synchronized |
As array list is not synchronized it is faster than vector | As vector are synchronized it is slow compare to ArrayList |
Both grow in size dynamically but ArrayList increases its size by 50% | Vector Increases its size by 100% |
ArrayList use Iterator for Iteration | But, Vector can use Iterator or Enumeration for iteration |
ArrayList is not preferred for multithreaded environment | Vector is preferred for multithread environment. |
Conclusion
In this post, we saw different ways to use ArrayList in Java. We used add(E element )
and add( int index, E element )
to add elements to list and also we saw different ways to create an ArrayList
example: new ArrayList()
.
We learned different flavours of method to remove elements from ArrayList like removeAll(Collection c)
.
Thank’s Note,
Thanks for spending you valuable time on this post hope this post was use full to you and you learned something new today. If you like our post please share our post.
Reference: Oracles Docs
Pingback: itemprop="name">Java LinkedList - Techi Journal