In: Computer Science
IN JAVA.
I have the following code (please also implement the Tester to test the methods )
And I need to add a method called public int remove() that should remove the first integer of the array and return it at the dame time saving the first integer and bring down all other elements.
After it should decrease the size of the array, and after return and save the integer.
package ourVector;
import java.util.Scanner;
public class ourVector {
private int[] A;
private int size;
public ourVector() {
A = new int[100];
size = 0;
}
public ourVector(int s) {
A = new int[s];
size = 0;
}
public int size() {
return size;
}
public int capacity() {
return A.length;
}
public boolean isEmpty() {
if(size == 0)
return true;
else
return false;
}
public String toString() {
if(this.isEmpty())
return "[]";
String st = "[";
for(int i = 0; i < size-1; i++) {
st += A[i] + ", ";
}
st += A[size -1 ] + "]";
return st;
}
public void add(int e) {
A[size] = e;
size++;
}
Program Code Screenshot


Sample Output :

Program Code to Copy
class ourVector {
private int[] A;
private int size;
public ourVector() {
A = new int[100];
size = 0;
}
public ourVector(int s) {
A = new int[s];
size = 0;
}
public int size() {
return size;
}
public int capacity() {
return A.length;
}
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
public String toString() {
if (this.isEmpty())
return "[]";
String st = "[";
for (int i = 0; i < size - 1; i++) {
st += A[i] + ", ";
}
st += A[size - 1] + "]";
return st;
}
public void add(int e) {
A[size] = e;
size++;
}
public int remove(){
//Remove first element
int ans = A[0];
//Shift all elements to the left
for(int i=0;i<size-1;i++){
A[i] = A[i+1];
}
//Reduce the size
size--;
return ans;
}
}
class Main{
public static void main(String[] args) {
ourVector v = new ourVector();
System.out.println("Capacity is "+v.size()+" and Initial size is "+v.capacity());
System.out.println("After adding 5 numbers");
for(int i=0;i<5;i++){
v.add(i+1);
}
System.out.println(v);
System.out.println("Size is "+v.size());
System.out.println("After removing "+v.remove());
System.out.println(v);
System.out.println("Size is "+v.size());
}
}