为什么安卓preFER静态类 [英] Why does Android prefer static classes

查看:172
本文介绍了为什么安卓preFER静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了很多的Java code其中安卓prefers让开发人员使用静态内部类。特别是对于像<一个模式href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html">ViewHolder格式定制ListAdapters。

I see a lot of java code where android prefers to have developers use static inner classes. Particularly for patterns like the ViewHolder Pattern in custom ListAdapters.

我不知道的区别是静态的和非静态类的东西。我读过有关,但它似乎并没有在其性能和内存占用关注是有道理的。

I'm not sure what the differences are between static and non-static classes. I've read about it but it doesn't seem to make sense when concerned with performance or memory-footprint.

推荐答案

这不只是Android开发者...

It's not just Android developers...

一个非静态内部类始终保持一个隐含的引用封闭对象。如果你不需要的参考,它是所有成本内存。试想一下:

A non-static inner class always keeps an implicit reference to the enclosing object. If you don't need that reference, all it does is cost memory. Consider this:

class Outer {
    class NonStaticInner {}
    static class StaticInner {}
    public List<Object> foo(){ 
        return Arrays.asList(
            new NonStaticInner(),
            new StaticInner()); 
    }
}

当你编译它,你得到的将是这样的:

When you compile it, what you get will be something like this:

class Outer {
    Outer(){}
    public List<Object> foo(){ 
        return Arrays.asList(
            new Outer$NonStaticInner(this),
            new StaticInner()); 
    }
}
class Outer$NonStaticInner {
    private final Outer this$0;
    Outer$NonStaticInner(Outer enclosing) { this$0 = enclosing; }
}
class Outer$StaticInner {
    Outer$StaticInner(){}
}

这篇关于为什么安卓preFER静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆