从父项中删除子类对象?

时间:2014-06-15 06:57:52

标签: java android

我有一个静态ArrayList,它包含VisibleObject类型的所有对象。 所有VisibleObjects也是BaseClass的子类,可以是很多类的父类。

我的问题是调用VisibleObject删除调用,但由于某种原因,随着大小的增加,它实际上并未从ArrayList中删除。

创建新的VisibleObject时,会添加VisibleObject

以下是问题代码。

//Remove base class and visible object.
    List<BaseClass> baseClassList = this.mBaseClassExtras;
    Iterator<BaseClass> baseClassIterator = baseClassList.iterator();
    while(baseClassIterator.hasNext())
    {
        BaseClass baseClass = baseClassIterator.next(); // must be called before you can call i.remove()
        baseClass.update(delta);

        if(baseClass.getIsCompleted())
        {
            if(baseClass instanceof VisibleObject)
            {
                if(VisibleObject.AllVisibleObjects.remove(baseClass))
                {
                    Functions.out("VisibleObject removed.");
                }
                else
                {
                    Functions.out("Failed to remove VisibleObject - Possible memory problems.");
                }
            }

            //Remove the base class.
            baseClassIterator.remove();
        }
    }

    //BaseClass
    if(mBaseClassExtras.size() > 0)
    {
        Functions.out(
                "Is called, VisibleObjects array:" + VisibleObject.AllVisibleObjects.size() +
                " | BaseClass size: " + mBaseClassExtras.size()
        );
    }

以下是System(Partial)

的输出
06-15 06:49:36.793    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: VisibleObject     removed.
06-15 06:49:36.793    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: Is called, VisibleObjects array:105 | BaseClass size: 11
06-15 06:49:36.825    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: Is called, VisibleObjects array:105 | BaseClass size: 12
06-15 06:49:36.857    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: VisibleObject removed.
06-15 06:49:36.857    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: Is called, VisibleObjects array:104 | BaseClass size: 11
06-15 06:49:36.893    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: Is called, VisibleObjects array:105 | BaseClass size: 11
06-15 06:49:36.925    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: Is called, VisibleObjects array:105 | BaseClass size: 12
06-15 06:49:36.977    9301-9301/com.youllneverknowmycompany.topsecretapp I/System.out﹕ OLLY_SYSTEM: VisibleObject removed.

1 个答案:

答案 0 :(得分:0)

我通过在两个类中链接一个同名的方法来解决这个问题。调用该方法时,它从存储它的类(静态)中删除了ArrayList项。

然后它转到父类并执行删除它自己的标准方法。工作完美!