I am writing code of Vector class of java and all other collection classes of Java but i am having problem that how it is possible to do that the size of array increase automatically at run time.. and program run properly without giving "Array out of bound Exception" .. Well,This is my code
/* Developed By: Nitin_Khanna
Date: 1/February/2018
Github Username:beNitinhere
Twitter Username:beNitinhere
*/
class Vector{
private static int[] A;
public static long length;
//Default size of Vector is 10
Vector(){
length+=10;
A= new int[10];
}
//One-parameterized Costructor
Vector(int n){
length+=n;
A= new int[n];
}
//get
public void get(){
int []B=new int[5];
for(int i=0;i<length();i++){
System.out.println(A[i]);
}
}
//lenght
public static long length(){
return length;
}
//removeLastElement
public void removeLastElement(){
length=length-1;
}
//removeFirstElement
public void removeFirstElement(){
for(int i=0;i<length();i++){
A[i]=A[i+1];
}
}
//clear
public void clear(){
length=0;
}
//add
public void add(int num,int index){
if(index>length()){
set();
}
A[index]=num;
}
//remove
public void remove(int index){
for(int i=index;i<length();i++){
A[i]=A[i+1];
}
length-=1;
}
//firstElementIs
public int firstElementIs(){
return A[0];
}
//lastElementIs
public int lastElementIs(){
return A[(int)length()-1];
}
//elementAt
public int elementAt(int index){
return A[index];
}
private void set(){
length*=2;
A=new int[(int)length];
}
public void size(){
}
// public boolean isEmpty(){
// }
public static void main(String args[]){
Vector v1=new Vector(5);
for(int i=0;i<=10;i++){
v1.add(i,i);
}
v1.get();
v1.removeLastElement();
System.out.println("After calling removeLastElement function");
v1.get();
System.out.println("After calling remove function");
v1.remove(2);
v1.get();
}
}
Thanks in advance for help..