Arraylists
Arraylists
ARRAY LISTS
Hierarchy of ArrayList class:
As shown in diagram, Java ArrayList class extends AbstractList class which
implements List interface.
The List interface extends Collection and Iterable interfaces in hierarchical order.
The Java Iterable interface represents a collection of objects which is iterable ( can be
iterated).
A class that implements the Java Iterable interface can have its elements iterated.
Syntax ArrayList :
Example:
ArrayList<String> list=new ArrayList<String>(); //creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now ArrayList is forced
to have the only specified type of objects in it. If you try to add another type of object,
it gives compile time error
Drawback of Array:
The issue with arrays is that they are of fixed length so if it is full we cannot add any
more elements to it, likewise if number of elements gets removed from it the memory
consumption would be the same as it doesn‘t shrink.
Advantage of ArrayList:
On the other ArrayList can dynamically grow and shrink after addition and removal of
elements. Apart from these benefits, ArrayList class enables us to use predefined
methods of it which makes our task easy.
Let‘s see the ArrayList example first then we will discuss it‘s methods and their usage.
ArrayList Example :
import java.util.*;
public class ArrayListExample
{
public static void main(String args[])
{
ArrayList<String>obj=new ArrayList<String>();
obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");
System.out.println("Currently the array list has following elements:"+obj);
obj.add(0,"Rahul");
obj.add(1,"Justin");
obj.remove("Chaitanya");
obj.remove("Harry");
System.out.println("Current array list is:"+obj); obj.remove(1);
System.out.println("Current array list is:"+obj);
}
}
Output:
Currently the array list has following elements:[ Ajeet, Harry,Chaitanya,Steve, Anuj]
Current array list is:[ Rahul,Justin, Ajeet,Steve, Anuj]
Current array list is:[Rahul,Ajeet,Steve,Anuj]
In order to create an ArrayList, we need to create an object of the ArrayList class. The
ArrayList class consists various constructors which allows the possible creation of the
array list. The following are the constructors available in this class:
Description
Constructor
Let’s understand the Java ArrayList in depth. Look at the below image:
5)set(int index, Object o): Used for updating an element. It replaces the element
present at the specified index with the object o.
obj.set(2,"Tom");
It would replace the 3rd element (index =2 is 3rd element) with the value Tom.
6)int indexOf(Object o): Gives the index of the object o. If the element is not found in
the list then this method returns the value -1.
int pos=obj.indexOf("Tom");
This would give the index (position) of the string Tom in the list.
7)Object get(int index): It returns the object of list which is present at the specified
index.
String str=obj.get(2);
Function get would return the string stored at 3rd position (index 2) and would be
assigned to the string ―str
.
8)int size(): It gives the size of the ArrayList – Number of elements of thelist.
int numberofitems=obj.size();
9)boolean contains(Object o): It checks whether the given object o is present in the
array list if its there then it returns true else it returns false.
obj.contains("Steve");
It would return true if the string ―Steve‖ is present in the list else we would get false.
10)clear(): It is used for removing all the elements of the array list in one go. The
below code will remove all the elements of ArrayList whose object is obj.
obj.clear();
Description
Method
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a
list.
boolean addAll(Collection<? It is used to append all of the elements in the specified
extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity(int It is used to enhance the capacity of an ArrayList
requiredCapacity) instance.
E get(int index) It is used to fetch the element from the particular
position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
Description
Method
int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the
list does not contain this element.
Object[] toArray() It is used to return an array containing all of the
elements in this list in the correct order.
Object clone() It is used to return a shallow copy of an
ArrayList.
boolean contains(Object o) It returns true if the list contains the specified
element
int indexOf(Object o) It is used to return the index in this list of the
first occurrence of the specified element, or -1 if
the List does not contain this element.
E remove(int index) It is used to remove the element present at the
specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the
specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the
list.
boolean removeIf(Predicate<? super It is used to remove all the elements from the list
E> filter) that satisfies the given predicate.
Description
Method
protected void removeRange(int It is used to remove all the elements lies
fromIndex, int toIndex) within the given range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the
operator) list with the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list
that are present in the specified collection.
E set(int index, E element) It is used to replace the specified element in
the list, present at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on
the basis of specified comparator.
Spliterator<E> spliterator() It is used to create spliterator over the
elements in a list.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies within
toIndex) the given range.
int size() It is used to return the number of elements
present in the list.
void trimToSize() It is used to trim the capacity of this
ArrayList instance to be the list's current
size.
ArrayList in Java:
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 the array is needed.
This class is found in java.util package.
Example: The following implementation demonstrates how to create and use an
ArrayList.
import java.io.*;
import java.util.*;
class ArrayListExample {
public static void main(String[] args)
{
// Size of the ArrayList
int n = 5;
// Declaring the ArrayList with initial size n
ArrayList<Integer> arrli
= new ArrayList<Integer>(n);
ArrayList arrli
= new ArrayList(n);
// Appending new elements at
// the end of the list
for (int i = 1; i <= n; i++)
arrli.add(i);
// Printing elements
System.out.println(arrli);
// Remove element at index 3
arrli.remove(3);
// Displaying the ArrayList after deletion
System.out.println(arrli);
// Printing elements one by one
for (int i = 0; i < arrli.size(); i++)
System.out.print(arrli.get(i) + " ");
}
}
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
1.Adding Elements: In order to add an element to an ArrayList, we can use the add()
method. This method is overloaded to perform multiple operations based on different
parameters.
They are:
add(Object): This method is used to add an element at the end of the ArrayList.
add(int index, Object): This method is used to add an element at a specific index in the
ArrayList
import java.util.*;
public class GFG {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<>();
al.add("Sairam");
al.add(“Sairam");
al.add(1, "For");
System.out.println(al);
}
}
Output:
[Sairam, For, Sairam]
2. Changing Elements: 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.
import java.util.*;
public class GFG {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<>();
al.add("Sairam");
al.add("Sairam");
al.add(1, "Suresh");
System.out.println("Initial ArrayList " + al);
al.set(1, "For");
System.out.println("Updated ArrayList " + al);
}
}
Output:
3. Removing Elements: In order to remove an element from an ArrayList, we can use the
remove() method.
remove(Object): This method is used to simply remove an object from the ArrayList. If
there are multiple such objects, then the first occurrence of the object is removed.
remove(int index): Since an ArrayList is indexed, this method takes an integer value
which simply removes the element present at that specific index in the ArrayList. After
removing the element, all the elements are moved to the left to fill the space and the
indices of the objects are updated.
import java.util.*;
public class GFG {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<>();
al.add("Sairam");
al.add("Sairam");
al.add(1, "For");
System.out.println("Initial ArrayList " + al);
al.remove(1); System.out.println(al.indexOf("Sairam")); // 0
System.out.println("After the Index Removal " + al);
al.remove("Sairam");
System.out.println("After the Object Removal " + al);
} }
Output:
Initial ArrayList [Sairam, For, Sairam]
After the Index Removal [Sairam, Sairam]
After the Object Removal [Sairam]
4. Iterating the ArrayList: There are multiple ways to iterate through the ArrayList.
The most famous ways are by using the basic for loop in combination with a get()
method to get the element at a specific index and the advanced for loop.
import java.util.*;
public class GFG {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<>();
al.add("Sairam");
al.add("Sairam");
al.add(1, "For");
// Using the Get method and the
// for loop
for (int i = 0; i < al.size(); i++) {
Since ArrayList is a dynamic array and we do not have to specify the size while
creating it, the size of the array automatically increases when we dynamically add and
remove items. Though the actual library implementation may be more complex, the
following is a very basic idea explaining the working of the array when the array
becomes full and if we try to add an item:
● Creates a bigger sized memory on heap memory (for example memory of double size).
● Copies the current memory elements to the new memory.
● New item is added now as there is bigger memory available now.
● Delete the old memory.