在了解了内部类之后,我知道它有一个对外部类的隐式引用。
但是我的老师告诉我,最好的方法是不要使用内部类,更喜欢使用静态的内部类。因为内部类可能会泄漏内存。
有人能解释一下这件事吗?
发布于 2015-03-01 11:37:23
在你的评论的答案(如果我张贴在评论中它将是不可读的),它属于哪里。外部添加内部类的示例。
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.因此,您不需要通过parrent类访问内部类,一旦创建了内部对象,它就可以作为任何其他对象使用,并且可以“泄漏”它的容器类,例如在上面的示例中,当狗列表将保存对狗的引用时,每个狗仍然会“知道”它的狗舍。
当innner类作为匿名内部类创建'ad‘时,来自StackTrace的链接示例与典型的用例相关,但问题是相同的。如果传递对内部类的任何实例的引用,则也是对外部类的“传递”引用。
https://stackoverflow.com/questions/28789234
复制相似问题