Internal implementation of ArrayList is:
import java.util.Arrays;
public class MyArrayList
{
private Object[] myStore;
private int actSize=0;
public MyArrayList() {
// TODO Auto-generated constructor stub
myStore = new Object[10];
}
public Object get(int index)
{
if(index < actSize)
{
return myStore[index];
}
else {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(Object obj) {
if(myStore.length-actSize<=5)
{
increaseListSize();
}
myStore[actSize++] = obj;
}
public Object remove(int index)
{
if (index < actSize)
{
Object obj = myStore[index];
myStore[index]=null;
int temp = index;
while (temp < actSize)
{
myStore[temp]=myStore[temp+1];
myStore[temp+1]= null;
temp++;
}
actSize--;
return obj;
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
public int size()
{
return actSize;
}
private void increaseListSize()
{
myStore = Arrays.copyOf(myStore, myStore.length*2);
System.out.println("\n new length : "+myStore.length);
}
public static void main(String[] args) {
MyArrayList mal= new MyArrayList();
mal.add(new Integer(2));
mal.add(new Integer(15));
mal.add(new Integer(25));
mal.add(new Integer(48));
mal.add(new Integer(24));
for (int i = 0; i < mal.size(); i++)
{
System.out.print(mal.get(i)+" ");
}
mal.add(new Integer(001));
System.out.println("element at index 5: "+mal.get(5));
System.out.println("list size: "+mal.size());
System.out.println("removeing element at 2: "+mal.remove(2));
for (int i = 0; i < mal.size(); i++)
{
System.out.print(mal.get(i)+" ");
}
}
}
==========================================================================
Output:
2 15 25 48 24
new length : 20
element at index 5: 1
list size: 6
removeing element at 2: 25
2 15 48 24 1