本文介绍了内部类具有对外部类的隐式引用,并且可能会泄漏内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

了解了内部类之后,我知道它对外部类有隐式引用.

After learning about the inner class, I understand it has an implicit reference to the outer class.

但是我的老师告诉我,最好的方法是不使用内部类,而更喜欢使用静态内部类.因为内部类可能会泄漏内存.

But my teacher told me that the best way is not use inner class, prefer to use static inner class. Because the inner class may leak memory.

有人可以对此进行解释吗?

Can someone kindly explain about this?

推荐答案

在您的评论的答案中(如果我将其发布在评论中,将不可读).在外部之外访问内部类的示例.

In the answer to your comment (it would be unreadable if I posted it in the comments), where it belongs. Example of accesing inner class outside the outer.

public class Dog {
    String name;
}

public class HugeKennel {
    Double[] memmoryWaste = new Double[10000000];


    public List<Dog> getDogs() {
        SneakyDog trouble = new SneakyDog("trouble");
        return Arrays.asList(trouble);
    }

    class SneakyDog extends Dog {
        SneakyDog(String name) {
            this.name = name;
        }
    }

}

代码中的其他地方

List<Dog> getCityDogs() {
    List<Dog> dogs = new ArrayList<>();
    HugeKennel k1 = ...
    dogs.addAll(k1.getDogs());
    HugeKennel k2 = ...
    dogs.addAll(k2.getDogs());
    return dogs;
}

....

List<Dog> cityDogs = getCityDogs();
for (Dog dog: dogs) {
    walkTheDog(dog);
}
// even though the Kenels were local variables in of getCityDogs(), they cannot be removed from the memory, as the SneakyDogs in the list are still referencing their parent kennels.
//from now on, until all the dogs are not disposed off, the kennels also have to stay in the memory.

因此,您不需要通过其父类访问内部类,一旦创建了内部对象,就可以将其用作任何其他对象,并且可以泄漏"到其容器类的外部,如上例所示,当狗列表中包含对狗的引用时,每只狗仍会知道"其狗窝.

So you don't need to access the inner class through its parrent class, once the inner object is created it can be used as any other object and can be 'leaked outside' its container class, like in the above example, when the dog list will hold references to dogs, but each dog will still 'know' about its kennel.

StackTrace的链接示例与典型的用例有关,当内部类被创建为"ad hock"作为匿名内部类时,但这是相同的问题.如果将引用传递给内部类的任何实例,那么您还将传递"对外部类的引用.

The linked example from StackTrace was related to typical use case, when the innner classes are created 'ad hock' as anonymous inner classes, but it is the same problem. If you pass the reference to any instance of an inner class, you are also 'passing' reference to the outer class.

这篇关于内部类具有对外部类的隐式引用,并且可能会泄漏内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 05:44