简体   繁体   中英

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.

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.

 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 . If so, then simply 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);

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