Is there a way to remove an element from a an Array on Runtime?
For Example:
int[] num = {8, 1, 4, 0, 5};
Output:
Enter the Index: 0
1, 4, 0, 5
Enter the Index: 3
1, 4, 0
Enter the Index: 1
4, 0;
I know that you cannot resize an Array's length once it is initialized and in this kind of sample problem, using an ArrayList
is much more practical. However, is there a way to do this kind of problem by using just an array?
I've managed to remove one element and display the array -1 by creating new array and copying the original array's values in it. But the problem is, in the next iteration in the Output I can still remove an element but the size does not change.
This is what happens:
int[] num = {8, 1, 4, 0, 5};
Output:
Enter the Index: 0
1, 4, 0, 5 // in the first loop it goes as I want it.
Enter the Index: 2
1, 4, 5, 5 // this time array's length is still 4 and just duplicates the last value
Enter the Index: 1
1, 5, 5, 5 // length is still the same and so on.
This is my code in removing an element from an array:
public static int[] removeElement(int index, int[] n) {
int end = n.length;
for(int j = index; j < end - 1; j++) {
n[j] = n[j + 1];
}
end--;
int[] newArr = new int[end];
for(int k = 0; k < newArr.length; k++) {
newArr[k] = n[k];
}
displayArray(newArr);
return newArr;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = {8, 1, 4, 0, 5};
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
removeElement(index, num);
}
}
public static void displayArray(int[] n) {
int i = 0;
for(; i < n.length - 1; i++) {
System.out.print(n[i] + ", ");
}
System.out.print(n[i]);
}
Is there a trick on how to do this on Arrays? Or do I really have to use ArrayList
?
You are discarding the new array returned by removeElement
.
Change your loop to:
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
num = removeElement(index, num);
}