How to clear a vector?

Asked

Viewed 2,837 times

1

I have a Java vector of size 5 to allocate 5 first numbers. I have to empty it when it is full in order to allocate 5 more numbers. And keep this routine until all the numbers are read!

int x[] = new int[5];

x[0] = 1
x[1] = 2
x[2] = 3
x[3] = 4
x[4] = 5
  • You can use a for loop to assign a new value to the positions of the vectors. For example: for(int i=0;i<x.lenght; x++){ x[i] = 0 }

2 answers

6


I can’t comment yet. I agree with the statement @Piovezan:

"Clearing" the vector in this case is not exactly possible, because it is saving integers and not references that could receive the null value

But I think the code would look more elegant using the Java Arrays class:

Arrays.fill(int[] a, int val)

Assigns the specified value to each element of the ints array.

Arrays.fill(x, 0);

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#Fill(int[],%20int)

2

"Clearing" the vector in this case is not exactly possible, because it is guarding integers and not references that could receive the value null.

The most you can do is assign a neutral value (for example zero) to all elements of the vector, if this helps in your program, and keep an extra variable as counter of the last available position to write a value (or the last position where a value was written, whatever is best for your program).

To assign zero to all elements you do so:

for (int i = 0; i < x.length; i++) {
    x[i] = 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.