Post

Java 2 - ArrayLists & LinkedLists

Introduction

  • Polymorphism is a feature of object-oriented programming languages that allows a single interface to be used to represent multiple types of objects.
  • In other words, when 2 objects share the same interface, they are considered polymorphic.
  • ArrayLists and LinkedLists are two types of collections in Java that have polymorphic behavior.

ArrayLists

  • An ArrayList is a resizable array that can store multiple values.
  • ArrayList automatically handles resizing when elements are added or removed, making it easier to work with.
  • The syntax for creating an ArrayList is as follows:
    • ArrayList<type> variable = new ArrayList<>(); for example:
    • List<String> list = new ArrayList<>() is an array list that can store multiple strings.
  • To add values to an ArrayList, you can use the add() method.
1
2
3
4
5
6
7
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

System.out.println(list); // [Apple, Banana, Orange]

  • To remove values from an ArrayList, you can use the remove() method.
1
2
3
4
5
6
7
8
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

list.remove("Banana");

System.out.println(list); // [Apple, Orange]

LinkedLists

  • A LinkedList is a collection of elements where each element has a reference to the next element in the list.
  • The syntax for creating a LinkedList is as follows:
    • LinkedList<type> variable = new LinkedList<>(); for example:
    • List<String> list = new LinkedList<>() is a linked list that can store multiple strings.
  • To add values to a LinkedList, you can use the add() method.
1
2
3
4
5
6
List<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);

System.out.println(list); // [1, 2, 3]
  • To remove values from a LinkedList, you can use the remove() method.
1
2
3
4
5
6
7
8
List<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);

list.remove(2);

System.out.println(list); // [1, 3]
  • Each element in a LinkedList is a Node object that contains a value and a reference to the next element in the list.
  • ArrayList is faster than LinkedList when you need to access elements by index.
  • LinkedList is slow when you need to access elements because there is no index to access elements directly. To access an element, you have to start from the beginning of the list and traverse the list until you find the element you are looking for.

ArrayLists vs LinkedLists

  • ArrayList is faster than LinkedList when you need to access elements by index.
  • LinkedList is better when you need to add or remove elements from the middle of the list.
  • ArrayList is better than LinkedList because in most cases, we need to either access elements by index or add/remove elements from the end of the list.
This post is licensed under CC BY 4.0 by the author.