Reputation: 267
Ill try to clarify.
I have:
public static void main(String[] args) {
int a[] = {5, 6 ,7 ,8 ,9 ,10};
removeArray takeOff = new removeArray();
takeOff.remove(3);
for (int i = 0 ; i < a.length ; i++){
System.out.print(" "+a[i]);
}
}
That should print out:
5, 6, 7, 9, 10.
The problem is the remove method, how should I write that. I have:
public class removeArray {
public void remove(int index) {
if (index > 0) {
System.arraycopy(testThatArray.a, 0, testThatArray.a, 0, index);
}
if (index < testThatArray.a.length - 1) {
System.arraycopy(testThatArray.a, index + 1, testThatArray.a, index, testThatArray.a.length - index - 1);
}
}
}
Still, no?
UPDATE:
I got it to print 5 6 7 9 10 10
, how can i remove the last value?
Upvotes: 0
Views: 276
Reputation: 21
you can't delete the index or element of array because it's already sized in the memory so you can't use delete but you can put two values { null or 0 } or another values you want to show that you already get of this.
Upvotes: 2
Reputation: 8044
ArrayUtils#removeElement will probably do what you want. However, consider using a List instead.
Upvotes: 0
Reputation: 31
Create a new array or resize it with the size of the actual array less one and loop through all the values in the array to fill the new array, but skip the one specified in the .remove method.
Upvotes: 0
Reputation: 2049
Arrays are fixed length sets. You cant remove a value. If you wan't to add and remove things use a List or ArrayList
Upvotes: 0
Reputation: 359786
Arrays cannot be resized. Use a List<Integer>
(such as an ArrayList<Integer>
) if you want a collection with resizability.
Otherwise, you'll have to implement this yourself by making a copy of the array that is one element smaller than the original array. Then copy all of the values except the one at the specified index from the old array to the new array.
Upvotes: 1