ArrayList In Java

ArrayList In Java :

Context

1) ArrayList in java?
2) Dynamic array in java?
3) Why ArrayList is better than Array?
4) How to use Java ArrayList?

  • Present java.util package.
  • ArrayList inherits AbstractList class and implements List interface.
  • It is also known as dynamic array.
  • Array is fixed length. We can not increment or modified length once define the Array. Array is sequential collection same type of elements, accessed by their index values.
  • ArrayList dynamic length. It can increase the length element is addition.
  • ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc.
  • ArrayList is resizable array.
  • List is interface, ArrayList is implement. For example List al = new ArrayList()

ArrayList :

  • Contain duplicate elements.
  • Maintains insertion order.
  • Non synchronized.
  • ArrayList allows random access because array works at the index basis.
  • ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.
  • ArrayList insert element starting position always 0.
  • ArrayList supports fast random access and quick iteration(access) of elements.

Constructor ArrayList :

  • ArrayList(): Empty ArrayList
  • ArrayList(Collection c): ArrayList initialized with the elements from collection c. For example. ArrayList arrli = new ArrayList();
  • ArrayList(int capacity): Initial capacity being specified.

Define ArrayList :

  • ArrayList arrli = new ArrayList(); //Intger ArrayList
  • ArrayList arrli = new ArrayList(); //String ArrayList
  • ArrayList arrli = new ArrayList(3); //Object ArrayList store String, integer etc. Initial capacity being specified. ArrayList al = new ArrayList(); //Old generic, Empty ArrayList List al = new ArrayList(); //List is interface, ArrayList is implement. ArrayList list = new ArrayList<>();
ArrayList In Java

Method ArrayList :

1) void add(int index, E element): Insert element specified the position.
2) boolean add(E e): Insert the end of List.
3) boolean addAll(Collection c):
4) boolean addAll(int index, Collection c):
5) void clear(): Clear all the elelemnt of List.
6) void ensureCapacity(int requiredCapacity): Enhance the capacity of an ArrayList instance.
7) E get(int index): get element specific postition.
8) boolean isEmpty(): It is return true or false. If the empty List return true otherwise false.
9) int lastIndexOf(Object o): Return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
10) Object[] toArray():
11) T[] toArray(T[] a):
12) Object clone(): Return a shallow copy of an ArrayList.
13) boolean contains(Object o): Contain the element return the true.
14) int indexOf(Object o):
15) E remove(int index): Remove the element list, specified the position.
16) E remove(int index):
17) boolean removeAll(Collection c): Remove all the elements from the list.
18) boolean removeIf(Predicate filter):
19) protected void removeRange(int fromIndex, int toIndex): Range to list remove element.
20) void replaceAll(UnaryOperator operator):
21) void retainAll(Collection c):
22) E set(int index, E element): Replace the specified element in the list, present at the specified position.
23) void sort(Comparator c): Sort element using comparator.
24) Spliterator spliterator():
25) List subList(int fromIndex, int toIndex):
26) int size(): Element size of the list.
27) void trimToSize(): Trim the capacity of this ArrayList instance to be the list’s current size.

Traverse the collection elements :

  • Iterator interface.
  • for-each loop.
  • ListIterator interface.
  • for loop.
  • forEach() method.
  • forEachRemaining() method.
import java.util.*;

class Subject {

    public static void main(String args[]) {
        ArrayList<String> subjectList = new ArrayList<>();
        subjectList.add("Android");
        subjectList.add("Java");
        subjectList.add("Kotlin");
        subjectList.add("Flutter");

        System.out.println(subjectList);

        System.out.println("Total element of length " + subjectList.size());
        subjectList.add("PHP");
        System.out.println("Add new elelemnt of total length " + subjectList.size());

        System.out.println(subjectList.isEmpty());

        subjectList.set(1, "Android set");

        subjectList.removeIf(str -> str.contains("PHP"));
        System.out.println("After invoking removeIf() method: " + subjectList);

        ArrayList<String> subjectNew = new ArrayList<String>();
        subjectNew.add("C");
        subjectNew.add("C++");

        subjectList.addAll(subjectNew);
        System.out.println("Updated list : " + subjectList);

        subjectList.removeAll(subjectNew);
        System.out.println("Remove all list subjectNew : " + subjectList);

        subjectList.clear();
        System.out.println("After invoking clear() method: " + subjectList);
    }
}

Output :

[Android, Java, Kotlin, Flutter]
Total element of length 4
Add new elelemnt of total length 5
false
After invoking removeIf() method: [Android, Android set, Kotlin, Flutter]
Updated list : [Android, Android set, Kotlin, Flutter, C, C++]
Remove all list subjectNew : [Android, Android set, Kotlin, Flutter]
After invoking clear() method: []

Iterator interface :

import java.util.*;

class Student {

    public static void main(String args[]) {
        ArrayList<String> subjectList = new ArrayList<>();
        subjectList.add("Android");
        subjectList.add("Java");
        subjectList.add("Kotlin");
        subjectList.add("Flutter");

        Iterator itr = subjectList.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Output :

Android
Java
Kotlin
Flutter

for-each loop :

import java.util.*;

class Student {

    public static void main(String args[]) {
        ArrayList<String> subjectList = new ArrayList<>();
        subjectList.add("Android");
        subjectList.add("Java");
        subjectList.add("Kotlin");
        subjectList.add("Flutter");

        for (String obj : subjectList) {
            System.out.println(obj);
        }
    }
}

Output :

Android
Java
Kotlin
Flutter

for each :

import java.util.*;

class Student {

    public static void main(String args[]) {
        ArrayList<String> subjectList = new ArrayList<>();
        subjectList.add("Android");
        subjectList.add("Java");
        subjectList.add("Kotlin");
        subjectList.add("Flutter");

        subjectList.forEach((obj) -> {
            System.out.println(obj);
        });
    }
}

Output :

Android
Java
Kotlin
Flutter

forEachRemaining :

import java.util.*;

class Student {

    public static void main(String args[]) {
        ArrayList<String> subjectList = new ArrayList<>();
        subjectList.add("Android");
        subjectList.add("Java");
        subjectList.add("Kotlin");
        subjectList.add("Flutter");

        Iterator<String> itr = subjectList.iterator();
        itr.forEachRemaining(a
                -> {
            System.out.println(a);
        });
    }
}

import java.util.*;

class Book {

    int id;
    String name, author, publisher;
    int quantity;

    public Book(int id, String name, String author, String publisher, int quantity) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.publisher = publisher;
        this.quantity = quantity;
    }
}

public class Student {

    public static void main(String[] args) {
        //Creating list of Books  
        List<Book> list = new ArrayList<Book>();
        //Creating Books  
        Book b1 = new Book(101, "Let us C", "Yashwant Kanetkar", "BPB", 8);
        Book b2 = new Book(102, "Data Communications & Networking", "Forouzan", "Mc Graw Hill", 4);
        Book b3 = new Book(103, "Operating System", "Galvin", "Wiley", 6);
        //Adding Books to list  
        list.add(b1);
        list.add(b2);
        list.add(b3);
        //Traversing list  
        for (Book b : list) {
            System.out.println(b.id + " " + b.name + " " + b.author + " " + b.publisher + " " + b.quantity);
        }
    }
}

Output :

101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

trimTosize() :

import java.util.ArrayList;

public class TrimProgram {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>(9);

        list.add(1);
        list.add(4);
        list.add(5);
        list.add(2);
        list.add(11);

        list.trimToSize();

        System.out.println("The List elements are:");

        // prints all the elements 
        for (Integer getData : list) {
            System.out.println("Number " + getData);
        }
    }
}

Output :

The List elements are:
Number 1
Number 4
Number 5
Number 2
Number 11

ArrayList using sorting :

import java.util.ArrayList;
import java.util.Collections;  // Import the Collections class

public class Student {

    public static void main(String[] args) {
        ArrayList<Integer> studentMarks = new ArrayList<>();
        studentMarks.add(33);
        studentMarks.add(15);
        studentMarks.add(20);
        studentMarks.add(34);
        studentMarks.add(8);
        studentMarks.add(12);

        Collections.sort(studentMarks);  // Sort myNumbers

        for (int i : studentMarks) {
            System.out.println(i);
        }
    }
}

Output :

8
12
15
20
33
34