Vector class
I have implemented a vector class.It's fine except it shows the
element at position 2 i.e. index 1 is 19 even after removing it.But
the size i am able to decrease.What should I do for that? Can anyone
suggest me?My program is:-
import java.io.*;
class VectorEmptyException extends RuntimeException {
VectorEmptyException(String message) {
super(message);
}
}
class Vector<T> {
Object[] data;
int count;
Vector() {
data = new Object[1];
count = 0;
}
Vector(int s) {
data = new Object[s];
count = 0;
}
int size() {return count;}
Object elementAt(int i) throws VectorEmptyException {
if(i>=count) throw new VectorEmptyException("Vector is
empty");
return data[i];
}
void add(int index,Object O) {
if(data.length == count) {
Object[] newdata = new Object[data.length*2];
for(int i=0;i<count;i++) {
newdata[i] = data[i];
}
data = newdata;
}
for(int i=count;i>index;i--) {
data[i] =data[i-1];
}
data[index] = O;
count++;
}
Object remove(int index) throws VectorEmptyException{
if(index >= count) throw new VectorEmptyException("Vector
is empty");
if (data.length <= count) {
Object[] newdata = new Object[data.length-1];
for(int i=0;i<index;i++)
newdata[i] = data[i];
for(int i=index;i<count-1;i++)
newdata[i] = data[i+1];
data = newdata;}
count--;
return data[index];
}
public static void main(String[] args){
Vector<Integer> v = new Vector<Integer>();
try{
v.add(0,22);v.add(1,19);v.add(2,45)
System.out.println("The 2nd element is : " +v.elementAt(1));
System.out.println("The size of the vector is : "
+v.size());
System.out.println("The removed element is : "
+v.remove(1));
System.out.println("The 2nd element is : " +v.elementAt(1));
System.out.println("The size of the vector is : "
+v.size());
}
catch(VectorEmptyException e){
System.out.println("The vector is empty");
System.out.println(e.getMessage());
}
}
}