PNG("image/png", new HashSet
{
add("png");
}
}),
HashMap的默认大小是4,这样会浪费很多内存
Pull request welcome~
@liuzhanta
As @nekocode said, would you like to optimize this? It's fine if you don't, I'll do it myself then.
Extract from the source code of HashMap:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 4;
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) {
initialCapacity = MAXIMUM_CAPACITY;
} else if (initialCapacity < DEFAULT_INITIAL_CAPACITY) {
initialCapacity = DEFAULT_INITIAL_CAPACITY;
}
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// Android-Note: We always use the default load factor of 0.75f.
// This might appear wrong but it's just awkward design. We always call
// inflateTable() when table == EMPTY_TABLE. That method will take "threshold"
// to mean "capacity" and then replace it with the real threshold (i.e, multiplied with
// the load factor).
threshold = initialCapacity;
init();
}
So it won't take effect if you pass 1 as the initial capacity.
如果超过默认大小,HashMap会自动扩容,当前大小*2,所以还是会造成一定浪费,可能我的问题太刁钻了。
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
@liuzhanta
It's not a problem at all that you brought up this issue. As a matter of fact, it's better to do as you said above on some conditions. But Matisse has a very special case, so it won't make any difference if you pass the initial capacity or not.
You're always welcome to contribute or file an issue.
Most helpful comment
Extract from the source code of HashMap:
So it won't take effect if you pass 1 as the initial capacity.