Arrays and Linked Lists
Arrays and linked lists are common data structures used to store and manipulate collections of elements. Although they serve similar purposes, there are notable differences between them.
Arrays
An array is a fixed-size data structure that stores elements of the same type in contiguous memory locations. Each element in an array can be accessed using an index. Arrays provide constant-time access to elements, which means accessing any element takes the same amount of time, regardless of its position.
Here's an example of initializing and printing an array in Java:
1int[] array = new int[5];
2array[0] = 1;
3array[1] = 2;
4array[2] = 3;
5array[3] = 4;
6array[4] = 5;
7
8for (int i = 0; i < array.length; i++) {
9 System.out.print(array[i] + " ");
10}
Linked Lists
A linked list is a dynamic data structure that consists of nodes, each containing a value and a reference to the next node. Unlike arrays, linked lists do not require contiguous memory locations. Instead, each node points to the next node in the sequence.
Here's an example of initializing and printing a linked list in Java:
1import java.util.LinkedList;
2
3LinkedList<Integer> linkedList = new LinkedList<>();
4linkedList.add(1);
5linkedList.add(2);
6linkedList.add(3);
7linkedList.add(4);
8linkedList.add(5);
9
10for (Integer value : linkedList) {
11 System.out.print(value + " ");
12}
xxxxxxxxxx
}
import java.util.ArrayList;
import java.util.LinkedList;
public class ArraysAndLinkedLists {
public static void main(String[] args) {
// Arrays
int[] array = new int[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
System.out.println("Array:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
// Linked Lists
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
System.out.println("Linked List:");