简体   繁体   English

从元素集中删除对象

[英]Removing an object from an element set

This code removes an object of a certain class with a certain name from a set of object references of differing class types. 此代码从一组不同类类型的对象引用中删除具有特定名称的特定类的对象。 It finds the objects with a certain class name, and then the object in that class with the name field of the object in the parameter, then it removes the object. 它找到具有特定类名的对象,然后找到该类中的对象,并在参数中包含该对象的名称字段,然后删除该对象。 It returns true if the object is removed, and false if the object could not be found. 如果删除了该对象,则返回true;如果找不到该对象,则返回false。

When it removes the object, I get a null pointer exception when trying to print out all the objects in the array. 当它删除对象时,在尝试打印出数组中的所有对象时,出现空指针异常。 I assume this is because it points to where the removed object was, and there is nothing there. 我认为这是因为它指向已删除对象的位置,那里什么也没有。 I'm unsure of what to do to resolve this error. 我不确定该如何解决此错误。 Any help? 有什么帮助吗? Would I need to copy the data into a new array? 我需要将数据复制到新数组中吗?

Here's the code. 这是代码。 theList is the array of object references. 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;
  }

When printing out the elements of the array, first check if the element at each index is null . 打印出数组的元素时,首先检查每个索引处的元素是否为null If so, then simply continue . 如果是这样,则只需continue

Another way would be to shift the elements of the array: 另一种方法是移动数组的元素:

  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