Java

Java – ArrayList With Examples

The Arraylist class is built on an Array data structure and implements the List interface. Because of its usefulness and adaptability, it is frequently utilized. A resizable array implementation of the List interface is called an array list in Java. It accepts any items, including null, and provides all optional list operations. Because it’s a very suitable substitute for conventional Java arrays, the majority of developers choose arraylists over arrays.

Array vs arraylist in java

The primary distinction between an array and an arraylist is that an arraylist may dynamically expand and contract whereas an array cannot.

If an array is already full, you cannot add any more items to it since arrays have defined lengths. Similar to this, if an ArrayList has a certain amount of entries deleted, the memory use does not decrease.

In contrast, ArrayList may dynamically expand and contract as entries are added to and removed from it. The ArrayList class contains a number of helpful methods that may simplify our process.

ArrayList in Java

  • ArrayList may automatically expand and contract in response to the insertion and deletion of items.
    There may be duplicate items in an array list.
  • The items in an array list appear in the same order in which they were added since the array list retains the insertion order.
  • The array list is not synced. Anyhow you can synchronize it

Hierarchy of ArrayList class in Java

The List interface, which extends the Collection interface, is implemented by the ArrayList class.

Arraylist in Java declaration

An ArrayList of the String type may be declared in the following way:

ArrayList<String> list=new ArrayList<>();

Declaring an ArrayList of Integer type looks like this:

ArrayList<Integer> list=new ArrayList<>();

Adding elements to Arraylist in java

Adding Element in ArrayList at specified position:

Using the add() function, you may add items to an ArrayList. There are a few versions of this strategy that you might apply depending on the situation.

You may, for instance, use the add() function to add the element at the end of the List by calling it as follows:

arrList.add("Steve"); //This will add "Steve" at the end of List

You may use the add() function and the index argument to add the element to the ArrayList at the desired place as follows:

arrList.add(3, "Steve"); //This will add "Steve" at the fourth position

Let’s write the whole program:

import java.util.*;  
class JavaExample{  
   public static void main(String args[]){  
      ArrayList<String> arrList=new ArrayList<String>();  
      arrList.add("Steve");
      arrList.add("Tim");
      arrList.add("Lucy");
      arrList.add("Pat");
      arrList.add("Angela");
      arrList.add("Tom");
  
      //displaying elements
      System.out.println(arrList);
  
      //Adding "Steve" at the fourth position
      arrList.add(3, "Steve");
  
      //displaying elements
      System.out.println(arrList);
   }  
}

Output:

[Steve, Tim, Lucy, Pat, Angela, Tom]
[Steve, Tim, Lucy, Steve, Pat, Angela, Tom]

Note: Because the index begins at 0, index 3 would really indicate position 4, not 3.

Change an element in ArrayList

The set method may be used to modify an ArrayList element. This function changes the element already existing at the provided index with the new supplied element after receiving the index and new element.

In the example below, we have specified “Lucy” as the new element and “0” as the index in the set() function. The procedure replaced the existing String element “Jim” at position 0 with the new String element “Lucy.”

import java.util.ArrayList;
public class JavaExample {
   public static void main(String[] args) {
      ArrayList<String> names = new ArrayList<String>();
      names.add("Jim");
      names.add("Jack");
      names.add("Ajeet");
      names.add("Chaitanya");
      names.set(0, "Lucy");
      System.out.println(names);
   }
}

Output:
Update element example

How to remove element from Arraylist in Java?

Removing Element from ArrayList:

A list’s items may be removed using the remove() function. There are a few versions to this procedure, much as the add() method.

For example:

import java.util.*;
class JavaExample{
   public static void main(String args[]){
      ArrayList<String> alist=new ArrayList<String>(); 
      alist.add("Steve");
      alist.add("Tim");
      alist.add("Lucy");
      alist.add("Pat");
      alist.add("Angela");
      alist.add("Tom");

      //displaying elements
      System.out.println(alist);

      //Removing "Steve" and "Angela"
      alist.remove("Steve");
      alist.remove("Angela");

      //displaying elements
      System.out.println(alist);

      //Removing 3rd element
      alist.remove(2);

      //displaying elements
      System.out.println(alist);
   }
}

Output:

[Steve, Tim, Lucy, Pat, Angela, Tom]
[Tim, Lucy, Pat, Tom]
[Tim, Lucy, Tom]

Iterating ArrayList

Here, the members of the ArrayList are iterated using an extended for loop. This is one of the finest methods for iterating a string-type ArrayList.

import java.util.*;  
class JavaExample{  
  public static void main(String args[]){  
     ArrayList<String> alist=new ArrayList<String>();  
     alist.add("Gregor Clegane");  
     alist.add("Khal Drogo");  
     alist.add("Cersei Lannister");  
     alist.add("Sandor Clegane"); 
     alist.add("Tyrion Lannister");
  
     //iterating ArrayList
     for(String str:alist)  
        System.out.println(str);  
     }  
}

Output:

Gregor Clegane
Khal Drogo
Cersei Lannister
Sandor Clegane
Tyrion Lannister

There are several more ways to loop an ArrayList:

  • Using iterator
  • Using enhanced for-each loop.
  • Using list iterator
  • Using for loop
  • Using forEachRemaining() method.

ArrayList Size

We can use size() method of ArrayList to find the number of elements in an ArrayList.

import java.util.ArrayList;
public class JavaExample {
   public static void main(String[] args) {
      ArrayList<Integer> numbers = new ArrayList<Integer>();
      numbers.add(1);
      numbers.add(7);
      numbers.add(5);
      numbers.add(6);
      System.out.println("Number of elements in ArrayList: "+numbers.size());
   }
}

Output:
ArrayList Size

Sort ArrayList

An ArrayList may be sorted using the sort() function of the Collections utility class. The java.util package contains this class. In the example that follows, a list of String type objects is sorted alphabetically. This technique also applies to lists of numbers (such as Integer type ArrayList).

import java.util.ArrayList;
import java.util.Collections;

public class JavaExample {
   public static void main(String[] args) {
      ArrayList<String> fruits = new ArrayList<String>();
      fruits.add("Orange");
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Pineapple");
      Collections.sort(fruits);

      for (String str : fruits) {
         System.out.println(str);
      }
   }
}

Output:
Sorting example output

ArrayList Example in Java

The creation, initialization, addition, and removal of members from an ArrayList are all shown in this example. We have an ArrayList of “String” type in this example. Using the method add, we are adding 5 String elements to the ArrayList (String E). The element at the end of the ArrayList is added using this technique.

Then, using the function add, we are adding two additional members to the ArrayList (int index, String E). The provided element is added using this technique at the stated index, where index 0 denotes the first position, index 1 the second place, and so on.

Then, the ArrayList’s “Chaitanya” and “Harry” entries are being deleted. Using the function remove once more, we eliminated the ArrayList’s second entry (int index).

import java.util.*;
public class JavaExample {
   public static void main(String args[]) {
      /* Creating ArrayList of type "String" which means
       * we can only add "String" elements
       */
      ArrayList<String> obj = new ArrayList<String>();

      /*This is how we add elements to an ArrayList*/
      obj.add("Ajeet");
      obj.add("Harry");
      obj.add("Chaitanya");
      obj.add("Steve");
      obj.add("Anuj");

      // Displaying elements
      System.out.println("Original ArrayList:");
      for(String str:obj)
         System.out.println(str);

      /* Add element at the given index
       * obj.add(0, "Rahul") - Adding element "Rahul" at first position
       * obj.add(1, "Justin") - Adding element "Justin" at second position
       */
      obj.add(0, "Rahul");
      obj.add(1, "Justin");

      // Displaying elements
      System.out.println("ArrayList after add operation:");
      for(String str:obj)
         System.out.println(str);

      //Remove elements from ArrayList like this
      obj.remove("Chaitanya"); //Removes "Chaitanya" from ArrayList
      obj.remove("Harry"); //Removes "Harry" from ArrayList

      // Displaying elements
      System.out.println("ArrayList after remove operation:");
      for(String str:obj)
         System.out.println(str);

      //Remove element from the specified index
      obj.remove(1); //Removes Second element from the List

      // Displaying elements
      System.out.println("Final ArrayList:");
      for(String str:obj)
         System.out.println(str);
   }
}

Output:
Original ArrayList:
Ajeet
Harry
Chaitanya
Steve
Anuj
ArrayList after add operation:
Rahul
Justin
Ajeet
Harry
Chaitanya
Steve
Anuj
ArrayList after remove operation:
Rahul
Justin
Ajeet
Steve
Anuj
Final ArrayList:
Rahul
Ajeet
Steve
Anuj

Related Articles

Leave a Reply

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

Back to top button