Saturday, July 27, 2019

Custom Own ArrayList Implementation

Create Custom ArrayList.

package com.shubh.example;

import java.util.Arrays;

public class CustomArrayList {
 // Define INITIAL_CAPACITY,
 private static int INITIAL_CAPACITY = 10;
 private Object[] listArray;
 // Define size of elements in custom ArrayList
 private int size = 0;

 // constructor of custom ArrayList with default INITIAL_CAPACITY
 public CustomArrayList() {
  listArray = new Object[INITIAL_CAPACITY];
 }

 // constructor of custom ArrayList with given INITIAL_CAPACITY
 public CustomArrayList(int initSize) {
  INITIAL_CAPACITY = initSize;
  listArray = new Object[INITIAL_CAPACITY];
 }

 public Object get(int index) {
  if (index < size) {
   return listArray[index];
  } else {
   throw new ArrayIndexOutOfBoundsException();
  }
 }

 public void add(E e) {
  if (size == listArray.length) {
   ensureCapacity(); // increase capacity of list, while size of array is equal to array length.
  }
  listArray[size++] = e;
 }

 public Object remove(int index) {
  if (index < size) {
   Object obj = listArray[index];
   listArray[index] = null;
   int tmp = index;
   while (tmp < size) {
    listArray[tmp] = listArray[tmp + 1];
    listArray[tmp + 1] = null;
    tmp++;
   }
   size--;
   return obj;
  } else {
   throw new ArrayIndexOutOfBoundsException();
  }

 }

 public int size() {
  return size;
 }

 private void ensureCapacity() {
  int newIncreasedCapacity = (int) (listArray.length + Math.ceil(listArray.length / 2));
  listArray = Arrays.copyOf(listArray, newIncreasedCapacity);
  System.out.println("\nNew length: " + listArray.length);
 }

 public static void main(String a[]) {
        CustomArrayList list = new CustomArrayList(11);
 list.add(2);
 list.add(5);
 list.add(1);
 list.add(12);
 list.add(13);
 list.add(15);
 list.add(16);
 list.add(15);
 list.add(17);
 list.add(13);
 list.add(25);
 for (int i = 0; i < list.size(); i++) {
  System.out.print(list.get(i) + " ");
 }
 list.add(15);
 list.add(16);
 list.add(15);
 list.add(17);
 list.add(30);
 for (int i = 0; i < list.size(); i++) {
  System.out.print(list.get(i) + " ");
 }
 list.add(18);
 list.add(19);
 System.out.println("Element at Index 6:" + list.get(6));
 System.out.println("List size: " + list.size());
 System.out.println("Removing element at index 2: " + list.remove(2));
 for (int i = 0; i < list.size(); i++) {
  System.out.print(list.get(i) + " ");
 }
 }
}
Output:

2 5 1 12 13 15 16 15 17 13 25 
New length: 16
2 5 1 12 13 15 16 15 17 13 25 15 16 15 17 30 
New length: 24
Element at Index 6:16
List size: 18
Removing element at index 2: 1
2 5 12 13 15 16 15 17 13 25 15 16 15 17 30 18 19 

No comments:

Post a Comment