Is a hashtable suitable for holding assets?

I come from the background of ActionScript3, and this is my first record of any Java in my life. Hashtables seem to be similar to dictionaries in Flash, but I want to make sure that I use them correctly. I believe that a Hashtable is printed to accept strings as keys and Typefaces as objects. It's right? Is there another subclass of the class that would be more suitable for something like that? By all means, please rip my n00b Java. I need to find out.

package com.typeoneerror.apps.app_name.utils;

import android.content.Context;
import android.graphics.Typeface;

import java.util.Hashtable;

public class FontRegistry
{
    private static FontRegistry _instance;

    private Context                         _context;
    private Hashtable<String, Typeface>     _fonts;

    private FontRegistry()
    {
        _fonts = new Hashtable<String, Typeface>();
    }

    public static FontRegistry getInstance()
    {
        if (_instance == null)
        {
            _instance = new FontRegistry();
        }
        return _instance;
    }

    public void init(Context context)
    {
        _context = context;

    }

    public Typeface getTypeface(int resourceId)
    {
        String fontName = _context.getResources().getString(resourceId);
        if (!_fonts.containsKey(fontName))
        {
            String fontPath = "fonts/" + fontName;
            Typeface typeface = Typeface.createFromAsset(_context.getAssets(), fontPath);
            _fonts.put(fontName, typeface);
        }
        return (Typeface)_fonts.get(fontName);
    }
}
+5
source share
2 answers

Two suggestions for you.

-, . Java.

-, HashMap, HashTable. HashTable , HashMap.

, ConcurrentHashMap HashTable. ConcurrentHashMap , .

,

private Map<String, Typeface>     _fonts;

_fonts = new HashMap<String, Typeface>();

, Java , - . .

: . , singleton . , http://accu.org/index.php/journals/337. , , singleton . .

:

private static FontRegistry _instance = new FontRegistry;
+7

, getInstance() . Singleton, "Bill Pugh" ( ):

public class Singleton {

    // Private constructor prevents instantiation from other classes
    private Singleton() {
    }

    /**
     * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
     * or the first access to SingletonHolder.INSTANCE, not before.
     */
    private static class SingletonHolder { 
        public static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

Android , "" Context. , , . , static Context ( , Context), , Activity .

+1

All Articles