Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

ArrayList Program in Java

Last Updated on February 9, 2024 by Abhishek Sharma

In Java programming, ArrayList is a widely used data structure that provides dynamic array-like functionality. It belongs to the Java Collections Framework and allows for the creation of resizable arrays, enabling flexible storage of elements. With ArrayList, you can add, remove, or access elements at any position within the list, making it a versatile and powerful tool for managing collections of objects. In this article, we will explore the concept of ArrayList in Java, its features, common operations, and frequently asked questions.

Introduction to Arraylist Program in Java

ArrayList program in Java is a resizable dynamic array that can store elements of any data type. It is part of the Java Collections Framework and provides several methods for adding, removing, and accessing elements within the list. Arraylists are useful when the size of the collection is not known in advance or needs to change dynamically. They are implemented using an underlying array that is resized as elements are added or removed and can be used to store both primitive data types and objects.

Arraylist Methods in Java

Here are some common methods of Arraylist in Java:

  • add(): It defines that an element Adds to the end of the Arraylist.
  • add(index, element): Inserts an element at a specific index in the Arraylist.
  • remove(index): Removes the element at a specific index in the Arraylist.
  • get(index): Returns the element at a specific index in the ArrayList.
  • size(): It defines the number of elements in the Arraylist that is returned using the size operator.
  • clear(): Removes all elements from the Arraylist.
  • indexOf(element): It defines the index of the first occurrence of the specified element in the Arraylist that has been returned.
  • lastIndexOf(element): It defines the index of the last occurrence of the specified element in the ArrayList that has returned.
  • contains(element): Returns true if the ArrayList contains the specified element, false otherwise.
  • isEmpty(): Returns true if the Arraylist is empty, false otherwise.
  • toArray(): Converts the Arraylist to an array.
  • sort(): Sorts the Arraylist in ascending order.

Operations Performed in Arraylist Program in Java

Here are some common operations that can be performed with Arraylist program in Java:

  • Adding elements: This can add elements to the end of the ArrayList using the add() method, or insert them at a specific index using the add(index, element) method.

    Example code:

    /* package whatever; // don't place package name! */
    
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
             ArrayList<String> names = new ArrayList<>();
            names.add("Sharma");
            names.add("Gourav");
            names.add("Deepthi");
            System.out.println(names);
        }
    }
     
  • Removing elements: This can remove elements from the ArrayList using the remove() method, which removes the element at a specific index, or the remove(Object) method, which removes the first occurrence of a specific element.

    Example code:

    /* package whatever; // don't place package name! */
    
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
            ArrayList<String> names = new ArrayList<>();
            names.add("Sharma");
            names.add("Gourav");
            names.add("Deepthi");
            names.remove(1);
            System.out.println(names);
        }
    }
     
  • Accessing elements: This can access elements in the ArrayList using the get() method, which returns the element at a specific index.

Example code:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        ArrayList<String> names = new ArrayList<>();
        names.add("Sharma");
        names.add("Gourav");
        names.add("Deepthi");
        String name = names.get(1);
        System.out.println(name);
    }
}
 
  • Searching elements: This can search for elements in the ArrayList using the indexOf() method, which returns the index of the first occurrence of a specific element, or the lastIndexOf() method in the index of the last occurrence of a specific element has returned.

    Example code:

    /* package whatever; // don't place package name! */
    
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
             ArrayList<String> names = new ArrayList<>();
            names.add("Sharma");
            names.add("Gourav");
            names.add("Deepthi");
            int index = names.indexOf("Gourav");
            System.out.println(index);
        }
    }
     
  • Sorting elements: This can sort the elements in the ArrayList using the sort() method or the Collections. sort() method.

    Example code:

    /* package whatever; // don't place package name! */
    
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
            ArrayList<String> names = new ArrayList<>();
            names.add("Sharma");
            names.add("Gourav");
            names.add("Deepthi");
            Collections.sort(names);
            System.out.println(names);
        }
    }
     
  • Checking the size and emptiness: This can check the number of elements in the ArrayList using the size() method, or check whether the ArrayList is empty using the isEmpty() method.

  • Converting to array: This can convert the ArrayList to an array using the toArray() method.

  • Iterating over elements: You can iterate over the elements in the ArrayList using a for loop or a for-each loop, or using an iterator or a list iterator.

Example of Arraylist Program in Java

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
         ArrayList<Integer> list = new ArrayList<Integer>();

      // Add some elements to the ArrayList
      list.add(10);
      list.add(20);
      list.add(30);
      list.add(40);

      // Print the ArrayList
      System.out.println("ArrayList: " + list);

      // Remove an element from the ArrayList
      list.remove(2);

      // Print the updated ArrayList
      System.out.println("Updated ArrayList: " + list);

      // Access an element in the ArrayList
      int element = list.get(1);

      // Print the accessed element
      System.out.println("Accessed Element: " + element);

      // Iterate over the elements in the ArrayList
      System.out.print("Iterating over ArrayList: ");
      for (int i = 0; i < list.size(); i++) 
         System.out.print(list.get(i) + " ");
    }
}
 

Explanation of arraylist program in java:
In the Arraylist program in Java, we first create a new ArrayList and add some integer values to it. We then print the ArrayList to the console using the println() method. Then, we remove an element from the ArrayList using the remove() method and print the updated ArrayList to the console. We then access an element in the ArrayList using the get() method and print the accessed element to the console. Finally, we iterate over the elements in the Arraylist program in Java by using a for loop and then printing each element to the console.

Advantages of Arraylist Program in Java

Here are some advantages of Arraylist program in Java:

  • ArrayLists can store elements of any data type.
  • ArrayLists give efficient methods for adding, removing, and accessing elements.
  • It can be easily sorted, searched, and iterated over.
  • It can be serialized and deserialized, allowing for easy storage and retrieval of data.
  • They are easy to use and widely used in Java programming.

Disadvantages of Arraylist Program in Java

Here are some disadvantages of ArrayList in Java:

  • Arraylists have slower performance when elements are frequently added or removed from the middle of the list.
  • Arraylists program in java uses more memory than arrays when storing small numbers of elements.
  • Arraylists program in java does not provide a direct way to sort or search for elements in the list, requiring additional code or the use of Collections class methods.
  • Arraylists program in java is not thread-safe by default, which can cause issues in concurrent programming environments.
  • Arraylists program in java can only store objects and not primitive data types, requiring additional code to convert primitives to objects.

Conclusion
In conclusion, ArrayList is a fundamental data structure in Java that offers dynamic and flexible array-like functionality. Its ability to resize dynamically, along with its extensive range of methods for adding, removing, and accessing elements, makes it an essential tool for managing collections of objects in Java programs. By understanding how to use ArrayList effectively, Java developers can create efficient and scalable applications that handle collections of varying sizes with ease.

Frequently Asked Questions(FAQs) related to ArrayList Program in Java

Below are some of the FAQs related to ArrayList Program in Java:

1. What is an ArrayList in Java, and how does it differ from a regular array?
An ArrayList in Java is a resizable array implementation of the List interface. Unlike regular arrays, ArrayLists can dynamically resize themselves, allowing for the addition and removal of elements without needing to specify a fixed size in advance.

2. How do I create an ArrayList in Java?
You can create an ArrayList in Java using the following syntax:

ArrayList arrayListName = new ArrayList();

Replace "Type" with the type of elements you want to store in the ArrayList, and "arrayListName" with the name you want to assign to your ArrayList instance.

3. What are some common operations performed on ArrayLists in Java?
Common operations performed on ArrayLists include adding elements (using methods like add()), removing elements (using methods like remove()), accessing elements (using methods like get()), checking if an element exists (using methods like contains()), and determining the size of the ArrayList (using the size() method).

4. How do I iterate through an ArrayList in Java?
You can iterate through an ArrayList in Java using various methods, such as using a for loop, an enhanced for loop (for-each loop), or an Iterator. Here’s an example using a for-each loop:

for (Type element : arrayListName) {
    // Do something with each element
}

5. Can an ArrayList store primitive data types in Java?
No, ArrayLists in Java can only store objects, not primitive data types. However, Java provides wrapper classes (such as Integer, Double, etc.) for primitive data types, allowing you to store them in ArrayLists indirectly.

6. What happens if I try to access or remove an element from an index that is out of bounds in an ArrayList?
If you try to access or remove an element from an index that is out of bounds in an ArrayList, Java will throw an IndexOutOfBoundsException. It’s essential to ensure that the index is within the valid range (0 to size() – 1) before performing such operations to avoid runtime errors.

Leave a Reply

Your email address will not be published. Required fields are marked *