Provide Best Programming Tutorials

ArrayList In Java

Following are few key points to note about ArrayList in Java –

  • An ArrayList is a re-sizable array, also called a dynamic array. It grows its size to accommodate new elements and shrinks the size when the elements are removed.

  • ArrayList internally uses an array to store the elements. Just like arrays, It allows you to retrieve the elements by their index.

  • Java ArrayList allows duplicate and null values.

  • Java ArrayList is an ordered collection. It maintains the insertion order of the elements.

  • You cannot create an ArrayList of primitive types like int, char etc. You need to use boxed types like Integer, Character, Boolean etc.

  • Java ArrayList is not synchronized. If multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. You must explicitly synchronize access to an ArrayList if multiple threads are gonna modify it.

Constructors Of ArrayList

Sr.No. Constructor & Description
1 ArrayList( )This constructor builds an empty array list.
2 ArrayList(Collection c)This constructor builds an array list that is initialized with the elements of the collection c.
3 ArrayList(int capacity)This constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

Methods Of ArrayList

Sr.No. Method & Description
1 void add(int index, Object element)Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
2 boolean add(Object o)Appends the specified element to the end of this list.
3 boolean addAll(Collection c)Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator. Throws NullPointerException, if the specified collection is null.
4 boolean addAll(int index, Collection c)Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5 void clear()Removes all of the elements from this list.
6 Object clone()Returns a shallow copy of this ArrayList.
7 boolean contains(Object o)Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8 void 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.
9 Object get(int index)Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
10 int indexOf(Object o)Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
11 int lastIndexOf(Object o)Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
12 Object remove(int index)Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).
13 protected void removeRange(int fromIndex, int toIndex)Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
14 Object set(int index, Object element)Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
15 int size()Returns the number of elements in this list.
16 Object[] toArray()Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
17 Object[] toArray(Object[] a)Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
18 void trimToSize()Trims the capacity of this ArrayList instance to be the list’s current size.

Examples

CCreating an ArrayList and adding new elements to it

   public static void createArrayListThenAddElement() {
        ArrayList<String> carArrayList = new ArrayList();
        carArrayList.add("BMW");
        carArrayList.add("Benz");
        carArrayList.add("VV");

        System.out.println(carArrayList);
    }

Creating an ArrayList from another collection

public static void createArrayListFromOtherArrayList() {
    ArrayList<String> benzCarArrayList = new ArrayList();
    benzCarArrayList.add("GLE");
    benzCarArrayList.add("smart");
    benzCarArrayList.add("GLC");

    ArrayList<ArrayList<String>> carArrayList = new ArrayList();
    carArrayList.add(benzCarArrayList);

    System.out.println(carArrayList);

}

Accessing elements from an ArrayList

This example shows:

  • How to check if an ArrayList is empty using the isEmpty() method.

  • How to find the size of an ArrayList using the size() method.

  • How to access the element at a particular index in an ArrayList using the get() method.

  • How to modify the element at a particular index in an ArrayList using the set() method.

public static void createArrayListThenAddElement() {
    ArrayList<String> carArrayList = new ArrayList();
    carArrayList.add("BMW");
    carArrayList.add("Benz");
    carArrayList.add("VV");

    System.out.println(carArrayList);


    System.out.println(carArrayList.size());
    System.out.println(carArrayList.isEmpty());
    System.out.println(carArrayList.get(0));
}

output

3
false
BMW

Removing elements from an ArrayList

This example shows:

  1. How to remove the element at a given index in an ArrayList | remove(int index)

  2. How to remove an element from an ArrayList | remove(Object o)

  3. How to remove all the elements from an ArrayList that exist in a given collection | removeAll()

public static void arrayListRemoveDemo() {
    ArrayList<String> carArrayList = new ArrayList();
    carArrayList.add("BMW");
    carArrayList.add("Benz");
    carArrayList.add("VV");


    carArrayList.remove(0);
    carArrayList.remove("Benz");
    carArrayList.removeAll(carArrayList);

    System.out.println(carArrayList);
}

Iterating over an ArrayList

The following example shows how to iterate over an ArrayList using

  1. iterator().

  2. Simple for-each loop.

  3. for loop with index.

public static void iteratingListRemoveDemo() {
    ArrayList<String> carArrayList = new ArrayList();
    carArrayList.add("BMW");
    carArrayList.add("Benz");
    carArrayList.add("VV");

    System.out.println("---------foreach-------------");

    for (String item:carArrayList){
        System.out.println(item);
    }

    System.out.println("---------iterator-------------");

    Iterator<String> itr =carArrayList.iterator();
    while (itr.hasNext()){
        System.out.println(itr.next());
    }
    System.out.println("----------simple for------------");


    for (int i=0;i<carArrayList.size();i++){
        System.out.println(carArrayList.get(i));
    }
}

Sorting an ArrayList

Sorting an ArrayList is a very common task that you will encounter in your programs. In this section, I’ll show you how to –

public static void sortArrayListDemo() {
    ArrayList<Integer> carArrayList = new ArrayList();
    carArrayList.add(43);
    carArrayList.add(-1);
    carArrayList.add(33);
    carArrayList.add(1);

    System.out.println(carArrayList);
    System.out.println("After sorted");
    Collections.sort(carArrayList);
    System.out.println(carArrayList);

}

public static void usingArrayListSortMethod() {
    List<String> names = new ArrayList<>();
    names.add("Lisa");
    names.add("Jennifer");
    names.add("Mark");
    names.add("David");

    System.out.println("Names : " + names);

    // Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.
    names.sort(new Comparator<String>() {
        @Override
        public int compare(String name1, String name2) {
            return name1.compareTo(name2);
        }
    });

    // The above `sort()` method call can also be written simply using lambda expression
    names.sort((name1, name2) -> name1.compareTo(name2));

    // Following is an even more concise solution
    names.sort(Comparator.naturalOrder());

    System.out.println("Sorted Names : " + names);
}


public static void usingComparableInterface() {
    List<Person> people = new ArrayList<>();
    people.add(new Person("Sachin", 47));
    people.add(new Person("Chris", 34));
    people.add(new Person("Rajeev", 25));
    people.add(new Person("David", 31));

    System.out.println("Person List : " + people);

    // Sort People by their Age
    people.sort((person1, person2) -> {
        return person1.getAge() - person2.getAge();
    });

    // A more concise way of writing the above sorting function
    people.sort(Comparator.comparingInt(Person::getAge));

    System.out.println("Sorted Person List by Age : " + people);

    // You can also sort using Collections.sort() method by passing the custom Comparator
    Collections.sort(people, Comparator.comparing(Person::getName));
    System.out.println("Sorted Person List by Name : " + people);
}

Questions

How do you do the following?

  1. Create an ArrayList for storing double values?

  2. Append an object to a list?

  3. Insert an object at the beginning of a list?

  4. Find the number of objects in a list?

  5. Remove a given object from a list?

  6. Remove the last object from the list?

  7. Check whether a given object is in a list?

  8. Retrieve an object at a specified index from a list?

  9. How to interate an ArrayList?How many ways?

  10. How to sort an ArrayList ? How many ways?

Leave a Reply

Close Menu