What is an Array?
An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
for ( int i : arr) {
cout << i << " " ;
}
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
int arr[] = { 1 , 2 , 3 , 4 , 5 };
for ( int i:arr){
System.out.print(i+ " " );
}
}
}
|
Python3
arr = [ 1 , 2 , 3 , 4 , 5 ]
for i in arr:
print (i, end = " " )
|
C#
using System;
class GFG {
public static void Main ( string [] args) {
int [] arr = {1,2,3,4,5};
foreach ( int i in arr){
Console.Write(i + " " );
}
}
}
|
Javascript
const arr = [1, 2, 3, 4, 5];
for (const i of arr) {
console.log(i + " " );
}
|
What is a Hash Table
A Hash table is a data structure that stores some information, and the information has basically two main components, i.e., key and value. The hash table can be implemented with the help of an associative array.
What is a List?
A list is an ordered and changeable collection of data objects. Unlike an array, which can contain objects of a single type, a list can contain a mixture of objects.
C++
#include <iostream>
#include <vector>
int main() {
std::vector< int > ll = {1, 2, 3, 4, 5};
for ( int num : ll) {
std::cout << num << " " ;
}
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main (String[] args) {
List<Integer> ll = Arrays.asList( new Integer[]{ 1 , 2 , 3 , 4 , 5 });
System.out.println(ll);
}
}
|
Python3
ll = [ 1 , 2 , 3 , 4 , 5 ]
for num in ll:
print (num, end = " " )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void Main( string [] args) {
List< int > ll = new List< int >( new int [] { 1, 2, 3, 4, 5 });
Console.WriteLine( string .Join( ", " , ll));
}
}
|
Javascript
function main() {
let ll = [1, 2, 3, 4, 5];
for (let num of ll) {
console.log(num + " " );
}
}
main();
|
Why use an “Array” to implement a “List” instead of a “Hash Table”?
All of the different collection data types have their specific advantages and disadvantages.
Time taken for insertion, lookup, and removal are O(1) for both arrays and hash tables in all cases. But array has a much lower constant overhead than hashtables. And arrays need less space per entry.
If you would like to remove and insert entries in a way that the following entries change their index accordingly, it would be O(n) in case of an array with n being the number of entries that need to be moved. It would also be O(n) for hashtables to do this but with a much higher constant overhead.
A list is typically ordered whereas a hashtable is not. So when you add elements into a list and expect the ordering to remain consistent then an array retains the ordering while a hashtable gives no guarantee as to the order you get back out. That’s why we use an array to implement a list instead of a hash table.