Here are the detailed explanation of Array Implementation of Lists:
In many programming languages, lists are often implemented using arrays.
• Arrays provide a contiguous block of memory where elements of the list are stored sequentially. Each element in the array is accessed using its index, allowing for efficient random access.
Here’s a basic implementation of a list using arrays in Java:
public class ArrayList {
private static final int INITIAL_CAPACITY = 10;
private int[] data;
private int size;
public ArrayList() {
this.data = new int[INITIAL_CAPACITY];
this.size = 0;
}
public void add(int element) {
if (size == data.length) {
// Resize the array if it's full
resize();
}
data[size++] = element;
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of bounds");
}
return data[index];
}
private void resize() {
int[] newData = new int[data.length * 2];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
public int size() {
return size;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(data[i]);
if (i < size - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
System.out.println("List: " + list);
System.out.println("Size: " + list.size());
System.out.println("Element at index 1: " + list.get(1));
}
}
OUTPUT:
List: [1, 2, 3]
Size: 3
Element at index 1: 2
In this implementation:
- The
ArrayList
class represents a list implemented using arrays. - The
add
method adds an element to the end of the list. If the array is full, theresize
method is called to double the capacity of the array. - The
get
method retrieves the element at a specified index in the list. - The
resize
method doubles the capacity of the array when needed and copies elements from the old array to the new array. - The
size
method returns the number of elements currently stored in the list. - The
toString
method provides a string representation of the list for printing purposes. - The
main
method demonstrates the usage of theArrayList
class.