从对象数组中删除对象

时间:2021-06-14 20:14:50
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

下面的方法从列表中删除一个项目。如果列表包含参数引用的相同项目,它将从列表中删除。如果项目多次出现在列表中,则只会删除一个实例。如果该项目未出现在列表中,则此方法不执行任何操作。 @param itemToRemove指的是要从列表中删除的项目

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,

当我运行这个时,我得到一个超时错误。我做错了什么以及如何解决它。注意:我不允许使用ArrayList,HashSet或LinkedList,

1 个解决方案

#1


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.

删除while(count == 0)循环,这是创建超时。

#1


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.

删除while(count == 0)循环,这是创建超时。