[英]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.