Thursday, November 30, 2017

ArrayList implementaion In Java

In some technical interview I have asked by the interviewer , Implement custom ArrayList or implement your own ArrayList.

Here is the program.

import java.util.Arrays;

public class ListImpl {

    private Object[] ListI;
    private int actsize = 0;

    public ListImpl() {

	ListI = new Object[10];
    }

    public Object get(int index) {

	if (index < actsize)
	    return ListI[index];
	else
	    throw new ArrayIndexOutOfBoundsException();
    }

    public void add(int item) {
	if (ListI.length - actsize <= 5)
	    increase();
	ListI[actsize++] = item;
    }

    private void increase() {
	ListI = Arrays.copyOf(ListI, actsize * 2);
	System.out.println("New size:" + ListI.length);
    }

    public int size() {
	return actsize;
    }

    public Object remove(int index) {
	if (index < actsize) {
	    Object v = ListI[index];
	    ListI[index] = null;
	    int tmp = index;

	    while (tmp < actsize) {
		ListI[tmp] = ListI[tmp + 1];
		ListI[tmp + 1] = null;
		tmp++;
	    }
	    actsize--;
	    return v;
	} else {
	    throw new ArrayIndexOutOfBoundsException();
	}
    }

    public static void main(String[] args) {
	ListImpl mal = new ListImpl();
	mal.add(new Integer(2));
	mal.add(new Integer(5));
	mal.add(new Integer(1));
	mal.add(new Integer(23));
	mal.add(new Integer(14));
	for (int i = 0; i < mal.size(); i++) {
	    System.out.print(mal.get(i) + " ");
	}
	mal.add(new Integer(29));
	System.out.println("Element at Index 5:" + mal.get(5));
	System.out.println("List size: " + mal.size());
	System.out.println("Removing element at index 2: " + mal.remove(2));
	for (int i = 0; i < mal.size(); i++) {
	    System.out.print(mal.get(i) + " ");
	}
    }

}

No comments: