Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a remove method for an object array

Tags:

java

arrays

list

I know my add method is correct:

public void add(Object object) {
    if (!contains(object) && size !=maxObjects) {
        set[size] = object; size++;
    }
    else 
        System.out.println("Already exists.");
}

because I get print outs like:

Set [maxObjects=8, set=[a, 7, null, null, null, null, null, null], count=2]  
true  (I ask if it contains a value)  
false  "                            "  
Set [maxObjects=8, set=[a, 7, b, Valencia, 24, s, Victoria, null], count=7]  
Set [maxObjects=8, set=[a, 7, b, Valencia, 24, s, Victoria, 4234], count=8]  

I have tried two different remove methods that are both the same (one I created; the other I found on Stack in the most similar problem a few days ago.)

1st remove:

public boolean remove(Object object) {
    if (contains(object)) {
        object = null; 
        return true;
    }
    System.out.println("The object doesn't exist to delete.");
    return false;
}

The other remove:

public boolean remove(object object) {
    for (int i=0; i<(size-1); i++) {
        while (!contains(object) && size <= maxObjects) {
            set[i] = set[i+1]; size--; return true;
        }
    }
    System.out.println("Doesn't exist.");
    return false;
}

Any help would be amazing!

like image 222
MCsuchNsuch Avatar asked Mar 15 '26 21:03

MCsuchNsuch


1 Answers

You have to find the object in the array and then for example move the last object to that index (if it isn't already the last) and decrement size.

if (obj == null) return;

for (int i = 0; i < size; i++) {
    if (obj.equals(set[i])) {
        set[i] = set[--size];
        break;
    }
}
like image 139
Tobias Ritzau Avatar answered Mar 17 '26 11:03

Tobias Ritzau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!