ArrayList & LinkedList in the Java Collections Framework

Methods in Classes & Interfaces of Lists in Collections Framework

Nimasha Madhushani
12 min readFeb 9, 2024
image by author

Hey Guys, I hope you have already read the first 2 articles of the Java Collections Framework Article Series. If not, this is for you.

So, below I have given you a summarized diagram.

image by author

🔷Methods available in the Collection Interface

These methods are derived as abstract methods. So there is no implementation available inside the Collection and List interfaces. So these methods are implemented using ArrayList and LinkedList classes.

👁‍🗨add()

  • Add a single object to the Collection.
  • If I want to add an object to the collection, there is a method called add(). So, this particular method will add an object to the Collection as add(Object o).

👁‍🗨addAll()

  • Add multiple objects to the Collection.
  • So, a group of objects can be added to the Collection as addAll(Collection c).

👁‍🗨remove()

  • An object can be removed from the Collection as remove(Object o).

👁‍🗨removeAll()

  • All objects will be removed from the Collection as removeAll(Collection c).

👁‍🗨retainAll()

  • Except for this object, other objects will be removed from the Collection as retainAll(Object o).
  • If we use retainAll(Collection c) , except for the group of objects represented as ‘c’, all other objects in the Collection will be removed.

👁‍🗨clear()

  • This method will clear all the objects in the collection.

👁‍🗨isEmpty()

  • This method will check whether the Collection is empty or not.

👁‍🗨size()

  • This method can be used to get the no: of objects in the Collection/ to get the Collection size.

👁‍🗨contains()

  • This method will check whether the particular object is available in the Collection or not by the contains(Object o).

👁‍🗨containsAll()

  • This method will check whether the particular group of objects/elements is available in the Collection or not by the containsAll(Collection c).

👁‍🗨toArray()

  • The Collection can be converted to an array by using this method as toArray(Collection c).
  • So, this entire Collection will be converted to an array. As a result, an object array will be returned Object[].

List, Set, and Queue are the child interfaces of the Collection interface. So, the methods which are in this Collection class will be inherited by these child classes. Some methods are specific to the List, Set, and Queue interfaces.

Ok guys, will see the own methods of the List interface...

💦Methods available in the List Interface

The index numbers represent the elements in the List. Duplicate elements are allowed in Lists. But we can differentiate them using the indexes of the List. So, to uniquely identify the elements, retrieving and inserting the elements in a List, we use these indexes.

We use add(Object o) method in the Collection interface. Here, the object will be added to the end of the List.

When it comes to the List interface, If we need to add an element/object somewhere in the List,add(index,Object o) is used. So the particular object will be added to the List based on the index.

  • add(Object o) — Coming from the Collection interface
  • add(index,Object o) — Own method of List interface

In the Collection interface, we have addAll(Collection c) method. But in the List interface, we use the index along with the group of elements/objects. So, the method definitions are different.

  • addAll(Collection c) — Coming from the Collection interface
  • addAll(index,Collection c) — Own method of List interface

In the Collection interface, we have remove(Object o) method. But in the List interface, we use the index along with the group of elements/objects. Then the element in the position of the index will be removed. So, the method definitions are different.

  • remove(Object o) — Coming from the Collection interface
  • remove(index,Object o) — Own method of List interface

🦄get()

  • get() method is not available in the Collection interface. But it is used in the List interface to get the elements from the List.
  • get(index) — This will give the element/object corresponding to the position of the index.

🦄set()

  • Here we pass an index and a new object. So, the existing object will be replaced by the new object by using this set method.

🐳Classes in List Interface

ArrayList Class and LinkedList Class are included in the List interface.

🐌ArrayList Class

  • ArrayList class is inside the java.utils package.
  • Declaring an ArrayList as ArrayList arrList = new ArrayList();
  • arrList, the reference variable of the ArrayList.
  • Every location in the ArrayList is identified by the index
  • ArrayList is automatically growable. So, it’s a growable object.
  • Insertion order is preserved and duplicate elements are allowed in the ArrayList.
  • There are many methods inside the ArrayList class.
  • ArrayList arrList = new ArrayList(); ArrayList() is the default constructor of the ArrayList Class
  • ArrayLists are allowed for different types of elements(heterogenous)
  • If we need similar types of objects/data to be stored, we should define only Strings inside the ArrayList,

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

Assume that, there is an empty ArrayList initially. If we need to add an element to this ArrayList, we can use the add(Object o) method. And if we need to add an element to a specific position of this ArrayList we can use add(index, Object o).

If we need to get the no: of elements/objects inside the ArrayList, size() method can be used.

If need to remove an element/object, we can use the remove() method. If we need to remove an element/object from a specific place of the array list, we can do it based on the index as remove(index, Object o).

  • get(index) method can be used to retrieve the data from the ArrayList.
  • set(index, Object o) method can be used to retrieve the data from the ArrayList.
  • contains(Object o) is used to whether this Collection has this object. Here a boolean value will be returned.
  • isEmpty() is used to check whether the ArrayList is empty or not. Tf the ArrayList is empty it will return true and otherwise return false.
  • addAll() is used to add a group of objects/elements to the ArrayList.
  • removeAll() is used to remove a group of objects/elements from the ArrayList.

We don’t have the sort() method directly in the ArrayList. So, we can use the predefined sort() method in the Collections Class which is inside the java.utils package. To sort the elements in the ArrayList, all elemts inside the ArrayList should be in the same type.

Collections.sort(arrayList); will sort the all elements inside the ArrayList. Here, the arrayList parameter which is inside this method is the reference variable of the ArrayList .

If we want to shuffle the elements in the ArrayList, we can use Collections.shuffle(arrayList); .

If we have an array, we can convert that to an ArrayList as well.

🐞Guys, we will do some hands-on experience to verify the things we discussed so far.

import java.util.*;

public class ArrayListCollection {
public static void main(String[] args) {
//Declare an ArrayList
ArrayList arrayList = new ArrayList(); // arrayList is the object reference variable

//this arraylist allow to store heterogeneous data. So, to restrict that by allowing only to insert homogenous data
//we can specify the ArrayList by using a wrapper class
ArrayList<Integer> integerArrayList = new ArrayList<>();
ArrayList<String> stringArrayList = new ArrayList<>();

//List interface is implemented by the ArrayList
List list = new ArrayList();//This is an example of polymorphism and coding to interfaces in Java.

//Add new elements to the ArrayList
arrayList.add(100);
arrayList.add("Nimasha");
arrayList.add(10.5);
arrayList.add('A');
arrayList.add(true);

System.out.println(arrayList);

//Add new elements to a specific place in the array list
//arrayList.add(index, object);
arrayList.add(1, "Welcome");
System.out.println("After insertion : " + arrayList);

//size()
System.out.println("\nNumber of elements in array list : " + arrayList.size());

//remove()
//remove elements based on the index of the array list
arrayList.remove(1); // here 1 is index
System.out.println("After removing the element in index 1 : " + arrayList);

//remove existing elements by the value
arrayList.remove("Nimasha"); // here Nimasha is an element in the array list
System.out.println("After removing the element 'Nimasha': " + arrayList);

//retrieve specific element from the array list
System.out.println("Element in the 0th index of the array list : " + arrayList.get(0));

//change the existing value, replace with a new value
arrayList.set(0, 50);
System.out.println("After changing the existing value in the 0th index : " + arrayList);

//search elements in the array list, it returns true/false
System.out.println(arrayList.contains(10.5));
System.out.println(arrayList.contains("Nimasha"));

//check for empty
System.out.println("is ArrayList empty? : " + arrayList.isEmpty());
System.out.println();

//Approaches to read the data in an array list

//1) for loop
System.out.println("Reading elements using for loop");
for (int i = 0; i < arrayList.size(); i++) {

System.out.print(arrayList.get(i) + " ");
}
System.out.println("\n\nReading elements using for each loop");

//2) for..each loop
for (Object element : arrayList
) {
System.out.print(element + " ");
}

//3) iterator
System.out.println("\n\nReading elements using iterator method");
Iterator iterator = arrayList.iterator();//This will read each and every element in the array list
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");//print and automatically move to the next element
}

//Adding multiple elements/objects
ArrayList arrayListNew = new ArrayList();
arrayListNew.add("A");
arrayListNew.add("M");
arrayListNew.add("P");
arrayListNew.add("L");

ArrayList duplicateArrayList = new ArrayList();
duplicateArrayList.addAll(arrayListNew);
System.out.print("\n\nDuplicated ArrayList : " + duplicateArrayList);

//Remove all objects in the array list
duplicateArrayList.removeAll(arrayListNew);

System.out.println("\n\nAfter removing all elements in ArrayList : " + duplicateArrayList);

//Sorting the elements in the array list
Collections.sort(arrayListNew);
System.out.println("\nAfter sorting : " + arrayListNew);
Collections.sort(arrayListNew, Collections.reverseOrder());
System.out.println("\nAfter sorting in reverse : " + arrayListNew);

//Shuffling the elements in the array list
Collections.shuffle(arrayListNew);
System.out.println("\nAfter shuffling array list : " + arrayListNew);

//Declaring an array
String array[] = {"Dog", "Cat", "Elephant"};
System.out.print("Array : ");
for (String value:array
) {
System.out.print(value + " ");
}

//Convert array into ArrayList
ArrayList arrayToArrayList =new ArrayList(Arrays.asList(array));
System.out.println("\nArrayList : "+arrayToArrayList+" ");
}
}

Output:

[100, Nimasha, 10.5, A, true]
After insertion : [100, Welcome, Nimasha, 10.5, A, true]

Number of elements in array list : 6
After removing the element in index 1 : [100, Nimasha, 10.5, A, true]
After removing the element 'Nimasha': [100, 10.5, A, true]
Element in the 0th index of the array list : 100
After changing the existing value in the 0th index : [50, 10.5, A, true]
true
false
is ArrayList empty? : false

Reading elements using for loop
50 10.5 A true

Reading elements using for each loop
50 10.5 A true

Reading elements using iterator method
50 10.5 A true

Duplicated ArrayList : [A, M, P, L]

After removing all elements in ArrayList : []

After sorting : [A, L, M, P]

After sorting in reverse : [P, M, L, A]

After shuffling array list : [M, L, A, P]

Array : Dog Cat Elephant
ArrayList : [Dog, Cat, Elephant]

Process finished with exit code 0

🐌LinkedList Class

  • The LinkedList class is used to implement the List interface. There is an interface called the Dequeue interface which extends from the Queue interface. So, this Dequeue interface is implemented using the LinkedList class.
  • The LinkedList class has many methods.
  • If we have a collection and if we need to do frequent retrieving, it is better to use the ArrayList concept. So, we can do that using get() method. There we can obtain the needed value by passing the index of the array list.

If we need to do more operations(insertion/deletion) it is better to use a LinkedList. Why…?

If we need to insert an element to the middle of the array list we need to shift the elements to the right side. And if we need to delete a specific element from the array list we have to shift the other elements to the left side. So, we need to do shifting for both insertion and deletion. This shifting will take time. When the number of elements in the array list is high the time taking is also high.

Assume an array list has 100 elements. We need to add an element to the 2nd index position of it. Then we have to shift 98 elements to the right side.

So, we do not prefer to use the ArrayList concept when there are more insertion and deletion operations.

LinkedList representation,

image by author

If we need to add a new element, a new node will be created and inserted into the LinkedList as below,

image by author
  • If we delete an element, that will be added to the garbage collection.

🟣 If we have more no: of retrievals, the LinkedList concept is not suitable.

  • When we need to search for any element, then need to traverse through the LinkedList to get the element. If we need to get the 100th element, 99 navigations are required to retrieve it.
image by author

LinkedLists are used to implement Queues and Stacks.

  • Queues — FIFO (First In First Out) Concept
  • Stacks — FILO (First In Last Out) Concept

List and Dequeue interface methods are implemented inside the LinkedList.

🦉LinkedList Features,

  • Duplicate elements are allowed.
  • Insertion order is preserved.
  • Null values are acceptable.
  • All elements are linked with the addresses of nodes.
  • Default LinkedList is a Doubly Linked List Data Structure.

Methods used in LinkedLists,

  • add(Object) — Adding an object to the LinkedList
  • add(index, Object) — Adding an object with an index to the LinkedList
  • addAll(Collection)— Adding a group of objects/Collection to the LinkedList
  • remove(Object) — Removing an object directly in the LinkedList
  • remove(index, Object) — Removing an object with an index directly in the LinkedList
  • removeAll(Collection) — Removing a group of objects/Collection to the LinkedList
  • get(index) — Accordingly can get the specific element
  • set(index, Object) — Replace the existing value in the node

Collections class which is in java.util package provides the methods for sorting and shuffling elements.

  • Collections.sort()
  • Collections.shuffle()
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class LinkedListDemo1 {
public static void main(String[] args) {
//Declare a LinkedList
LinkedList linkedList = new LinkedList();// allows to store heterogeneous data
LinkedList<Integer> integerLinkedList = new LinkedList<>();//allows to store only homogeneous data
LinkedList<String> stringLinkedList = new LinkedList<>();

//Adding elements
linkedList.add(100);
linkedList.add("Welcome");
linkedList.add(15.5);
linkedList.add('A');
linkedList.add(true);
linkedList.add(null);

System.out.println(linkedList);

//Get the length of the LinkedList
System.out.println(linkedList.size());

//Remove an element
linkedList.remove(3);
System.out.println("After removing 3rd element : " + linkedList);

//Adding elements in the middle of the LinkedList
linkedList.add(3, "Java");
System.out.println("After inserting an element : " + linkedList);

//Retrieving value/object
System.out.println("3rd element : " + linkedList.get(2));

//Changing the value
linkedList.set(5, "X");
System.out.println("After changing the value : " + linkedList);

//Contains
System.out.println("Check for availability \"Java\" :" + linkedList.contains("Java"));
System.out.println("Check for availability \"Python\" :" + linkedList.contains("Python"));

//Check for empty
System.out.println("Linkedlist is Empty? :" + linkedList.isEmpty());

//Reading elements from LinkedList using for loop
for (int i = 0; i < linkedList.size(); i++) {
System.out.print(linkedList.get(i) + " ");
}
System.out.println();
for (Object element : linkedList
) {
System.out.print(element + " ");

}
System.out.println();

//iterator method
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}

LinkedList list = new LinkedList();
list.add("X");
list.add("B");
list.add("F");
list.add("D");
list.add("C");

LinkedList newList = new LinkedList();
newList.addAll(list);
System.out.print(newList + " ");

newList.removeAll(list);
System.out.println("\n" + newList);

//soring
System.out.println("Before Sorting : " + list);
Collections.sort(list);
System.out.println("After Sorting : " + list);

//reverse order
Collections.sort(list, Collections.reverseOrder());
System.out.println("Reverse Sorting : " + list);

//shuffling elements
System.out.println("\nBefore Shuffling : " + list);
Collections.shuffle(list);
System.out.println("After Shuffling : " + list);
}
}

Output:

[100, Welcome, 15.5, A, true, null]
6
After removing 3rd element : [100, Welcome, 15.5, true, null]
After inserting an element : [100, Welcome, 15.5, Java, true, null]
3rd element : 15.5
After changing the value : [100, Welcome, 15.5, Java, true, X]
Check for availability "Java" :true
Check for availability "Python" :false
Linkedlist is Empty? :false
100 Welcome 15.5 Java true X
100 Welcome 15.5 Java true X
100 Welcome 15.5 Java true X [X, B, F, D, C]
[]
Before Sorting : [X, B, F, D, C]
After Sorting : [B, C, D, F, X]
Reverse Sorting : [X, F, D, C, B]

Before Shuffling : [X, F, D, C, B]
After Shuffling : [F, X, C, D, B]

Process finished with exit code 0

🔴Special methods belong to the LinkedList class,

🐇addFirst(Object) — Adding the element in the first place as the 1st element

🐇addLast(Object) — Adding the element as the element

🐇removeFirst() — The first element will be removed from the LinkedList.

🐇removeLast() — The last element will be removed from the LinkedList.

🐇getFirst() — Get the 1st element/node from the LinkedList

🐇getLast() — Get the Last element/node from the LinkedList

import java.util.LinkedList;

public class LinkedListDemo2 {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("Dog");
list.add("Cat");
list.add("Horse");

System.out.println(list + " ");

list.addFirst("Tiger");
list.addLast("Elephant");

System.out.println(list + " ");

System.out.println(list.getFirst());
System.out.println(list.getLast());

list.removeFirst();
System.out.println("After removing first element : " + list + " ");

list.removeLast();
System.out.println("After removing last element : " + list + " ");

}
}

Output:

[Dog, Cat, Horse] 
[Tiger, Dog, Cat, Horse, Elephant]
Tiger
Elephant
After removing first element : [Dog, Cat, Horse, Elephant]
After removing last element : [Dog, Cat, Horse]

Process finished with exit code 0

Cool..Guys!😎

I think we can have a break here, So, I hope to discuss,

💦Methods available in the Set Interface

💦Methods available in the Queue Interface

in the next blog. Then bye for all…! Stay tuned to grab the knowledge in the part 4 article in the Java Collections Framework article series…!

--

--