15,966,305 members
See more:
One way to remove element from array is to replace element with zero. Below is a rough snippet I am sharing:
int N=sc.nextInt();
int pos=sc.nextInt();
int A[]=new int[N];
if(pos==i)
{
A[i]=0;
}
But the problem is that size of array remains same still. You have only replaced element with zero.
What extra step we need to perform along with this?

What I have tried:

```int N=sc.nextInt();
int pos=sc.nextInt();
int A[]=new int[N];
if(pos==i)
{
A[i]=0;
}```
Posted
Updated 21-Sep-23 20:37pm
v2

## Solution 1

Arrays are not resizeable. You would need to create a new array one element shorter, then copy the elements you want to keep to that array.

If you want a collection which can grow or shrink, then use something like an ArrayList[^] instead.

Abhinav Kishore M 22-Sep-23 3:54am
ou would need to create a new array one element shorter, then copy the elements you want to keep to that array.
How to do this part without any method?
Richard Deeming 22-Sep-23 4:01am
Seriously?

You already know how to create a new array, and how to specify its length. All you need to do is loop through the source array and copy the desired elements to the new array.

Eg:
```int indexToRemove = 42;
int[] B = new int[A.length - 1];
int BIndex = 0;

for (int index = 0; index < A.length; index++)
{
if (index != indexToRemove)
{
B[BIndex] = A[index];
BIndex++;
}
}```

## Solution 2

Replacing the content does not "remove" anything, any more that changing your hanky removes one of your pockets!

Arrays in Java are not resizable: to remove an element and reduce the number of elements, you need to create a new array, one way or another.
Basically, you have two options:
1) Create a new array with one fewer elements. Copy all the elements up to the index over, skip the element you want to remove, and then copy all the other ones over.
Or
2) Form an ArrayList with the array elements, remove the specified index element using the remove() method, then form a new array from the ArrayList using the mapToInt() or toArray() methods.

Or better, use an ArrayList instead of an array ...

Abhinav Kishore M 22-Sep-23 3:55am
You would need to create a new array one element shorter, then copy the elements you want to keep to that array.
How to do this part without any method?
OriginalGriff 22-Sep-23 4:27am
Step one: create a new, empty array with one element less than your current one.
You know how to create an array, so what is the problem with doing this yourself?