Wednesday, 19 March 2014

Java Custom ArrayList

This blog explains how internally a ArrayList stores data. To simplify the actual ArrayList implementation I have created a custom ArrayList class with minimum methods to add and get the elements. The ArrayList here uses generics and can also be instantiated without the generic parameter as allowed for java.util.ArrayList class.




The class here has a array of Object class with fixed size initially just like the ArrayList class and the array grows as the elements are added to it.




public class MyArrayList<T>{

 // Object array which actually stores the data
 Object[] element;
 
 // The variable which gets incremented after every ading in the list
 int size;
 
 public void add(T t){
  
  // If the array is null, instantiate the array with size 2
  if(element==null){
   element = new Object[2];
  }
  // If the size of the array has reached its threshold then recreate the array with a new size
  // and copy the contains of old array in the new one
  else if(size==element.length-1){
   
   int newSize = ((element.length*3)/2)+1;
   element = Arrays.copyOf(element, newSize);
  }
  element[size]=t;
  size++;
 }
 public T get(int position){
  
  return (T)element[position];
 }
 
}


Test class

public class Test {
 public static void main(String[] args) {
  MyArrayList<Integer> l = new MyArrayList<Integer>();
  
  l.add(31);
  l.add(62);
  l.add(35);
  l.add(74);
  l.add(58);
  l.add(67);
  l.add(78);
  l.add(99);

  
  for(int i=0;i<l.size;i++)
  {
   System.out.println(l.get(i));
     
  }
  System.out.println("Size of array : "+l.element.length);
 }
}


Output

31
62
35
74
58
67
78
99
Size of array : 11


To know more about Java Collections framework read Java Collections Internal Working.
Custom implementation of Collections and Data Structure:
ArrayList
LinkedList
HashMap
Blockchain in Java

5 comments:

  1. Nice Explanation of CustomArrayList,
    in the same way can you explain CustomHashMap, how it works internally...

    ReplyDelete
    Replies
    1. Hello Sasi,
      I have created a blog explaining CustomHashMap. http://www.java-redefined.com/2015/07/custom-java-hashmap.html

      Thanks for your comment,
      Hunaid.

      Delete
  2. Hello,

    i read the arraylist size increased by 50% ie if size 2, it will grow to 4.
    But you mention some formula here. Is it correct, can you please provide your inputs on this

    ReplyDelete
    Replies
    1. From latest Java versions, new size calculation is updated to size8*2 (double the size).

      Delete
  3. Can you explain ArrayList internal working implementation with method add(index i, E element).Please

    ReplyDelete

Share the post