HashMap用法总结

来源:互联网 发布:武汉大学罗知 编辑:程序博客网 时间:2024/05/16 23:55

Java中的HashMap的格式为<Key, Value>

和hashtable相比是unsynchronized的,同时也允许null值


常用method:

voidclear()

Removes all of the mappings from this map.

booleancontainsKey(Object key)

Returns true if this map contains a mapping for the specified key.
booleancontainsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
Vget(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
booleanisEmpty()
Returns tr
Vput(K key, V value)
Associates the specified value with the specified key in this map.
Vremove(Object key)
Removes the mapping for the specified key from this map if present.
booleanremove(Object key, Object value)
Removes the entry for the specified key only if it is currently mapped to the specified value.

Vreplace(K key, V value)

Replaces the entry for the specified key only if it is currently mapped to some value.
booleanreplace(K key, V oldValue, V newValue)
Replaces the entry for the specified key only if currently mapped to the specified value.
intsize()
Returns the number of key-value mappings in this map.
Set<Map.Entry<K,V>>entrySet()
Returns a Set view of the mappings contained in this map.

需要注意的是各种输入输出的类型(type),比如get方法返回的直接就是value的type。

关于Map.entry:

Modifier and TypeMethod and Descriptionbooleanequals(Object o)

Compares the specified object with this entry for equality.
KgetKey()
Returns the key corresponding to this entry.
VgetValue()
Returns the value corresponding to this entry.
inthashCode()
Returns the hash code value for this map entry.
VsetValue(V value)
Replaces the value corresponding to this entry with the specified value (optional operation).
关于set:

Iterator<E>iterator()

Returns an iterator over the elements in this set.

关于Iterator:

booleanhasNext()

Returns true if the iteration has more elements.
Enext()
Returns the next element in the iteration.
voidremove()
Removes from the underlying collection the last element returned by this iterator (optional operation).

例:以下为某次写的一小段代码,对于返回值类型为object还是key,value本身的类型非常迷茫,于是有很多冗余的cast:

Iterator iterator = map.entrySet().iterator();       while (iterator.hasNext()) {      Map.Entry pairs = (Map.Entry)iterator.next();      if (Integer.parseInt(pairs.getValue().toString()) % 2 == 1) {        iterator.remove();        return pairs.getKey().toString();      }    }

我用的HashMap<String, Integer>

其中pairs.getValue()已经是所需的东西了,并不需要用
Integer.parseInt(pairs.getValue().toString())
如此复杂的东西来表示~ 同理pairs.getKey()也不需要pairs.getKey().toString();

1 0
原创粉丝点击