从对象数组中删除对象

时间:2015-05-06 00:24:24

标签: java arrays sorting

public class SortedListOfImmutables {


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

private Listable[] items;

下面的方法从列表中删除一个项目。如果列表包含参数引用的相同项目,它将从列表中删除。如果项目多次出现在列表中,则只会删除一个实例。如果该项目未出现在列表中,则此方法不执行任何操作。 @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;

}

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

1 个答案:

答案 0 :(得分:1)

将您的第二个for循环更改为

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

这应该适合你。

编辑:

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