Here's a solution that works using only true array of objects, rather than any of the Java Collections. The outline of how this works in pseudocode is:
- Iterate through all members of the array, checking for equality to
anObject.
- When a match is found, remove the element.
- Iterate through the remaining members of the array, shifting them forward one spot.
- At the end of the array, mark the final member as
null.
I've included some extra code that won't be necessary for your assignment, but will help you to visualize how the method is working on the array:
public class ArrayMethodTester {
private Object[] array = {3, 5, 1, 6, 8, 7, 0, 9, 2, 4};
public static void main(String[] args) {
ArrayMethodTester testArray = new ArrayMethodTester();
testArray.printArray();
testArray.remove(7);
testArray.printArray();
}
public boolean remove(Object anObject) {
for (int i = 0; i < array.length; i++) {
if(array[i].equals(anObject)) {
for (int j = i; j < array.length - 1; j++) {
array[j] = array[j + 1];
}
array[array.length - 1] = null;
return true;
}
}
return false;
}
private void printArray() {
System.out.printf("[%s", array[0]);
for (int i = 1; i < array.length; i++) {
System.out.printf(",%s", array[i]);
}
System.out.println("]");
}
}