简体   繁体   中英

Removing objects from an array of Objects

public class SortedListOfImmutables {


 // Assume that I already have constructors that create new objects,
 // thus have its own items array.

private Listable[] items;

The method below removes an item from the list.If the list contains the same item that the parameter refers to, it will be removed from the list. If the item appears in the list more than once, just one instance will be removed. If the item does not appear on the list, then this method does nothing. @param itemToRemove refers to the item that is to be removed from the list

public void remove(Listable itemToRemove) {

    Listable[] newList = new Listable[items.length - 1];

    int count = 0;

    if(items.length == 0){
        newList[0] = itemToRemove;
    }else {
 /*Compares objects. If they are equal, I replace the index of items
  * to null. I use int count to make sure that it only makes one object
  * null.
  */
        for(int i = 0; i < items.length; i++){
            while(count == 0){
                if(items[i].equals(itemToRemove)){
                    items[i] = null;
                    count++;
                }
            }
        }
    }

    int changeVar = 0;

 /* Copy all the objects into my newList array. Wherever items is null,
  * skip to the next index of items and put it into newList.
  */
    for(int i = 0; i < newList.length; i++){
        newList[i] = items[i + changeVar];
        if(items[i + changeVar] == null){
            changeVar += 1;
            newList[i] = items[i + changeVar];
        }
    }

    items = newList;

}

When I run this I get a timeout error. What did I do wrong and how can I fix it. Note: I am not allowed to use ArrayList, HashSet, or LinkedList,

Change your second for loop to

int j=0;
for (int i = 0; i < items.length; i++) {
        if (items[i] ! = null) {
            newList[j] = items[i];
            j++;
        }
}

This should work for you.

Edit:

Remove the while (count==0) loop, this is creating the timeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM