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
ArrayListis 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
ArrayListis 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 theadd()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 theremove()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
LinkedListis a collection of elements where each element hasa referenceto the next element in the list. - The syntax for creating a
LinkedListis 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 theadd()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 theremove()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
LinkedListis aNodeobject that contains a value and a reference to the next element in the list.
ArrayListis faster thanLinkedListwhen you need to access elements by index.LinkedListis 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
ArrayListis faster thanLinkedListwhen you need to access elements by index.LinkedListis better when you need to add or remove elements from the middle of the list.
ArrayListis better thanLinkedListbecause 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.