java hashmap怎么初始化

Python013

java hashmap怎么初始化,第1张

HashMap 是一种常用的数据结构,一般用来做数据字典或者 Hash 查找的容器。普通青年一般会这么初始化

HashMap<String, String>map = new HashMap<String, String>()

map.put("name", "test")

map.put("age", "20")

看完这段代码,很多人都会觉得这么写太啰嗦了,文艺青年一般这么来了:

HashMap<String, String>map = new HashMap<String, String>() {

{

map.put("name", "test")

map.put("age", "20")

}

}

Portlet portlet = new Portlet() //Portlet 你的TestLzp

JSONObject jsonObject = JSONObject.fromObject(portlet) // net.sf.json.JSONObject

Map map = new HashMap()

for (Object objectKey : jsonObject.keySet()){

   String value = String.valueOf(jsonObject.get(objectKey))

   map.put(objectKey,value)

}

System.out.println(map.toString())

这个问题可以跟踪一下HashMap的源码就知道了,根据输入的初始化容量(门槛?)的值(先了解HashMap中容量和负载因子的概念,其实这个和HashMap确定存储地址的算法有关),先判断是否大于最大容量,最大容量2的30次方,1<<30 =(1073741824),如果大于此数,初始化容量赋值为1<<30,如果小于此数,调用tableSizeFor方法 使用位运算将初始化容量修改为2的次方数,都是向大的方向运算,比如输入13,小于2的4次方,那面计算出来桶的初始容量就是16.

public HashMap(int initialCapacity) {

        this(initialCapacity, DEFAULT_LOAD_FACTOR)

    }

 /**

     * 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)

        this.loadFactor = loadFactor

        this.threshold = tableSizeFor(initialCapacity)

    }

/**

* Returns a power of two size for the given target capacity.

*/

static final int tableSizeFor(int cap) {

int n = cap - 1

n |= n >>>1

n |= n >>>2

n |= n >>>4

n |= n >>>8

n |= n >>>16

return (n <0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1

}