`
yuanlanjun
  • 浏览: 1185712 次
文章分类
社区版块
存档分类
最新评论

java.util.Map使用心得

 
阅读更多

注意点1:

Map的容量如何定义

Map xMap = new HashMap();在Map的子类HashMap中,可以在创建的时候指定容量,没有指定的情况是默认16,源代码一直都是很好的证明工具之一,下面是HashMap()的源代码块

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 16;

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
    }

从这两个块中可以看到默认的容量是16。

而Map xMap = new HashMap(6);这里所指定的6,是用户期望的数量,为了提高效率,Map的容量会是2的幂,就是一些移位操作的原因了,内部其实是这样的:

/**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        // Find a power of 2 >= initialCapacity
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);
        table = new Entry[capacity];
        init();
    }


关键看这个:

int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;

所以,传入6,实际上市会生成容量为8的HashMap,传入9的话,就是16了。

注意点2:

更容错的Map取值方法

参考文章:http://hellosure.iteye.com/blog/1255080

当需要用String.valueOf(Object obj)来取值作为map.get(key)中的key值的时候,建议使用map.get(String.valueOf((Object)obj));这样可以预防在取到null值时候的比较难找的错误。

持续更新....20120703

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics