ArrayList in Java

What is ArrayList?

ArrayList is a class in the Java which is present in the java.util package.
ArrayList class implements the List interface and inherits the AbstractList class.
ArrayList capacity grows automatically. ArrayList is created with an initial size of 10, although we can change it’s initial capacity.
It allows duplicate elements. 
Insertion order is preserved in an ArrayList.
ArrayList allows us to random access.
ArrayList does not use with primitives like int, char, float etc. ArrayList uses with Wrapper classes.
ArrayList in Java is an alternate to vector in c++.

Difference between an Array and an ArrayList in Java:-
The main difference between of an Array and an ArrayList is that, the size of the array can not be grow or shrink at run time. while  the size of an ArrayList can grow or shrink at run time. It means that an Array is static by nature and an ArrayList is dynamic by nature.

Constructors of ArrayList:-
                                Constructors and it's description
1. 

ArrayList( )

It is used to create an empty ArrayList with an initial size of 10.

2.

ArrayList(int c)

It is used to create an ArrayList with the specified capacity c. 

3.

ArrayList(Collection x)

It is used to create an ArrayList initialized with the elements of the collection x.


Methods of ArrayList:-
                              Methods and it's description
1. 

void add(int i, Object e)

It is used to insert an specified element e at the specified position index i in a list. 

2.

boolean add(Object e)

It is used to append the specified element e to the end of a list.

3.

boolean addAll(Collection c)

It is used to append all of the elements in the specified collection c to the end of the list, in the order that they are returned by the specified collection's iterator. 

4.

boolean addAll(int i, Collection c)

It is used to insert all of the elements in the specified collection c, starting at the specified position i. 

5.

void clear( )

It is used to remove all of the elements from the ArrayList.

6.

Object clone( )

It returns a shallow copy of this ArrayList.

7.

boolean contains(Object o)

It returns true if the ArrayList contains the specified element o, otherwise returns false.

8.

void ensureCapacity(int capacity)

It is used to increase the capacity of the ArrayList instance.

9.

Object get(int index)

It  returns the element at the specified index position in the ArrayList. 

10.

int indexOf(Object o)

It returns the index position in the ArrayList of the first occurrence of the specified element o, or -1 if the List does not contain this element.

11.

int lastIndexOf(Object o)

It returns the index position in the ArrayList of the last occurrence of the specified element o, or -1 if the List does not contain this element.

12.

Object remove(int x)

It is used to remove the element at the specified position x in the list. 

13.

protected void removeRange(int fromIndex, int toIndex)

It is used to remove all of the elements  from the List whose index is between fromIndex to toIndex.

14.

Object set(int index, Object element)

It is used to replace the element at the specified index position in the ArrayList with the specified element. 

15.

int size( )

It is used to find the number of elements in the list.

16.

Object[ ] toArray( )

It returns an array containing all of the elements in the ArrayList in the correct order. 

17.

boolean isEmpty( )

It returns true if the ArrayList is empty, otherwise false.

18.

void trimToSize( )

It is used to trim the capacity of the ArrayList instance to be the list's current size.

19.

void sort(Collection<?> c )

It is used to sort all the elements of the ArrayList.

20.

boolean removeAll(Collection<?> c)

It is used to remove all the elements of the ArrayList.

Creation of ArrayList:-
ArrayList can be created in two ways:-
1. Type unsafe
2. Type safe 

Type Unsafe ArrayList:-
It can be created as shown below-
      ArrayList list=new ArrayList( );
Although they are easier to create but we cannot check what kind of data we are adding in the ArrayList. 
for example:- 
1. list.add("Naman");
2. list.add(20);
3. list.add(true);
4. list.add(25.5);

All the above lines will successfully compile and run.

Type Safe ArrayList:-
It can be created as shown below-
      ArrayList<String> list=new ArrayList<String>( );
The < > are called diamond operator in Java and they tell the compiler to only allow us to add String values in the ArrayList.
Any other type of value cannot be added in the ArrayList and if we try to do so, the compiler will generate syntax error.
for example:- 
1. list.add("Naman");   // correct
2. list.add(20);            // wrong
3. list.add(true);         // wrong
4. list.add(25.5);       // wrong

Inserting elements in ArrayList:-
To insert element in the ArrayList, we have to call the method add( ).
This method has two versions:-
Prototype of the method add( ):-
1. public boolean add(Object):- The first method accepts an Object as argument and adds that Object at the end of the ArrayList.
2. public void add(int, Object):-  The second method accepts an index number as well as an Object as argument and adds the Object at the specified index. If index is out of range then it throws the exception IndexOutOfBoundsException.

for example:- 
    ArrayList<String> list=new ArrayList<String>( );
1. list.add("India");
2. list.add(0, "England");

Retrieving elements of ArrayList:-
To retrieve an elements from the ArrayList, we have to call the method get( ).
Prototype of the method get( ):-
1. public Object get(int index):- This method accepts an index number as argument and returns the element at that position.

If index is out of range then it throws the exception IndexOutOfBoundsException.


for example:- 
   ArrayList<String> list=new ArrayList<String>( );
   list.add("India"); 
   list.add("Japan");
   String s=list.get(0);
   String p=list.get(1);
   System.out.println(s);     // will show India
   System.out.println(p);    // will show Japan

Checking size of an ArrayList:-
Size of an ArrayList means total number of elements currently present in an ArrayList. 
To retrieve size of an ArrayList, we have a method called size( ), whose prototype is-
     public int size(int index)
for example:- 
   ArrayList<String> list=new ArrayList<String>( );
   list.add("India"); 
   list.add("England");
   int x=list.size();
   System.out.print(x);  // will get 2

Searching an element in an ArrayList:-
Sometimes we need to check whether an element exists in an ArrayList or not. 
For this purpose we can use contains( ) method of Java, whose prototype is-
public boolean contains(Object):- contains( ) method takes type of object defined in the ArrayList creation and returns true if this list contains the specified element.
for example:- 
   ArrayList<String> list=new ArrayList<String>( );
   list.add("Indore"); 
   list.add("Bhopal");
   boolean x=list.contains("Indore");
   boolean y=list.contains("Gwalior");
   System.out.print(x);  // will get true
   System.out.print(y);  // will get false

Another way of Searching an element in an ArrayList:-
we can also use indexOf() method of ArrayList in Java to find out index of a particular object or it returns  -1 if the List does not contains this element.
for example:- 
   ArrayList<String> list=new ArrayList<String>( );
   list.add("Indore"); 
   list.add("Bhopal");
   int x=list.indexOf("Indore");
   int y=list.indexOf("Gwalior");
   System.out.print(x);  // will get 0
   System.out.print(y);  // will get -1

Removing an element from an ArrayList:-
There are two ways to remove any element from an ArrayList in Java. The method to be called is remove( ).
It has two versions:-
1. public Object remove(int)
2. public boolean remove(Object)
We can either remove an element based on its index or by providing object itself.
for example:- 
   ArrayList<String> list=new ArrayList<String>( );
   list.add("Indore"); 
   list.add("Bhopal");
   list.remove(0);
   list.remove("Bhopal");
   System.out.print(list.size());  // will get 0

Changing an element in an ArrayList:-
To change or modify element in an ArrayList, we have to call the method set( ).
public Object set(int, Object):- It replaces the element at the specified index position in the ArrayList with the specified element. 
for example:- 
   ArrayList<String> list=new ArrayList<String>( );
   list.add("Indore"); 
   list.add("Bhopal");
   list.set(0,"Gwalior");
   System.out.print(list.get(0));   // will get Gwalior
   System.out.print(list.get(1));  // will get Bhopal

Sorting of an element in an ArrayList:-
The Java language provides us predefined sorting functions/methods to sort the elements of collections  like ArrayList.
Thus, we do not have to write our own logic for sorting these collections.
This is done using a class called “Collections” in the package java.util which contains a static method called sort( ) which can sort an ArrayList.
The prototype of the method is:-

  public static void sort(List L)

This method accepts a List as argument and sorts it’s elements in natural order.
What is natural order?
Natural order means the default sorting order which is as follows:-
1) If the List consists of String elements, it will be sorted into alphabetical order.
2) If it contains Integers , it will be sorted in numeric order.
3) If it consists of Date elements, it will be sorted into chronological order.

Example:-
Ranking of top 5 teams given by ICC  for ODI in 2020 is as follows:

1- England

2- India

3- New Zealand

4- South Africa

5- Australia

Write a program to do the following:-

1. Accept names of these 5 teams and store them in the ArrayList.
2. prints size of an ArrayList.
3. Now ask the user to input a team name and search and print it’s ranking. If the team name is not found then print the message Team not found.
4. And at last sort the element of an ArrayList.
Solution:-

Output:-

What is a custom ArrayList?
A custom ArrayList is an ArrayList which can hold objects of programmer defined classes.
For example, suppose we have a class called Employee and we want to store Employee objects in an ArrayList then such an ArrayList will be called a custom ArrayList.

How do we create a custom ArrayList?
To create a custom ArrayList, we use the following syntax-
     ArrayList <name of our class> refName= new ArrayList< >( );
for example:-
     ArrayList <Employee> emp= new ArrayList<Employee>( );

Post a Comment

0 Comments