Java ArrayList With Simple Example

Share:
Java ArrayList With Simple Example | Java ArrayList
  • In Java ArrayList is a class which is used to store elements.
  • It inherits AbstractList Class which implements List interface.
Java ArrayList With Simple Example
Points to remember about Java ArrayList Class.
  • It is re-sizeable /grow-able Array also called as Dynamic Array.
  • It allows duplicate elements. 
  • It can contain null also.
  • It maintain the insertion order i.e., insertion order is preserved.
  • Heterogeneous objects are allowed.
  • It is best for search operations.
  • It implements Random access hence it is best for search operations.
  • In ArrayList Manipulation is slow because lot of shifting is required if any elements is removed from it.
ArrayList Class
As shown in the diagram it extends AbstractList class which implements the List interface, and List interface extends the Collection and Iterable interface. 

Declaration of ArrayList Class.
It is present in java.util package.
public class ArrayList<E> extends AbstractList<E> implements List<E>,RandomAccess,Cloneable,Serializable.

Constructors of ArrayList
1.ArrayList();
  • It creates an empty ArrayList with initial capacity i.e.10.
  • When ArrayList reached its max capacity then it creates a new ArrayList with 50% increment in initial capacity.
  • New Capacity=(Current Capacity x3/2)+1;
2.ArrayList(int Initial capacity);
  • It creates an ArrayList with specified initial capacity.
3.ArrayList(Collection);
  • It creates an equivalent ArrayList object for given collection.
Now Java ArrayList Method
There are following methods:
void add(Object obj);
-Used to add elements to end of an ArrayList.
void add(int index,Object obj);
-Used to add elements to specified index in a ArrayList.
boolean addAll(Collection c);
-Used to add elements of specified collection to the end of an ArrayList.
boolean addAll(int index,Collection c);
-Used to add elements of specified collection to an ArrayList from the specified index of an ArrayList.
void clear();
-Used to remove all elements from an ArrayList.
int indexOf(Objec obj);
-Used to return the first index of specified element as it allows duplicates.
int latIndexOf(Objec obj);
-Used to return the last index of specified element as it allows duplicates.
Object[] toArray();
-Used to return an array of current ArrayList in correct order.
Object clone();
-Return a shallow copy ArrayList.
void trimToSize();
Used to trim the capacity of this ArrayList instance to be the current size.

Creating an ArrayList and adding new Elements to it.

This example shows:
  • How to create an ArrayList using ArrayList() constructor.
  • Adding new elements to an ArrayList using add() method.
  • Adding new elements at specified index to an ArrayList using add(int index) method.
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
List al=new ArrayList();
al.add(1);
al.add(2);
al.add(3);
System.out.println(al);
//adding an elements to arraylist with specified index
al.add(0,100);
System.out.println(al);
  }
}
output:
[1, 2, 3]
[100, 1, 2, 3]

How to create an ArrayList from another Collection?
In this example we are going to see:
  • How to create an ArrayList from another Collection using ArrayList(Collection c) constructor.
  • How to add all elements from existing collection to new ArrayList using addAll() method.
import java.util.*;
public class ArrayListExample2 {

public static void main(String[] args{

List<Integer> firstFiveNumbers=new ArrayList<Integer>();

firstFiveNumbers.add(1);

firstFiveNumbers.add(2);
firstFiveNumbers.add(3);

firstFiveNumbers.add(4);

firstFiveNumbers.add(5);
List<Integer> firstTenNumbers=new ArrayList<Integer> (firstFiveNumbers);                          

List<Integer> nextFiveNumbers=new ArrayList<Integer>();

nextFiveNumbers.add(6);

nextFiveNumbers.add(7);

nextFiveNumbers.add(8);

nextFiveNumbers.add(9);

nextFiveNumbers.add(10);  
//adding all elements of nextFiveNumbers to firstTenNumbers

firstTenNumbers.addAll(nextFiveNumbers);

System.out.println(firstTenNumbers);
   }
}
output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 Non Generic vs Generic ArrayList.
Programmers can ad any type of objects to the ArrayList but at run time suppose if we added Integer to ArrayList and if we try to get 0th index element using get(0) method then what is the type of 0th element we don't know and we are trying to hold it in String then compile time error occured but if we perform Type Casting then error will solve but at run time we will get ClassCastException.
See Example...
1.Non Generics
import java.util.*;
public class ArrayListDemo{
public static void main(String args[]){
List li=new ArrayList();
li.add("one");
li.add(1);
String s=(String li.get(1);
System.out.println(s);
  }
}
output:
Exception in thread "main" 
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
-So Here Type Safety and Type Casting Issue raised in the above example.
To overcome these problem SUN People come with Generic Version of ArrayList.
2.Generic ArrayList
import java.util.*;
public class ArrayListDemo2{
public static void main(String args[]){
List<String> li=new ArrayList<String>();
li.add("one");
li.add("two"); 
String s=li.get(1);
System.out.println(s);
  }
}
output:two
  • In the above example we have created Generic List with angular braces<String>,So we can add String object only to this list, If we try to insert any other type of object then we will get compile time error. 
  • So after generic version of ArrayList we can store specific type of elements in Collection.
  • So Type Safety and Type Casting Problem is resolved.
  • Compile time checking because Compile Time Checking is better than Run Time.

How to access elements of an ArrayList?
see the example...
import java.util.*;
public class MyClass{
public static void println(String args[]){
List<String> players=new ArrayList<String>();
System.out.println("Is the Players list empty? yes it is   "+players.isEmpty());
players.add("Matin");
players.add("Vijay");
players.add("Manish");
players.add("Praksh");
players.add("Shravan");
//Size of players list
System.out.println("Here is the Top "+players.size()+" Players List");
System.out.println(players);
//Retrieving the players from list see below
System.out.println("No One Player "+players.get(0));
System.out.println("No Two Player "+players.get(1));
System.out.println("Last Player in the list is "+players.get(players.size()-1));
//Now changing the No One Players i.e Modification
players.set(0,"Akash");
System.out.println("Now No One Player in the list is "+players.get(0));
System.out.println(players);
  }
}
output:
Is the Players list empty? yes it is true
Here is the Top 5 Players List
[Matin, Vijay, Manish, Praksh, Shravan]
No One Player Matin
No Two Player Vijay
Last Player in the list is Shravan
Now No One Player in the list is Akash
[Akash, Vijay, Manish, Praksh, Shravan]
So from the above example we learnt.
  • How to check either ArrayList is Empty or not using isEmpty() method.
  • How to check the size of an ArrayList using size() method.
  • How to access an element at  particular index in an ArrayList using get(int index ) method.
  • How to change an element at particular index in an ArrayList using set(int index,String element) method.

HOW TO REMOVE ELEMENTS FROM AN ArrayList?
In this example we are going to see how to remove an elements from an ArrayList using/
remove(Object obj).
remove(int index).
removeAll(Collection<?> c).
removeIf().
remove().
File Name:
MyRemovingClass.java
import java.util.*;
import java.util.function.Predicate;
public class MyRemovingClass{
public static void main(String args[]){
List<String> players=new ArrayList<String>();
players.add("Matin");
players.add("Vijay");
players.add("Manish");
players.add("Praksh");
players.add("Shravan");
System.out.println("Top 5 Players List at initial Stage "+players);

//removing element using remove(Objec obj)
//remove(Objec obj) return false if element does not exist
boolean b=players.remove("Shravan");
System.out.println(b);
System.out.println("After Removal of Shravan "+players);

//removing element using remove(int index),
//it remove the element of specified index and return that element 
String removedElement=players.remove(3);
System.out.println("Removed Element "+removedElement);

//Now Stable ArrayLsit
System.out.println("Now Players List After remove(3) "+players);

// satisfying the given predicate and removing elements
players.removeIf(new Predicate<String>() {
@Override
public boolean test(String element) {
return element.endsWith("n");
}
});
System.out.println("After removing elements ends with n, Now Remaining Players "+players);

//removing all elements from an arraylist using clear() method
players.clear();
System.out.println("After clear() "+players);
 }
}
output:
Top 5 Players List at initial Stage [Matin, Vijay, Manish, Praksh, Shravan]
true
After Removal of Shravan [Matin, Vijay, Manish, Praksh]
Removed Element Praksh
Now Players List After remove(3) [Matin, Vijay, Manish]
After removing elements ends with n, Now Remaing Players [Vijay, Manish]
After clear() []

Iterating over an ArrayList
File Name:
IteratingClass.java
import java.util.*;
public class IteratingClass{
public static void main(String args[]){
List<String> players=new ArrayList<String>(); 
players.add("Matin");
players.add("Vijay");
players.add("Manish");
players.add("Praksh");
players.add("Shravan");
System.out.println("Before Iteration "+players);
//Iterating using for loop
System.out.println("After Iteration Using Normal For Loop");
for(int i=0;i<players.size();i++)
  {
   System.out.println(players.get(i));}
  }
System.out.println("=======================");
//Iterating using for each loop
System.out.println("After Iteration using For Each ");
for(String player:players)
{
  System.out.println(player);
}
System.out.println("=======================");
//Iterating using Iterator
System.out.println("Iterating using Iterator ");
Iterator<String> itr=players.iterator();
while(itr.hasNext())
 {
    System.out.println(itr.next());
 }
System.out.println("=======================");
//Iterating in backward direction using ListIterator 
System.out.println("Iterating in backward direction using ListIterator ");
ListIterator<String> itr=players.listIterator(players.size());
while(itr.hasPrevious())
{
System.out.println(itr.previous());
}
System.out.println("=======================");
//Iterating in backward direction using ListIterator 
System.out.println("Iterating in backward direction using ListIterator ");
ListIterator<String> itr=players.listIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
System.out.println("=======================");

//Iterating using Java 8 forEach and lambda
System.out.println("Iterating using Java 8 forEach and lambda ");
players.forEach(play -> {
            System.out.println(play);
        });
System.out.println("=======================");
   }//end of main
}//end of class
OutPut:
Before Iteration [Matin, Vijay, Manish, Praksh, Shravan]
After Iteration Using Normal For Loop
Matin
Vijay
Manish
Praksh
Shravan
====================
After Iteration using For Each 
Matin
Vijay
Manish
Praksh
Shravan
=======================
Iterating using Iterator 
Matin
Vijay
Manish
Praksh
Shravan
=======================
Iterating in backward direction using ListIterator 
Shravan
Praksh
Manish
Vijay
Matin
=======================
Iterating in forward direction using ListIterator 
Matin
Vijay
Manish
Praksh
Shravan
=======================
Iterating using Java 8 forEach and lambda 
Matin
Vijay
Manish
Praksh
Shravan
=======================

List and ListIterator
Iterator
  • It can traverse the elements in forward direction only.
  • This Iterator can be used with List,Set and Queue.
  • While traversing the element it can perform remove operation only.
whereas...
ListIterator
  • It can traverse the element in both direction i.e. Forward as well as Backward.
  • This Iterator can be used with List only.
  • While traversing the elements it can perform add,remove and set operations.

Hope This Article Was Helpful.

You should know also.
Difference between ArrayList and LinkedList

No comments

You May Like Also

Programming Knowledge


Java JDK
Reversing String in Java
Java Generic Concept With Simple Example
Java Generic Objects Behavior In Non-Generic Area
Creating Connection With MySql Databse Using Java Application
Performing Database Operations Java MySql Insert Update Delete Select
Java Inserting Data in MySql Databse Table
Java Basic Login System Using MySql Database Table
JSP Login System Using MySql Databse
Jsp Servlet Login And Logout System Using Mysql Database Table
What is jdk in Java?
Exaplain inheritance in Java with example?
Exaplain polymorphism in Java with example?
Exaplain abstraction in Java with example?
Exaplain encapsulation in Java with example?
What is the use of this keyword in Java?
Explain ArrayList With Example
Explain LinkedList With Example
Explain Vector Class With Example
Explain Vector Class With Example
Generics in java with example
Behavior of generic objects
How can i pass generic class to a method in java
How to create a login system in jsp using mysql database?
How to create a login and logout system in jsp & servlet using mysql database?
How to connection a simple Java application with mysql database?
How to insert values in mysql databse usiong Java applications?
Perform insertion, retrieval, updatation and delete operations?
How to create a simple login system in java using mysql database?

PHP Login System Using MySql Database
PHP Complete Login System With Session And Logout Using MySql Database