package com.tandbergtv.watchpoint.pmm.web.util;

import java.util.ArrayList;

/**
 * An ArrayList that grows creating elements by itself. }:(
 * 
 * @author Raj Prakash
 *
 * @param <E>
 */
public class CustomArrayList<E> extends ArrayList<E> {
	
	private static final long serialVersionUID = 751767798351008351L;
	
	private Class<E> clazz;
	
	/**
	 * Constructor.
	 * 
	 * @param clazz		the class that is to be instantiated and 
	 * 					added to the list when required
	 */
	public CustomArrayList(Class<E> clazz) {
		this.clazz = clazz;
	}
	
	/**
	 * If the list is of size less than the given index + 1,
	 * creates and adds objects upto the given index. 
	 */
	protected void createUpto(int index) {
		try {
			for(int i=size(); i<=index; ++i)
				add(clazz.newInstance());
		} catch (InstantiationException e) {
		} catch (IllegalAccessException e) {
		}
	}
	
	/**
	 * Gets the element at the given index. If not found, will create objects
	 * upto the index and return the newly created object at the index.
	 */
	@Override
	public E get(int index) {
		createUpto(index);
		return super.get(index);
	}
}
