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] ;



}
1
  • by the way, that TODO seems pretty meaningless. may want to remove it Commented Feb 26, 2019 at 19:42

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.