Array List

What is an ArrayList in Java?

In Java, the ArrayList class is used to create resizable arrays, effectively implementing the List interface from the collections framework. Unlike fixed-size built-in arrays, ArrayLists in Java offer the advantage of dynamic resizing. This means that elements can be easily added or removed from the ArrayList as needed, providing users with convenient memory management capabilities.

Syntax:

ArrayList<Type> arrayList= new ArrayList<>()

//Here, Type indicates the type of an arraylist.

//For example

// create Integer type arraylist

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

// create String type arraylist

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

In the provided code snippets, we used Integer instead of int when declaring the ArrayList. This is because ArrayLists in Java cannot directly store primitive data types; they can only hold objects. To work around this limitation, we use the corresponding wrapper classes, which are objects that encapsulate primitive types.

Important characteristics of the ArrayList:

  1. Resizable Array: ArrayList is based on a resizable array or growable array data structure.
  2. Duplicate Elements: ArrayList allows duplicate elements, meaning the same value can appear multiple times in the list.
  3. Preserved Insertion Order: The order in which elements are inserted into the ArrayList is maintained, and elements can be accessed based on their index.
  4. Heterogeneous Objects: ArrayList can hold elements of different data types, allowing for a mix of various objects in the same list.
  5. Null Insertion: It is possible to insert “null” values into an ArrayList.

Useful methods in ArrayList

ArrayList provides a variety of useful methods to manage elements within the list. Some of the most commonly used methods include:

  1. Adding Elements:
    • add(E element): Appends the specified element to the end of the ArrayList.
    • add(int index, E element): Inserts the element at the specified index, shifting existing elements to the right.
  2. Accessing Elements:
    • get(int index): Retrieves the element at the specified index.
    • indexOf(Object o): Returns the index of the first occurrence of the specified element, or -1 if not found.
    • lastIndexOf(Object o): Returns the index of the last occurrence of the specified element, or -1 if not found.
  3. Removing Elements:
    • remove(int index): Removes the element at the specified index.
    • remove(Object o): Removes the first occurrence of the specified element, if present.
    • clear(): Removes all elements from the ArrayList, making it empty.
  4. Size and Capacity:
    • size(): Returns the number of elements in the ArrayList.
    • isEmpty(): Checks if the ArrayList is empty.
    • ensureCapacity(int minCapacity): Increases the capacity of the ArrayList to at least the given minimum capacity.
    • trimToSize(): Reduces the internal array size to the actual number of elements in the list.
  5. Iterating through ArrayList:
    • Using a for loop, for-each loop, or an iterator to traverse the elements in the list.
  6. List Iteration and Modification:
    • listIterator(): Returns a list iterator over the elements in the list.
    • listIterator(int index): Returns a list iterator over the elements, starting at the specified index.
  7. Sublist Operations:
    • subList(int fromIndex, int toIndex): Returns a view of the portion of the ArrayList between the specified fromIndex, inclusive, and toIndex, exclusive.

Operations performed in ArrayList

1. Adding Elements

import java.util.ArrayList;

public class AddingElementsExample {
    public static void main(String[] args) {
        // Create an ArrayList of integers
        ArrayList<Integer> numbers = new ArrayList<>();

        // Adding elements using add(E element)
        numbers.add(10); // Add 10 to the end of the ArrayList
        numbers.add(30); // Add 30 to the end of the ArrayList
        numbers.add(40); // Add 40 to the end of the ArrayList

        // Display the ArrayList
        System.out.println("After adding elements using add(E element): " + numbers);

        // Adding elements using add(int index, E element)
        numbers.add(1, 20); // Add 20 at index 1
        numbers.add(3, 35); // Add 35 at index 3

        // Display the ArrayList after adding elements at specific positions
        System.out.println("After adding elements using add(int index, E element): " + numbers);
    }
}

Output:

After adding elements using add(E element): [10, 30, 40]
After adding elements using add(int index, E element): [10, 20, 30, 35, 40]

Explanation of this code:

  1. Create an ArrayList of integers: ArrayList<Integer> numbers = new ArrayList<>(); Here, The code declares and initializes an ArrayList named ‘numbers‘ to store Integer objects.
  2. Adding elements using add(E element):
    • numbers.add(10); :- Adds the integer value 10 to the end of the ArrayList.
    • numbers.add(30); :- Adds the integer value 30 to the end of the ArrayList.
    • numbers.add(40); :- Adds the integer value 40 to the end of the ArrayList.
  3. Display the ArrayList using System.out.println: System.out.println(“After adding elements using add(E element): ” + numbers); This line will print the ArrayList after adding elements using add(E element) to the console. After adding elements using add(E element): [10, 30, 40]
  4. Adding elements using add(int index, E element):
    • numbers.add(1, 20); :- Adds the integer value 20 at index 1. This will insert 20 between the elements 10 and 30. The ArrayList will become [10, 20, 30, 40].
    • numbers.add(3, 35); :- Adds the integer value 35 at index 3. This will insert 35 between the elements 30 and 40. The ArrayList will become [10, 20, 30, 35, 40].
  5. Display the ArrayList after adding elements at specific positions using System.out.println: System.out.println(“After adding elements using add(int index, E element): ” + numbers); This line will print the ArrayList after adding elements at specific positions using add(int index, E element) to the console. It will output: After adding elements using add(int index, E element): [10, 20, 30, 35, 40]

2. Accessing Elements:

import java.util.ArrayList;

public class AccessingElementsExample {
    public static void main(String[] args) {
        // Create an ArrayList of strings
        ArrayList<String> fruits = new ArrayList<>();

        // Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Banana");
        fruits.add("Orange");

        // Accessing elements using get(int index)
        String firstFruit = fruits.get(0);
        String thirdFruit = fruits.get(2);

        System.out.println("First fruit: " + firstFruit);
        System.out.println("Third fruit: " + thirdFruit);

        // Accessing the index of an element using indexOf(Object o)
        int bananaIndex = fruits.indexOf("Banana");
        int pineappleIndex = fruits.indexOf("Pineapple");

        System.out.println("Index of 'Banana': " + bananaIndex);
        System.out.println("Index of 'Pineapple': " + pineappleIndex);

        // Accessing the last index of an element using lastIndexOf(Object o)
        int lastBananaIndex = fruits.lastIndexOf("Banana");
        int lastPineappleIndex = fruits.lastIndexOf("Pineapple");

        System.out.println("Last index of 'Banana': " + lastBananaIndex);
        System.out.println("Last index of 'Pineapple': " + lastPineappleIndex);
    }
}

Output:

First fruit: Apple
Third fruit: Mango
Index of ‘Banana’: 1
Index of ‘Pineapple’: -1
Last index of ‘Banana’: 3
Last index of ‘Pineapple’: -1

Explanation of this code:

  • In this example, we create an ArrayList called fruits, which holds strings. We add several fruits to the list, including duplicates like “Banana.”
  • We then use the get(int index) method to access the first and third fruits (at indices 0 and 2, respectively) and display them.
  • Next, we use the indexOf(Object o) method to find the index of “Banana” and “Pineapple” in the ArrayList. Since “Pineapple” is not present in the list, its index is -1.
  • Finally, we use the lastIndexOf(Object o) method to find the last index of “Banana” and “Pineapple” in the ArrayList. As “Pineapple” is not present in the list, its last index is also -1.

3. Removing Elements:

import java.util.ArrayList;

public class RemovingElementsExample {
    public static void main(String[] args) {
        // Create an ArrayList of strings
        ArrayList<String> fruits = new ArrayList<>();

        // Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Orange");
        fruits.add("Pineapple");

        // Display the ArrayList
        System.out.println("Original ArrayList: " + fruits);

        // Removing element using remove(int index)
        int indexToRemove = 2; // Remove element at index 2 (Mango)
        fruits.remove(indexToRemove);

        // Display the ArrayList after removing element at the specified index
        System.out.println("After removing element at index " + indexToRemove + ": " + fruits);

        // Removing element using remove(Object o)
        boolean isRemoved = fruits.remove("Banana");

        // Display the ArrayList after removing element using remove(Object o)
        if (isRemoved) {
            System.out.println("After removing 'Banana': " + fruits);
        } else {
            System.out.println("'Banana' not found in the ArrayList.");
        }

        // Clearing the ArrayList using clear()
        fruits.clear();

        // Display the ArrayList after clearing
        System.out.println("After clearing the ArrayList: " + fruits);
    }
}

Output:

Original ArrayList: [Apple, Banana, Mango, Orange, Pineapple]
After removing element at index 2: [Apple, Banana, Orange, Pineapple]
After removing ‘Banana’: [Apple, Orange, Pineapple]
After clearing the ArrayList: []

Explanation of this code:

  1. An ArrayList named ‘fruits’ is created to store strings.
  2. Five string elements (“Apple”, “Banana”, “Mango”, “Orange”, and “Pineapple”) are added to the ‘fruits‘ ArrayList using the add(E element) method.
  3. The original contents of the ‘fruits‘ ArrayList are displayed using System.out.println().
  4. An element at a specific index (index 2) is removed from the ‘fruits’ ArrayList using the remove(int index) method.
  5. The contents of the ‘fruits’ ArrayList are displayed again after removing the element at the specified index.
  6. An element with the value “Banana” is removed from the ‘fruits’ ArrayList using the remove(Object o) method. The method returns a boolean value indicating if the removal was successful.
  7. The contents of the ‘fruits’ ArrayList are displayed again after removing the element using its value. If “Banana” was found and removed, it shows the updated ArrayList; otherwise, it prints a message stating that “Banana” was not found in the list.
  8. All elements in the ‘fruits’ ArrayList are cleared using the clear() method.
  9. The contents of the ‘fruits’ ArrayList are displayed after clearing it. As a result, the ArrayList will be empty.

4. Size and Capacity of Elements:

import java.util.ArrayList;

public class SizeAndCapacityExample {
    public static void main(String[] args) {
        // Create an ArrayList of strings
        ArrayList<String> colors = new ArrayList<>();

        // Check if the ArrayList is empty
        System.out.println("Is ArrayList empty? " + colors.isEmpty());

        // Add elements to the ArrayList
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Yellow");
        colors.add("Orange");

        // Display the ArrayList
        System.out.println("ArrayList elements: " + colors);

        // Get the size of the ArrayList
        int size = colors.size();
        System.out.println("Size of the ArrayList: " + size);

        // Check if the ArrayList is empty
        System.out.println("Is ArrayList empty? " + colors.isEmpty());

        // Ensure minimum capacity of the ArrayList
        int minCapacity = 10;
        colors.ensureCapacity(minCapacity);

        // Display the ArrayList after ensuring capacity
        System.out.println("ArrayList elements after ensuring capacity: " + colors);

        // Trim the capacity of the ArrayList to the current size
        colors.trimToSize();

        // Display the ArrayList after trimming
        System.out.println("ArrayList elements after trimming: " + colors);
    }
}

Output:

Is ArrayList empty? true
ArrayList elements: [Red, Green, Blue, Yellow, Orange]
Size of the ArrayList: 5
Is ArrayList empty? false
ArrayList elements after ensuring capacity: [Red, Green, Blue, Yellow, Orange]
ArrayList elements after trimming: [Red, Green, Blue, Yellow, Orange]

Explanation of this code:

  1. ArrayList<String> colors = new ArrayList<>(); :- This line declares and initializes an ArrayList named colors that will store elements of type String.
  2. System.out.println(“Is ArrayList empty? ” + colors.isEmpty()); :- This line checks if the colors ArrayList is empty using the isEmpty() method. Initially, it will be empty, so the output will be true.
  3. Adding elements to the ArrayList: colors.add(“Red”); colors.add(“Green”); colors.add(“Blue”); colors.add(“Yellow”); colors.add(“Orange”); .This code block adds five elements to the colors ArrayList.
  4. System.out.println(“ArrayList elements: ” + colors); :- This line displays the elements of the colors ArrayList. It will output something like: ArrayList elements: [Red, Green, Blue, Yellow, Orange].
  5. int size = colors.size(); :- This line gets the current size of the colors ArrayList using the size() method.
  6. System.out.println(“Size of the ArrayList: ” + size); :- This line prints the size of the colors ArrayList.
  7. System.out.println(“Is ArrayList empty? ” + colors.isEmpty()); :- This line checks if the colors ArrayList is empty again after adding elements. Since elements have been added, the output will be false.
  8. int minCapacity = 10; :- This line declares an integer variable minCapacity with a value of 10.
  9. colors.ensureCapacity(minCapacity); :- This line ensures that the colors ArrayList has a minimum capacity of 10. This means the ArrayList will allocate space for at least 10 elements, even if the current number of elements is less than that. However, the size of the ArrayList will still be the same as the number of elements added so far.
  10. System.out.println(“ArrayList elements after ensuring capacity: ” + colors); :- This line displays the elements of the colors ArrayList after ensuring its capacity. It will show the same elements as before, but the ArrayList now has a minimum capacity of 10.

5. Changing Elements

To modify elements in an ArrayList, use the set() method. Since the ArrayList is indexed, you specify the index of the element to change, along with the updated value to replace it.

import java.util.ArrayList;

public class ChangingElementsExample {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        colors.set(1, "Yellow"); // Change "Green" to "Yellow"

        System.out.println(colors); // Output: [Red, Yellow, Blue]
    }
}

Output:

[Red, Yellow, Blue]

Explanation of this code:

  1. ArrayList<String> colors = new ArrayList<>(); :- This line declares and initializes an ArrayList named colors that will store elements of type String.
  2. colors.add(“Red”); :- This line adds the string “Red” to the colors ArrayList.
  3. colors.add(“Green”); :- This line adds the string “Green” to the colors ArrayList. At this point, the ArrayList will contain two elements: “Red” and “Green”.
  4. colors.add(“Blue”); :- This line adds the string “Blue” to the colors ArrayList. Now, the ArrayList will contain three elements: “Red”, “Green”, and “Blue”.
  5. colors.set(1, “Yellow”); :- This line uses the set(index, element) method to change the element at index 1 of the colors ArrayList. The set() method replaces the element at the specified index with the new element provided as the second argument. In this case, it replaces the element at index 1 (which is “Green”) with “Yellow”. After this operation, the ArrayList will be: [“Red”, “Yellow”, “Blue”].
  6. System.out.println(colors); :- This line prints the contents of the colors ArrayList to the console. The output will be: [Red, Yellow, Blue].

6. Iterating the ArrayList

Various methods are available to iterate through an ArrayList. The common ones include using a basic for loop with the get() method to access elements by index and using an advanced for loop (enhanced for loop).

import java.util.ArrayList;

public class ArrayListIterationExample {
    public static void main(String[] args) {
        // Create an ArrayList of integers
        ArrayList<Integer> numbers = new ArrayList<>();

        // Add elements to the ArrayList
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        // Using a basic for loop to iterate through the ArrayList
        System.out.println("Using basic for loop:");
        for (int i = 0; i < numbers.size(); i++) {
            int element = numbers.get(i);
            System.out.println("Element at index " + i + ": " + element);
        }

        // Using an advanced (enhanced) for loop to iterate through the ArrayList
        System.out.println("\nUsing advanced for loop:");
        for (int number : numbers) {
            System.out.println("Element: " + number);
        }
    }
}

Output:

Using basic for loop:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Using advanced for loop:
Element: 10
Element: 20
Element: 30
Element: 40
Element: 50

Explanation of this code:

  1. An ArrayList<Integer> named numbers is created to store integers.
  2. Five elements (10, 20, 30, 40, 50) are added to the numbers ArrayList using the add() method.
  3. A basic for loop is used to iterate through the numbers ArrayList. The loop runs from index 0 to one less than the size of the ArrayList (numbers.size() – 1). Inside the loop, it retrieves each element using the get() method and prints the element’s value along with its index.
  4. An advanced (enhanced) for loop (foreach loop) is used to iterate through the numbers ArrayList. This loop automatically iterates over each element in the numbers ArrayList and assigns the element’s value to the variable number. Inside the loop, it prints each element’s value.

7. ArrayList Sort:

ArrayList sorting refers to arranging the elements in ascending or natural order (if elements are comparable) or in a custom order (if a comparator is provided).

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

public class ArrayListSortExample {
    public static void main(String[] args) {
        // Create an ArrayList of integers
        ArrayList<Integer> numbers = new ArrayList<>();

        // Add elements to the ArrayList
        numbers.add(30);
        numbers.add(10);
        numbers.add(50);
        numbers.add(20);
        numbers.add(40);

        // Sort the ArrayList in ascending order
        Collections.sort(numbers);

        // Display the sorted ArrayList
        System.out.println("Sorted ArrayList: " + numbers);
    }
}

Output:

Sorted ArrayList: [10, 20, 30, 40, 50]

Explanation of this code:

  1. An ArrayList<Integer> named numbers is created to store integers.
  2. Five elements (30, 10, 50, 20, 40) are added to the numbers ArrayList using the add() method. The elements are added in an unordered manner.
  3. The Collections.sort() method is used to sort the numbers ArrayList in ascending order. This method arranges the elements in ascending order based on their natural ordering (for integers, it means from the smallest to the largest).
  4. The sorted numbers ArrayList is then displayed using the System.out.println() method. The Collections.sort() method modifies the numbers ArrayList in-place, arranging its elements in ascending order. The output shows the sorted numbers ArrayList with elements [10, 20, 30, 40, 50].

It’s important to note that this sorting method works for sorting integers because they have a natural ordering. For more complex objects or custom sorting criteria, you may need to implement the Comparable interface or use a custom comparator.

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close