Let's say that i have an array of objects.

So, I need to delete the object at the given index and make sure to compress myObjects and update currentObject. Also, I have to verify that the given index exists in myObjects.

This is what I got:
NOTE: I will just show part of my program, because it's a long program but everthing is working well so far...

First: Those are my attributes:

private final int INITIAL_ARRAY_SIZE = 10;
private final int ARRAY_EXPAND = 20;
private Object[] myObjects = new Object[INITIAL_ARRAY_SIZE];
private int currentObject;

And this is my deleteObject(int index)

public void deleteObject(int index) {


    for(int i = index; i < myObjects.length - 1; i++){
        myObjects[i] = myObjects[i + 1];

    }   

How can I update my currentObject and compress myObjects?
Do I need something that compress it?

Please if you are confuse with something or have aditional questions please let me know.

update current object - depends on whether it was one of the objects you moved in that loop

you can't "compress" an array. If your array has unused space at the end you can copy it to a new smaller array and let the old array get garbage collected

Hey James,

Doesn't this part:

myObjects[i] = myObjects[i + 1];

does this part update it?

you could implement a linked list as an array so as to use pointers after deleting since you can't compress an array

does this part update it?

That updates the existing array to overwrite the "deleted" entry. Eg if the array was {2,4,6,8} and you delete index 1 the array will now be {2,6,8,8} - ie the correct entry has been deleted, but you now have a "spare" entry at the end. There's also a problem with the currentObject variable - with the example above, if currentObject was 0 that's OK, if it was 2 or 3 it will now be referring to the wrong entry because they have moved. And what if it was 1 and you just deleted that?

@James

Thanks,Im' working on it!

i came up with this:

public void deleteObject(int index) {
    for(int i = index; i < myObjects.length - 1; i++){
        myObjects[i] = myObjects[i + 1];
} 
    currentObject = myObjects.length - index;
}

It does works, but the fact that my professor wrote the demo part I'm not sure if this part is testing all probabilities.

That does not check the index value as required in your spec, and overwrites currentIndex to point at some arbitrary location regardless of what its previous value may have been. See my reply to your other post for suggestions on how to get this logic right.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.