• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Classes » Java ArrayList class with Example
Next →
← Prev

Java ArrayList class with Example

By Dinesh Thakur

Java ArrayList class is a part of unified architecture (collection framework) interfaces are present in java.util package and used when we want to change the array size when your Java program run. You know that arrays are that they’re fixed size that must be specified the number of elements when the array created. How to add elements values to an array in java that filled? It’s an easy way to create a more extensive array, and all its elements are copied from the (smaller) source array to the (broader) target array, with the remaining space for new elements. It’s an alternative is to use the ArrayList whose size can change frequently. An instance of Java ArrayList class contains an array that dynamically increased as required so that it relaxes the programmer from the burden of doing this.

Following are few key points to note about ArrayList in Java

• The ArrayList class inherits AbstractList class and implements the List interface.

• Java ArrayList provides automatic resizing , also called a dynamic array; It expands as you add more elements or shrink if elements removed.

• Java ArrayList class retrieve a random element from the list.

• The ArrayList class allows duplicate and null values.

• The ArrayList class is just like arrays, It retrieves the elements by their index.

• The ArrayList class cannot use for primitive types, like int, char. We need a wrapper class for such cases.

• Java ArrayList class can see as similar to vector in C++.

Java ArrayList class

Below are some of the constructors and methods in this class.

ArrayList(): Constructor creates an empty array of size ten.
ArrayList(int n): Constructor creates an empty array of size n.
Boolean add (Object obj): Adds the object obj to the end of the array and returns true.
Object remove(int index): Removes and returns the object at the given index.
Int size(): Returns the number of elements in this array.
Boolean isEmpty(): Returns true if this array does not have any elements; otherwise, returns false.
Object get (int i): Returns (without removing) the element at index i from the array.
Object set(int i, Object obj): Changes the element at index i to obj and returns the previous element at this index.
forEach(Consumer<? super T> action): performs the given action for each element of this stream. The forEach() method added to the Iterable interface.
retainAll?(Collection c): Remove its elements from a list that not contained in the specified collection.
removeIf?(Predicate filter): Removes all of the elements from the List that satisfy the given predicate.
contains?(Object o): Returns true if this list contains the specified element.
remove?(int index): Removes the element at the specified index from a list.
remove(Object o): removes the first occurrence of the specified object from the list.
get?(int index): get the element of the specified position within the list.
subList?(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

spliterator?(): Creates a late-binding and fail-fast Spliterator over the elements in this list.
set?(int index, E element): Replaces the element at the specified position in this list with the specified element.
size?(): Returns the number of elements in this list.
removeAll?(Collection c): Removes from this list all of its elements that are contained in the specified collection.
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.
listIterator?(): Returns a list iterator over the elements in this list (in proper sequence).
listIterator?(int index): Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
isEmpty?(): The isEmpty() method is returns true if this list is empty.
removeRange?(int fromIndex, int toIndex): The removeRange() method is used to removes all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive from a ArrayList object.
Void clear(): The clear() method is used to remove all the elements from a list.
Void add(int index, Object element): This method is used to insert a specific element at a specific index in a ArrayList object.
Void trimToSize(): This method is used to trim a ArrayList instance to the list’s current size.
Int indexOf(Object O): The index the first occurrence of an element in an ArrayList object.
Int lastIndexOf(Object O): This method is used to get the index of the last occurrence of a specific element is either returned or -1 in an ArrayList object.
Object clone(): The clone() method is used to return a shallow copy of an existing ArrayList object.
Object[] toArray(Object[] O): The toArray() method is used to return an array containing all of the elements in this ArrayList object in the correct order (from first to the last element).
Boolean addAll(Collection C): This method used to add all the elements from a specific collection to another list.
Boolean add(Object o): The add(Object o) method used to add a specified element to the ArrayList.
Boolean addAll(int index, Collection C): used for adding all of the elements of Collection c starting at the specified position from a specific collection into the end of the list.

We’ll be covering the following topics in this tutorial:

  • How to create an ArrayList and Add new elements
  • How to create an ArrayList from another collection
  • How to accessing elements from an ArrayList
  • How to remove the elements from an ArrayList
  • Iterating over an ArrayList in java
  • How to Search an elements in an ArrayList
  • How to create an ArrayList of user defined objects

How to create an ArrayList and Add new elements

This example shows:

• Create a List using theArrayList()constructor.

• Add new elements to the List using theadd()method.

import java.util.ArrayList;
import java.util.List;
public class ArrayListEx {
public static void main(String[] args) {
            // Creating an ArrayList of String
         List<String> state = new ArrayList<>();
// Adding new elements to the ArrayList
state.add(“Punjab”);
state.add(“UP”);
state.add(“Rajasthan”);
state.add(“J & K”);
          System.out.println(state);
            // Adding an element at a particular index in an ArrayList
state.add(3,“Himachal”);
          System.out.println(state);
     }
}

[Punjab, UP, Rajasthan, J & K] [Punjab, UP, Rajasthan, Himachal, J & K]

How to create an ArrayList from another collection

This example shows:

• Create a List from another collection using theArrayList(Collection c)constructor.

• Add all the elements from an existing collection to the new the List using theaddAll()method.

import java.util.ArrayList;
import java.util.List;
public class ArrayListFromCollection {
      public static void main(String[] args) {
List<String> Birds =newArrayList<>();
Birds.add(“Crow”);
Birds.add(“Peacock”);
Birds.add(“Sparrow”);
Birds.add(“Ostrich”);
Birds.add(“Pigeon”);
// Creating an ArrayList from another collection
           List<String> BirdsandAnimals = newArrayList<>(Birds);
List<String> Animals = newArrayList<>();
Animals.add(“Dog”);
Animals.add(“Puppy”);
Animals.add(“Turtle”);
Animals.add(“Rabbit”);
Animals.add(“Parrot”);
           // Adding an entire collection to an ArrayList
BirdsandAnimals.addAll(Animals);
          System.out.println(BirdsandAnimals);
      }
}

[Crow, Peacock, Sparrow, Ostrich, Pigeon, Dog, Puppy, Turtle, Rabbit, Parrot]

How to accessing elements from an ArrayList

This example shows:

• For checking if an ArrayList is empty or not using the isEmpty() method.
• Check the size of an ArrayList using the size() method.
• Access element of an index in an ArrayList using the get() method.
• Modify the element of an index in an ArrayList using the set() method.

import java.util.ArrayList;
import java.util.List;
public class AccessElementsFromArrayList {
public static void main(String[] args){
           List<String> continents =newArrayList<>();
           // Check if an ArrayList is empty
           System.out.println(“Is the continents list empty? : “+ continents.isEmpty());
           continents.add(“Asia”);
continents.add(“Africa”);
continents.add(“Europe”);
continents.add(“Australia”);
continents.add(“North America”);

           continents.add(“South America”);

           continents.add(“Antarctica”);
// Find the size of an ArrayList
       System.out.println(“Here are the top “+ continents.size()+” is the world’s largest continent of the seven continents in size and population.”);
          System.out.println(continents);
          // Retrieve the element at a given index
          String largestcontinent = continents.get(0);
          String secondlargest = continents.get(1);
          String smallestcontinent = continents.get(continents.size()–4);
          System.out.println(“World’s largest continent: “+ largestcontinent);
          System.out.println(“Second largest: “+ secondlargest);
          System.out.println(“World’s smallest continent: “+ smallestcontinent);
          // Modify the element at a given index
continents.set(3,“island continent”);
          System.out.println(“Modified seven continents list: “+ continents);
      }
}

Is the continents list empty? : true
Here are the top 7 is the world’s largest continent of the seven continents in size and population.
[Asia, Africa, Europe, Australia, North America, South America, Antarctica] World’s largest continent: Asia
Second largest: Africa
World’s smallest continent: Australia
Modified seven continents list: [Asia, Africa, Europe, island continent, North America, South America, Antarctica]

How to remove the elements from an ArrayList

This example shows:

• Removes the element at the specified index from a list | remove(int index)
• removes the first occurrence of the specified object from the list. | remove(Object o)
• Removes from this list all of its elements that are contained in the specified collection. | removeAll()
• Removes all of the elements from the List that satisfy the given predicate. | removeIf()
• The clear() method is used to remove all the elements from a list. | clear()

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class RemoveObjectsFromArrayList {
      public static void main(String[] args){
List<String> StudentName =newArrayList<>();
StudentName.add(“Manjinder”);
StudentName.add(“Karan”);
StudentName.add(“Sunil”);
StudentName.add(“Rajwinder”);
StudentName.add(“Pankaj”);
StudentName.add(“Punar”);
StudentName.add(“Sandeep”);
System.out.println(“Student List: “+ StudentName);
             // Remove the element at index `5`
StudentName.remove(5);
              System.out.println(“After remove(5): “+ StudentName);
              // Remove the first occurrence of the given element from the ArrayList
              // (The remove() method returns false if the element does not exist in the ArrayList)
              boolean isRemoved = StudentName.remove(“Rajwinder”);
              System.out.println(“After remove(\”Rajwinder\”): “+ StudentName);
             // Remove all the elements that exist in a given collection
             List<String> Removeallelements =newArrayList<>();
Removeallelements.add(“Pankaj”);
Removeallelements.add(“Punar”);
Removeallelements.add(“Sandeep”);
StudentName.removeAll(Removeallelements);
             System.out.println(“After removeAll(Removeallelements): “+ StudentName);
            // Remove all the elements that satisfy the given predicate
StudentName.removeIf(new Predicate<String>(){
                 @Overridepublicboolean test(String s){
                     return s.startsWith(“S”);
                 }
            });
             /*  The above removeIf() call can also be written using lambda
expression like this –

StudentName.removeIf(s -> s.startsWith(“S”))
        */
             System.out.println(“After Removing all elements that start with \”S\”: “+ StudentName);
            // Remove all elements from the ArrayList
StudentName.clear();
            System.out.println(“After clear(): “+ StudentName);
        }
}

Student List: [Manjinder, Karan, Sunil, Rajwinder, Pankaj, Punar, Sandeep]
After remove(5): [Manjinder, Karan, Sunil, Rajwinder, Pankaj, Sandeep]
After remove(“Rajwinder”): [Manjinder, Karan, Sunil, Pankaj, Sandeep]
After removeAll(Removeallelements): [Manjinder, Karan, Sunil]
After Removing all elements that start with “S”: [Manjinder, Karan]
After clear(): []

Iterating over an ArrayList in java

There are various example shows how to iterate over an ArrayList in java

• forEach() method.
• iterator().
• forEachRemaining() method.
• listIterator().
• for-each loop.
• for loop.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ArrayListelements {
        public static void main(String[] args){
           List<String> tvSerials =newArrayList<>();
tvSerials.add(“Tarak Mehta ka Ulta Chasma”);
tvSerials.add(“Tenali Rama”);
tvSerials.add(“Kumkum”);
tvSerials.add(“CID”);
           System.out.println(“=== Iterate using Java 8 forEach”);
tvSerials.forEach(tvSerial –>{
               System.out.println(tvSerial);
           });
           System.out.println(“\n=== Iterate using an iterator() ===”);
Iterator<String> tvSerialIterator = tvSerials.iterator();
           while(tvSerialIterator.hasNext()){
               String tvSerial = tvSerialIterator.next();
System.out.println(tvSerial);
           }
           System.out.println(“\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ===”);
tvSerialIterator = tvSerials.iterator();
tvSerialIterator.forEachRemaining(tvSerial –>{
                 System.out.println(tvSerial);
});
System.out.println(“\n=== Iterate using a listIterator() to traverse in both directions ===”);
           // Here, we start from the end of the list and traverse backwards.
           ListIterator<String> tvSerialListIterator = tvSerials.listIterator(tvSerials.size());
           while(tvSerialListIterator.hasPrevious()){
               String tvSerial = tvSerialListIterator.previous();
               System.out.println(tvSerial);
}
           System.out.println(“\n=== Iterate using simple for-each loop ===”);
           for(String tvSerial: tvSerials){
                System.out.println(tvSerial);
           }
System.out.println(“\n=== Iterate using for loop with index ===”);
for(int i =0; i < tvSerials.size(); i++){
                 System.out.println(tvSerials.get(i));
            }
      }
}

=== Iterate using Java 8 forEach
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using an iterator() ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using an iterator() and Java 8 forEachRemaining() method ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using a listIterator() to traverse in both directions ===
CID
Kumkum
Tenali Rama
Tarak Mehta ka Ulta Chasma

=== Iterate using simple for-each loop ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using for loop with index ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

How to Search an elements in an ArrayList

The example below shows

• Returns true if this list contains the specified element. | contains()
• The index the first occurrence of an element in an ArrayList object. | indexOf()
• This method is used to get the index of the last occurrence of a specific element is either returned or -1 in an ArrayList object. | lastIndexOf()

import java.util.ArrayList;
import
java.util.List;
public class SearchElements {
      public static void main(String[] args){
          List<String> EmployeeName =newArrayList<>();
EmployeeName.add(“Rajan”);
EmployeeName.add(“Punar”);
EmployeeName.add(“Sandeep”);
EmployeeName.add(“Rohit”);
EmployeeName.add(“Daljeet”);
EmployeeName.add(“Raguveer”);
EmployeeName.add(“Mukesh”);
// Check if an ArrayList contains a given element
          System.out.println(“Does Employee Name array contain \”Rohit\”? : “+ EmployeeName.contains(“Rohit”));
          // Find the index of the first occurrence of an element in an ArrayList
System.out.println(“indexOf \”Daljeet\”: “+ EmployeeName.indexOf(“Daljeet”));
          System.out.println(“indexOf \”Renu\”: “+ EmployeeName.indexOf(“Renu”));
          // Find the index of the last occurrence of an element in an ArrayList
          System.out.println(“lastIndexOf \”Raguveer\” : “+ EmployeeName.lastIndexOf(“Raguveer”));
          System.out.println(“lastIndexOf \”Billa\” : “+ EmployeeName.lastIndexOf(“Billa”));
      }
}

Does Employee Name array contain “Rohit”? : true
indexOf “Daljeet”: 4
indexOf “Renu”: -1
lastIndexOf “Raguveer” : 5
lastIndexOf “Billa” : -1

How to create an ArrayList of user defined objects

Below is the example of, how to create an ArrayList of user defined objects

import java.util.ArrayList;
import java.util.List;
class User {
private String Ename;
       private int Salary;
       public User(String Ename, int Salary) {
           this.Ename = Ename;
this
.Salary = Salary;
       }
       public String getEname() {
           return Ename;
       }
       public void setEname(String Ename) {
           this.Ename = Ename;
}
public int getSalary() {
return Salary;
       }
       public void setSalary(int Salary) {
           this.Salary = Salary;
       }
}
public class ArrListUDO {
        public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User(“Punardeep”, 250000));
users.add(new User(“Sandeep”, 460000));
users.add(new User(“Rohit”, 550000));
users.forEach(user –> {
                  System.out.println(“Name : “ + user.getEname() + “, Salary : “ + user.getSalary());       

             });
        }
}

Name : Punardeep, Salary : 250000
Name : Sandeep, Salary : 460000
Name : Rohit, Salary : 550000

You’ll also like:

  1. Inner class in java with Example
  2. Java Class Rectangle Example
  3. Nested Class in Java Example
  4. Class methods in Java
  5. Singleton Class in Java with Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW