Data Structure & Algorithm in Java

⌘K
  1. Home
  2. Docs
  3. Data Structure & Alg...
  4. Linked Lists
  5. Array Implementation of Lists

Array Implementation of Lists

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));   
    }
}
List: [1, 2, 3]
Size: 3
Element at index 1: 2
  • 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, the resize 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 the ArrayList class.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *