MyList.java(Interface)
package com.nt.util;
public interface MyList {
public void add(Object obj);
}
MyArrayList.java(Class)
package com.nt.util;
public class MyArrayList implements MyList{
private Object[] objArray;
private static int elementCount=0;
//default constructor
public MyArrayList() {
//initial size
this.objArray=new Object[4];
}
//Logic to add elements
public void add(Object obj) {
//checks if capacity is == size
if(this.capacity()==this.size())
{
//then it will create a new array
Object[] tempArray=new Object[this.capacity()*2];
int i=0;
//it will copy all the element to new array
for(;i<(this.size());i++)
{
tempArray[i]=this.objArray[i];
}
//it will insert the last element
tempArray[elementCount++]=obj;
//it will copy tempArray to objArray
this.objArray=tempArray;
}
else
{
this.objArray[elementCount++]=obj;
}
}
//returns the capacity
private int capacity() {
return this.objArray.length;
}
//returns the size
private int size()
{
return elementCount;
}
@Override
public String toString()
{
String str=java.util.Arrays.toString(this.objArray);
return str.replaceAll("null","");
}
}
ArrayListTest.java
package com.nt.test;
import com.nt.util.MyArrayList;
import com.nt.util.MyList;
public class ArraylistTest {
public static void main(String[] args) {
MyList list=new MyArrayList();
list.add(23);
list.add(45);
list.add(43);
list.add(3);
list.add(55);
System.out.println(list);
}
}
No comments:
Post a Comment