Difference between ArrayList, LinkedList and Vector
Last Updated :
10 Nov, 2023
ArrayList:
Array List is an implemented class of List interface which is present in package java.util. Array List is created on the basis of the growable or resizable array. And Array List is an index-based data structure. In ArrayList, the element is stored in a contiguous location. It can store different data types. And random access is allowed. We can also store the duplicate element in Array List. It can store any number of null values.
Below is the implementation of ArrayList:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Creating a vector of int type
vector<int> vec;
// Appending new elements
// at the end of the vector
// using push_back() method via for loops
for (int i = 1; i <= 5; i++)
vec.push_back(i);
// Printing the vector
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
// Removing an element at index 3
// from the vector
// using erase() method
vec.erase(vec.begin() + 3);
// Printing the vector after
// removing the element
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
return 0;
}
// This code is contributed by Akash Jha
Java
// Java program to Illustrate working of an ArrayList
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList of Integer type
ArrayList<Integer> arrli = new ArrayList<Integer>();
// Appending the new elements
// at the end of the list
// using add () method via for loops
for (int i = 1; i <= 5; i++)
arrli.add(i);
// Printing the ArrayList
System.out.println(arrli);
// Removing an element at index 3
// from the ArrayList
// using remove() method
arrli.remove(3);
// Printing the ArrayList after
// removing the element
System.out.println(arrli);
}
}
Python3
# Creating a list of integers
my_list = []
# Appending new elements to the list using for loop
for i in range(1, 6):
my_list.append(i)
# Printing the list
print(my_list)
# Removing an element at index 3 from the list
my_list.pop(3)
# Printing the list after removing the element
print(my_list)
C#
// C# program to Illustrate working of an ArrayList
// Importing required namespaces
using System;
using System.Collections;
// Main class
class GFG {
// Main driver method
static void Main(string[] args)
{
// Creating an ArrayList of integer type
ArrayList arrli = new ArrayList();
// Appending the new elements
// at the end of the list
// using Add() method via for loops
for (int i = 1; i <= 5; i++)
arrli.Add(i);
// Printing the ArrayList
foreach(int i in arrli) Console.Write(i + " ");
Console.WriteLine();
// Removing an element at index 3
// from the ArrayList
// using RemoveAt() method
arrli.RemoveAt(3);
// Printing the ArrayList after
// removing the element
foreach(int i in arrli) Console.Write(i + " ");
Console.WriteLine();
}
}
// This code is contributed by Akash Jha
JavaScript
let vec = [];
// Appending new elements
// at the end of the vector
// using push() method via for loops
for (let i = 1; i <= 5; i++) {
vec.push(i);
}
// Printing the vector
for (let i = 0; i < vec.length; i++) {
console.log(vec[i] + " ");
}
console.log("\n");
// Removing an element at index 3
// from the vector
// using splice() method
vec.splice(3, 1);
// Printing the vector after
// removing the element
for (let i = 0; i < vec.length; i++) {
console.log(vec[i] + " ");
}
console.log("\n");
//This code is contributed by Akash Jha
Output[1, 2, 3, 4, 5]
[1, 2, 3, 5]
Linked List:
Linked list is a linear data structure where data are not stored sequentially inside the computer memory but they are link with each other by the address. The best choice of linked list is deletion and insertion and worst choice is retrieval . In Linked list random access is not allowed . It traverse through iterator.
Below is the implementation of the LinkedList:
C++
#include <iostream>
// LinkedList class definition
class LinkedList {
public:
// Node structure definition within LinkedList class
struct Node {
int data;
Node *next;
// Node constructor
Node(int d) : data(d), next(nullptr) {}
};
// Pointer to head node
Node *head;
// Constructor
LinkedList() : head(nullptr) {}
// Function to print the linked list
void printList() {
// Pointer to traverse the linked list
Node *n = head;
while (n != nullptr) {
// Print the data of the node
std::cout << n->data << " ";
// Move to the next node
n = n->next;
}
}
};
// Main function
int main() {
// Create an instance of the LinkedList class
LinkedList llist;
// Create three nodes with data 1, 2 and 3
llist.head = new LinkedList::Node(1);
LinkedList::Node *second = new LinkedList::Node(2);
LinkedList::Node *third = new LinkedList::Node(3);
// Connect the first node with the second node
llist.head->next = second;
// Connect the second node with the third node
second->next = third;
// Call the printList function to print the linked list
llist.printList();
return 0;
}
Java
import java.util.*;
// LinkedList class definition
class LinkedList {
// Node class definition within LinkedList class
static class Node {
int data;
Node next;
// Node constructor
Node(int d) {
this.data = d;
next = null;
}
}
// Pointer to head node
Node head;
// Constructor
LinkedList() {
head = null;
}
// Function to print the linked list
void printList() {
// Pointer to traverse the linked list
Node n = head;
while (n != null) {
// Print the data of the node
System.out.print(n.data + " ");
// Move to the next node
n = n.next;
}
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an instance of the LinkedList class
LinkedList llist = new LinkedList();
// Create three nodes with data 1, 2 and 3
llist.head = new LinkedList.Node(1);
LinkedList.Node second = new LinkedList.Node(2);
LinkedList.Node third = new LinkedList.Node(3);
// Connect the first node with the second node
llist.head.next = second;
// Connect the second node with the third node
second.next = third;
// Call the printList function to print the linked list
llist.printList();
//This code is Contributed by Abhijit Ghosh
}
}
Python3
class LinkedList:
# Node structure definition within LinkedList class
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __init__(self):
# Pointer to head node
self.head = None
def printList(self):
# Pointer to traverse the linked list
n = self.head
while n is not None:
# Print the data of the node
print(n.data, end=' ')
# Move to the next node
n = n.next
if __name__ == '__main__':
# Create an instance of the LinkedList class
llist = LinkedList()
# Create three nodes with data 1, 2 and 3
llist.head = LinkedList.Node(1)
second = LinkedList.Node(2)
third = LinkedList.Node(3)
# Connect the first node with the second node
llist.head.next = second
# Connect the second node with the third node
second.next = third
# Call the printList function to print the linked list
llist.printList()
C#
// C# program to define a LinkedList class
using System;
// LinkedList class definition
class LinkedList {
// Node structure definition within LinkedList class
public class Node {
public int data;
public Node next;
// Node constructor
public Node(int d) {
data = d;
next = null;
}
}
// Pointer to head node
public Node head;
// Constructor
public LinkedList() {
head = null;
}
// Function to print the linked list
public void PrintList() {
// Pointer to traverse the linked list
Node n = head;
while (n != null) {
// Print the data of the node
Console.Write(n.data + " ");
// Move to the next node
n = n.next;
}
}
}
// Main function
class GFG {
static void Main() {
// Create an instance of the LinkedList class
LinkedList llist = new LinkedList();
// Create three nodes with data 1, 2 and 3
llist.head = new LinkedList.Node(1);
LinkedList.Node second = new LinkedList.Node(2);
LinkedList.Node third = new LinkedList.Node(3);
// Connect the first node with the second node
llist.head.next = second;
// Connect the second node with the third node
second.next = third;
// Call the PrintList function to print the linked list
llist.PrintList();
}
}
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
printList() {
let n = this.head;
while (n != null) {
console.log(n.data + " ");
n = n.next;
}
}
}
let llist = new LinkedList();
llist.head = new Node(1);
let second = new Node(2);
let third = new Node(3);
llist.head.next = second;
second.next = third;
llist.printList();
//This code is contributed by Akash Jha
Vector:
The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface
Below is the implementation of the Vector:
C++
#include <iostream>
#include<vector>
using namespace std;
int main()
{
// Size of the Vector
int n = 5;
// Declaring the Vector with
// initial size n
vector<int> v;
// Appending new elements at
// the end of the vector
for (int i = 1; i <= n; i++)
v.push_back(i);
// Printing elements
for(auto i : v)
cout<<i<<" ";
cout<<endl;
// Remove element at index 3
v.erase(v.begin()+3);
// Displaying the vector
// after deletion
for(auto i : v)
cout<<i<<" ";
cout<<endl;
return 0;
}
Java
// Java Program to Demonstrate Working
// of Vector Via Creating and using it
// Importing required classes
import java.io.*;
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Size of the Vector
int n = 5;
// Declaring the Vector with
// initial size n
Vector<Integer> v = new Vector<Integer>(n);
// Appending new elements at
// the end of the vector
for (int i = 1; i <= n; i++)
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
// Displaying the vector
// after deletion
System.out.println(v);
// iterating over vector elements
// using for loop
for (int i = 0; i < v.size(); i++)
// Printing elements one by one
System.out.print(v.get(i) + " ");
}
}
Python3
# Size of the List
n = 5
# Declaring the List with initial size n
v = []
# Appending new elements at the end of the list
for i in range(1, n + 1):
v.append(i)
# Printing elements
print(v)
# Remove element at index 3
v.pop(3)
# Displaying the list after deletion
print(v)
# Iterating over list elements using a for loop
for i in range(len(v)):
# Printing elements one by one
print(v[i], end=" ")
C#
using System;
using System.Collections.Generic;
namespace ConsoleApp {
class Program {
static void Main(string[] args)
{
// Size of the List
int n = 5;
// Declaring the List with
// initial size n
List<int> lst = new List<int>();
// Appending new elements at
// the end of the List
for (int i = 1; i <= n; i++)
lst.Add(i);
// Printing elements
foreach(var i in lst) Console.Write(i + " ");
Console.WriteLine();
// Remove element at index 3
lst.RemoveAt(3);
// Displaying the List
// after deletion
foreach(var i in lst) Console.Write(i + " ");
Console.WriteLine();
Console.ReadKey();
}
}
}
//This code is contributed by Akash Jha
JavaScript
// Size of the Array
let n = 5;
// Declaring the Array with initial size n
let v = [];
// Appending new elements at the end of the Array
for (let i = 1; i <= n; i++)
v.push(i);
// Printing elements
console.log(v.join(" "));
// Remove element at index 3
v.splice(3, 1);
// Displaying the Array after deletion
console.log(v.join(" "));
Output[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Difference between Array List, Linked List, and Vector:
|
Not present | Not present | present |
Allowed | Not Allowed | Allowed |
contiguous | Not contiguous | contiguous |
supports | supports | supports |
Dynamic Array | Doubly Linked List | Dynamic Array |
Yes | Yes | Yes |
Insertion and deletion are slow | Insertion and deletion are fast | Insertion and deletion are slow |
Which one is better among Linked list, Array list, or Vector?
It depends on the specific use case, each of these data structures has its own advantages and trade-offs. If you mostly need to insert and delete elements at the start or middle of the container, then a linked list might be a better option. If you need fast random access and are willing to accept slower insertion and deletion at end positions, an Array List or Vector is a better option.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem