Array List in Java

Array List

When you create an array in java, you can’t change its size. If you need to remove or add items to an array, you must create a new one. You can use ArrayList, add items, and remove items anytime you want. To use array list, you must import java.util.ArrayList;

Syntax

import java.util.ArrayList; // First Import this

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

Add Items To Array List

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

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

        names.add("Tanisha Thapa");
        names.add("Mamita Shrestha");
        names.add("Shradha Shrestha");
        names.add("Anar Singh Basnet");
        
        // to print details
        for(String name: names){
            System.out.println(name);
        }

    }
}
Show Output

Remove Items From Array List

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

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

        names.add("Tanisha Thapa");
        names.add("Mamita Shrestha");
        names.add("Shradha Shrestha");
        names.add("Anar Singh Basnet");

        names.remove("Tanisha Thapa"); // this will remove name
        
        // to print details
        for(String name: names){
            System.out.println(name);
        }

    }
}
Show Output

To Access Array Item

In the java build-in array, we can use names[0]; to get the item at index 0, but in array list, we use names.get(0); to access array item.

To Change Array Item

In java build in array we can use names[0] = "Ram"; to change the item at index 0, but in array list we use names.set(0, "Ram"); to change array item.

Some Useful Methods For ArrayList

Methods Description
names.get(0); Get item at index 0.
names.set(0); Set item at index 0.
names.remove(0); Removes item at index 0.
names.clear(); Clear all items of array.
names.size(); To get size of an array.

How To Sort ArrayList

You can also sort array lists in ascending or descending order. You can sort for strings as well as numbers. You can import java.util.Collections; for sorting.

Example

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

public class Main {
    public static void main(String[] args) {

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

        names.add("Tanisha Thapa");
        names.add("Mamita Shrestha");
        names.add("Shradha Shrestha");
        names.add("Anar Singh Basnet");

        // sort names
        Collections.sort(names);

        // to print details
        for(String name: names){
            System.out.println(name);
        }

    }
}
Show Output

Sort ArrayList Decending

Collections.sort(names, Collections.reverseOrder());
Info

Note: Replace names with your list variable.