You can't resize the array, per se, but you can create a new array and efficiently copy the elements from the old array to the new array using some utility function like this:
public static int[] removeElement(int[] original, int element){
int[] n = new int[original.length - 1];
System.arraycopy(original, 0, n, 0, element );
System.arraycopy(original, element+1, n, element, original.length - element-1);
return n;
}
A better approach, however, would be to use an ArrayList (or similar List structure) to store your data and then use its methods to remove elements as needed.
Using ArrayUtils.removeElement(Object[],Object)
from org.apache.commons.lang is by far the easiest way to do this.
int[] numbers = {1,2,3,4,5,6,7};
//removing number 1
numbers =(int[])ArrayUtils.removeElement(numbers, 1);
without using the System.arraycopy method you can delete an element from an array with the following
int i = 0;
int x = 0;
while(i < oldArray.length){
if(oldArray[i] == 3)i++;
intArray[x] = oldArray[i];
i++;
x++;
}
where 3 is the value you want to remove.
Since an array has a fixed size that is allocated when created, your only option is to create a new array without the element you want to remove.
If the element you want to remove is the last array item, this becomes easy to implement using Arrays.copy
:
int a[] = { 1, 2, 3};
a = Arrays.copyOf(a, 2);
After running the above code, a will now point to a new array containing only 1, 2.
Otherwise if the element you want to delete is not the last one, you need to create a new array at size-1 and copy all the items to it except the one you want to delete.
The approach above is not efficient. If you need to manage a mutable list of items in memory, better use a List. Specifically LinkedList
will remove an item from the list in O(1)
(fastest theoretically possible).
The size of a Java array is fixed when you allocate it, and cannot be changed.
If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.arraycopy(...)
or Arrays.copyOf(...)
. A copy loop works as well, though it looks a bit clunky ... IMO.
If you want to "delete" an item or items from an array (in the true sense ... not just replacing them with null
), you need to allocate a new smaller array and copy across the elements you want to retain.
Finally, you can "erase" an element in an array of a reference type by assigning null
to it. But this introduces new problems:
null
elements to mean something, you can't do this.null
element in the appropriate fashion. More complexity and potential for bugs1.There are alternatives in the form of 3rd-party libraries (e.g. Apache Commons ArrayUtils
), but you may want to consider whether it is worth adding a library dependency just for the sake of a method that you could implement yourself with 5-10 lines of code.
It is better (i.e. simpler ... and in many cases, more efficient2) to use a List
class instead of an array. This will take care of (at least) growing the backing storage. And there are operations that take care of inserting and deleting elements anywhere in the list.
For instance, the ArrayList
class uses an array as backing, and automatically grows the array as required. It does not automatically reduce the size of the backing array, but you can tell it to do this using the trimToSize()
method; e.g.
ArrayList l = ...
l.remove(21);
l.trimToSize(); // Only do this if you really have to.
1 - But note that the explicit if (a[e] == null)
checks themselves are likely to be "free", since they can be combined with the implicit null
check that happens when you dereference the value of a[e]
.
2 - I say it is "more efficient in many cases" because ArrayList
uses a simple "double the size" strategy when it needs to grow the backing array. This means that if grow the list by repeatedly appending to it, each element will be copied on average one extra time. By contrast, if you did this with an array you would end up copying each array element close to N/2 times on average.
You can always expand an array just by increment the size of it while creating an array or you can also change the size after creating, but to shrink or delete elements. The alternate solution without creating a new array, possibly is:
package sample;
public class Delete {
int i;
int h=0;
int n=10;
int[] a;
public Delete()
{
a = new int[10];
a[0]=-1;
a[1]=-1;
a[2]=-1;
a[3]=10;
a[4]=20;
a[5]=30;
a[6]=40;
a[7]=50;
a[8]=60;
a[9]=70;
}
public void shrinkArray()
{
for(i=0;i<n;i++)
{
if(a[i]==-1)
h++;
else
break;
}
while(h>0)
{
for(i=h;i<n;i++)
{
a[i-1]=a[i];
}
h--;
n--;
}
System.out.println(n);
}
public void display()
{
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Delete obj = new Delete();
obj.shrinkArray();
obj.display();
}
}
Please comment for any mistakes!!
I have created this function, or class. Im kinda new but my friend needed this also so I created this:
public String[] name(int index, String[] z ){
if(index > z.length){
return z;
} else {
String[] returnThis = new String[z.length - 1];
int newIndex = 0;
for(int i = 0; i < z.length; i++){
if(i != index){
returnThis[newIndex] = z[i];
newIndex++;
}
}
return returnThis;
}
}
Since its pretty revelant, I thought I would post it here.
object[] newarray = new object[oldarray.Length-1];
for(int x=0; x < array.Length; x++)
{
if(!(array[x] == value_of_array_to_delete))
// if(!(x == array_index_to_delete))
{
newarray[x] = oldarray[x];
}
}
There is no way to downsize an array after it is created, but you can copy the contents to another array of a lesser size.
Arrays are fixed in size, you cannot resize them after creating them. You can remove an existing item by setting it to null
:
objects[4] = null;
But you won't be able to delete that entire slot off the array and reduce its size by 1.
If you need a dynamically-sized array, you can use an ArrayList
. With it, you can add()
and remove()
objects, and it will grow and shrink as needed.
No use of any pre defined function as well as efficient: --- >>
public static void Delete(int d , int[] array )
{
Scanner in = new Scanner (System.in);
int i , size = array.length;
System.out.println("ENTER THE VALUE TO DELETE? ");
d = in.nextInt();
for ( i=0;i< size;i++)
{
if (array[i] == d)
{
int[] arr3 =new int[size-1];
int[] arr4 = new int[i];
int[] arr5 = new int[size-i-1];
for (int a =0 ;a<i;a++)
{
arr4[a]=array[a];
arr3[a] = arr4[a];
}
for (int a =i ;a<size-1;a++)
{
arr5[a-i] = array[a+1];
arr3[a] = arr5[a-i];
}
System.out.println(Arrays.toString(arr3));
}
else System.out.println("************");
}
}
Source: Stackoverflow.com