关于static和final的一点疑问

今天看到这样一行代码:

private final HashMap<Font, WeakReference<Typeface>> mTypefaces = new HashMap<Font, WeakReference<Typeface>>();

不太理解用final修饰的用途。
推测其意图可能是想避免重复加载字体文件,导致大量耗时,所以将Typeface对象存放到HashMap中,并用弱引用引用之。
但如果是这种意图,用static修饰HashMap是不是更合理点。
另外,在网上看到有人用WeakHashMap,不太理解和HashMap之间的区别,希望大神指点迷津。

阅读 2.8k
2 个回答

不能再给mTypefaces赋值,

private final HashMap<Font, WeakReference<Typeface>> mTypefaces = new HashMap<Font, WeakReference<Typeface>>();

~~mTypefaces = new HashMap<Font, WeakReference<Typeface>>();~~(error)

Java 修饰符

In the Java programming language, the final keyword is used in several different contexts to define an entity that can only be assigned once.

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object (this property of final is called non-transitivity[1]). This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.[2]

以上是wikipedia的一段关于final的描述,简单点来说就是final修饰了就不能修改,其中分两种情况,一种是值变量,如int,char,String之类是不可修改的,第二种是对象集之类,如StringBuffer等,可以append,但是不能更换引用指向的对象。

        final String test = "test";
        final StringBuffer sB = new StringBuffer();
        
        try{
            test = "123";
        }catch(Exception e){
            System.out.println("string ");
        }
        
        try{
            sB.append(test);
        }catch(Exception e){
            System.out.println("stringBuffer.append ");
        }
        
        try{
            sB = new StringBuffer();
        }catch(Exception e){
            System.out.println("stringBuffer new");
        }
        

编辑器自己就会有提示

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题