0

I have this method header:

public boolean remove(Object anObject)
{....}

I need the body of the method to remove the first occurrence of a specified element from an int array and shift the remaining elements in the array to the left. I have thought about starting with

for (int i = 0; i < arr.length; i++) {
     if (arr[i] == anObject) 
 }

but this is not working as expected. Any help would be great, thanks!

Sushant Somani
  • 1,450
  • 3
  • 13
  • 31
duffyct2
  • 17
  • 1
  • 4
  • 3
    Don't use an Array. Instead use an ArrayList. The remove(...) method will shift all the elements automatically. – camickr Aug 28 '18 at 23:53
  • I am actually not allowed to use an ArrayList for this assignment. – duffyct2 Aug 28 '18 at 23:56
  • 1
    It is not possible to *remove* elements from an array. Arrays are of **fixed-size**. You can only change the elements, but never remove or add something. You could have a special value denoting that there is *nothing*, such as `null` or `-1` (if working with numbers). But that's still an element, just with a special meaning to you. Also, you will have a *gap* in your array then. – Zabuzard Aug 29 '18 at 00:13

4 Answers4

0

I have a solution for you. Use a for loop that runs and shifts all of your array data over by one.

Building off of your original code:

for (int i = 0; i < arr.length-1; i++) {
     if (arr[i].equals(anObject)){
         for (int k = i; k < arr.length; k++){  //starts replacing ON the duplicate value
             arr[k] = arr[k+1];  //replaces the value with the 1 higher one; aka moving all your array values left       
     }
 }

And like what @camickr said:

You need to use stringName.equals(Object); to compare strings because they are non-primative data types.

Hope this helps. Good luck.

Edward Dan
  • 134
  • 1
  • 10
  • `IndexOutOfBoundsException` – Jim Garrison Aug 29 '18 at 00:31
  • Ok, I am sorry if coded this incorrectly to result in an error. I am currently only an AP Comp Sci student myself and learned how to operate arrays within the past week :p. Please no hate. I also fixed the out of bounds error, did not notice it before. – Edward Dan Aug 29 '18 at 00:33
  • You should adjust the bounds of your inner loop, not your outer one. Otherwise if the object is in the last element of the array it won't be removed. – Michael Myers Aug 29 '18 at 03:18
-1

What you're trying to achieve can be done quite easily through the use of an ArrayList, as camickr mentioned. Overall, the use off ArrayLists for objects can be considered better practice in general.

Simply declare an ArrayList of type the object you are using, and add and remove instances of said object by using

myArrayList.add(object);
myArrayList.remove(index);
tmillward
  • 32
  • 2
-1

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("]");
    }
}
John Stark
  • 1,293
  • 1
  • 10
  • 22
  • `I've included some extra code that won't be necessary for your assignment,` - this is an assignment. The point of an assignment is for the OP to write the code. – camickr Aug 29 '18 at 00:35
  • 1
    @camickr Let’s recap. Author asks for an array-based solution. Gets 3 answers that don’t use an array. The two answers that do use an array, get comments scolding them. Post gets closed as a dupe. How is this a good experience for the author, or any of the contributors? Whenever I post an answer like this, I place a pseudo-coded answer in the body first to make it clear how I approached the problem. I can see where you are coming from with not posting a full code answer, but I also remember wanting to quit CS altogether over frustration at a single problem. – John Stark Aug 29 '18 at 00:43
  • The OP stated the complete requirement for the assignment, which is good so we have the background. However, the OP posted code that didn't work. The reason the code didn't work is because you can't use "==" for object comparison. So we give the solution to the problem based on the posted code and let the OP implement that suggestion and work on the rest of the requirement. People didn't pay attention to the actual stated problem and instead tried to provide all kinds of fancy solutions. – camickr Aug 29 '18 at 00:57
  • `How is this a good experience for the author, or any of the contributors?` - I did not down vote any answer. Instead I left comments, so answers can be better in the future, while paying attention to answers already given. There was no need for 5 answers. People did not pay attention to the actual stated requirement and problem. – camickr Aug 29 '18 at 01:04
-2

but i learned this will not get me my answer

if (arr[i] == anObject) 

You should NOT be using "==" for object comparison.

if (arr[i].equals(anObject)) 

Instead you should be using the equals(..) method.

Then once you know the index of the item you want to remove. So now you just need to copy the next item to that index and repeat until you reach the end of the array. The last item would then be set to null to indicate no value exists.

camickr
  • 321,443
  • 19
  • 166
  • 288