/*
Konsep arraylist ini adalah untuk memudahkan menyimpan data tanpa perlu risau akan size array tersebut.
Ianya dinamic array di mana jika size sudah mencapai limitnya maka ianya akan membuat array baru dengan size
yang lebih besar supaya boleh menyimpan sebanyak data yang user mahukan.
*/
public class ArrayList{
private int length;
private int maxSize;
private Object []list;
public ArrayList(){
length=0;
maxSize=10; //defaut initialize
list=new Object[maxSize];
}
public ArrayList(int size){
length=0;
maxSize=size;
list=new Object[maxSize];
}
public Object get(int index){
return list[index];
}
public boolean isEmpty()
{
return (length == 0);
}
public boolean isFull()
{
return (length == maxSize);
}
public void add(Object element)
{
if(isFull()) {// if list is full
maxSize *= 2; //maxSize will be multiplied by 2
Object [] newlist = new Object[maxSize]; //create new array with new capacity(maxSize)
System.arraycopy(this.list, 0, newlist, 0, this.length); //copy old array to new array (list -> newlist)
this.list = newlist;
}
for(int i = length; i>0; i--){
list[i]=list[i-1];//item at the specified position
}
list[0]=element;
length++; //increment the length
}//end add
public void add(int loc,Object element)
{
if(isFull()) {// if list is full
maxSize *= 2; //maxSize will be multiplied by 2
Object [] newlist = new Object[maxSize]; //create new array with new capacity(maxSize)
System.arraycopy(this.list, 0, newlist, 0, this.length); //copy old array to new array (list -> newlist)
this.list = newlist;
}
for(int i = length; i>loc; i--){
list[i]=list[i-1];//item at the specified position
}
list[loc]=element;
length++; //increment the length
}//end add
public void remove(int loc)
{
if(isEmpty()) //list is empty
System.err.println("List is empty");
else
{
length--;
for(int i=loc; i<length; i++){
list[i]=list[i+1]; //item at the specified position
}
}
}//end remove
public void display(){
if(isEmpty()){
System.out.println("(Empty)");
}
else{
System.out.printf("[0] = %2d",list[0]);
for(int i=1;i<length;i++){
System.out.printf(" | ["+i+"] = %2d",list[i]);
}
System.out.println();
}
}
public int size()
{
return length;
}
public int maxSize()
{
return maxSize;
}
}