0

I have an array with a size of 5, I want to delete an element from the same array which should reduce it's size by one as well, I can make it by creating a new array but I am trying to execute on the same array. Is there is any way to get make it?

public static void main(String[] args) {
    // TODO Auto-generated method stub
int arraysize = 5;
int[] a = new int[arraysize] ;
    a[0]=1;
    a[1]=2;
    a[2]=3;
    a[3]=4;
    a[4]=5;

    for(int i=0 ; i < a.length ; i++)
    {
        if(a[i]==3)
        {
            a[i]=a[i+1];
            i = i + 1;  
        }
        System.out.println(a[i]);
    }
    a[arraysize] = a[arraysize-1] ;



}
Ali
  • 73
  • 9

2 Answers2

3

In java you cannot delete element from array and reduce it's size. Size of array is CONSTANT. Do use ArrayList instead.


This is demo snippet

int arraysize = 5;
List<Integer> numbers = new ArrayList<>(arraysize);

for (int i = 1; i <= 5; i++)
    numbers.add(i);

System.out.println(numbers.size()); // 5
System.out.println(Arrays.asList(numbers.toArray()));   // [1, 2, 3, 4, 5]

numbers.remove(3);
System.out.println(numbers.size()); // 4
System.out.println(Arrays.asList(numbers.toArray()));   //  [1, 2, 3, 5]
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

It's impossible to reduce array length. You have to use another data structure

nissim abehcera
  • 821
  • 6
  • 7