Sunday, November 28, 2010

ArrayList implementation in Java

Here is the ArrayList implementation in Java:

package com;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyArrayList {
    public Object objectArray[] ;
    private int size;
  
    MyArrayList(){
this(10);
    }
    MyArrayList(int initialCapacity){
this.objectArray = new Object[initialCapacity];
    }  
    public void add(int index , Object o){
if(index > size || index < 0){
   throw new IndexOutOfBoundsException("Index : "+index+" Size :"+size);
}
System.arraycopy(objectArray, index, objectArray,index+1,size - index);
objectArray[index] = o;
size++;
    }  
    public static void main(String[] args) {
String s = null;
MyArrayList myObj = null;
for(Integer i=0; i < 20; i++){
   s= new String("Sek"+i);
   System.out.println(" s == "+s);
   myObj = new MyArrayList();
   myObj.add(s);
}
myObj.size();
    }  
    public void add(Object o){
System.out.println(" Get the Current length of the Object array : "+objectArray.length);
//Before adding an Element increase the Size of the array First.
ensureCapacity(size+1);
objectArray[size++] = o;
    }  
    public void ensureCapacity(int minCapacity){
int oldCapacity = objectArray.length;
if(minCapacity > oldCapacity){
   Object oldData[] = objectArray;
   /*Then increase the size of the ObjectArray....
   ArrayList increases the size by 50% of the current size.*/
   int newCapacity = (oldCapacity * 3)/2 + 1;
   if(newCapacity < minCapacity){
newCapacity = minCapacity;
   }
   System.out.println(" New Capacity : "+newCapacity);
   objectArray = Arrays.copyOf(oldData, newCapacity);
}
    }
    public Object get(int index){
return index;
    }
    public int size(){
return objectArray.length;
    }
    public void clear(){
//Remove all elements.
    }
    public int indexOf(Object o){
int index = 0;
return index;
    }
    public Object remove(int index){
rangeCheck(index);
Object oldValue = objectArray[index];
int numOfElementsToMove = size - index - 1;
if(numOfElementsToMove > 0){
   System.arraycopy(objectArray, index+1, objectArray, index, numOfElementsToMove);
}
objectArray[--size] = 0;
return oldValue;
    }
    private void rangeCheck(int index) {
if(index > size){
   throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
}
    }
    @Override
    public String toString(){
return null;
    }
}

No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...