Is it possible to remove elements from an array?

Is it possible to remove elements from an array (rather than an arraylist), for example.

JButton[] arr = {button1, button2, button3};

I want to remove button 1 from it.

+3
source share
4 answers

Yes, you could do: arr[0] = null;and poof, button1 disappeared from the array.

If you want the array to be smaller than, say, 2 arrays of elements, you will need to make a copy of the array using System.arraycopy(originalArray, 1, destinationArray, 0, 2), by copying the last two elements into an array of two elements.

Best solution: just use Flipin 'ArrayList as what it is created for.

Note that aside, your question has nothing to do with Swing.

+2
source

, button1 {button2, button3}, null, arr[0] = null.

+1

Using ArrayUtils.removeElement(Object[],int)from org.apache.commons.lang, it will remove the index 0, and the size of the array will bedecrease by 1

arr =(JButton[])ArrayUtils.removeElement(arr , 0);
+1
source

You can make any of your indexes null, but the size of the array will remain the same as the array works?

A workaround would be to first convert your array to an ArrayList, remove the element, and then make it an array again -

List<String> list = new ArrayList<String>(Arrays.asList(array));
list.remove(button1);
array= list.toArray(array);
+1
source

All Articles