繁体   English   中英

从元素集中删除对象

[英]Removing an object from an element set

此代码从一组不同类类型的对象引用中删除具有特定名称的特定类的对象。 它找到具有特定类名的对象,然后找到该类中的对象,并在参数中包含该对象的名称字段,然后删除该对象。 如果删除了该对象,则返回true;如果找不到该对象,则返回false。

当它删除对象时,在尝试打印出数组中的所有对象时,出现空指针异常。 我认为这是因为它指向已删除对象的位置,那里什么也没有。 我不确定该如何解决此错误。 有什么帮助吗? 我需要将数据复制到新数组中吗?

这是代码。 theList是对象引用的数组。

 public boolean removeAnObject(Element anObject)
  {
     String paramClass = anObject.getClassName();
     String currClass;

     for (int i = 0; i < currentSize; i++)
     {
        currClass = theList[i].getClassName();
        if (currClass.equals(paramClass))
        {
           if (theList[i].equals(anObject))
           {
              theList[i] = null;
              return true;
           }
        }
     }

    // This object was not found in the set
     return false;
  }

打印出数组的元素时,首先检查每个索引处的元素是否为null 如果是这样,则只需continue

另一种方法是移动数组的元素:

  public boolean removeAnObject(Element anObject)
  {
     String paramClass = anObject.getClassName();
     String currClass;

     for (int i = 0; i < currentSize; i++)
     {
        currClass = theList[i].getClassName();
        if (currClass.equals(paramClass))
        {
           if (theList[i].equals(anObject))
           {
              for (int j = i; j < currentSize-1; j++) {
                 theList[j] = theList[j+1];
              }
              currentSize--;
              return true;
           }
        }
     }

    // This object was not found in the set
     return false;
  }

除了将其设置为null之外,如何将其删除?

theList = ArrayUtils.removeElement(theList, i);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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