Skip to main content

3. Array Implementation

 

Array Implementation

The Array class in Java consists of the following methods:

  1. insert(int value, int idx): Insertion of an element at any position of array.
  2. append(int value): Appending an element at the end of array.
  3. delete(int idx): Deleting an element from any position in an array.
  4. remove(): Removing an element from the end of an array.
  5. show(): Displaying the array.

The data members of Array class consists:

  1. len: Tells the length of array.
  2. size: Private member stores the maximum length of array.
  3. arr[]: Private array of the class.
class Array {
    int len;
    private int size;
    private int arr[];

    Array(int size) {
        len = 0;
        this.size = size + 10;
        arr = new int[this.size];
    }

    boolean insert(int value, int idx) {
        if (idx > len || len == size || idx < 0)
            return false;
        for (int i = len - 1; i > idx - 1; i--)
            arr[i + 1] = arr[i];
        arr[idx] = value;
        len++;
        return true;
    }

    boolean append(int value) {
        if (len == size)
            return false;
        arr[len] = value;
        len++;
        return true;
    }

    boolean delete(int idx) {
        if (idx > len - 1 || idx < 0)
            return false;
        for (int i = idx; i < len - 1; i++)
            arr[i] = arr[i + 1];
        len--;
        return true;
    }

    boolean remove() {
        if (len == 0)
            return false;
        arr[len - 1] = 0;
        len--;
        return true;
    }

    void show() {
        for (int i = 0; i < len; i++)
            System.out.print(arr[i] + " ");
    }
}

Prev Next

Comments