Java中的HashMap的格式爲<Key, Value>
和hashtable相比是unsynchronized的,同時也允許null值
常用method:
void |
clear()
Removes all of the mappings from this map.
|
boolean |
containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
|
boolean |
containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
|
V |
get(Object key)
Returns the value to which the specified key is mapped, or
null if this map contains no mapping for the key. |
boolean |
isEmpty()
Returns tr
|
V |
put(K key, V value)
Associates the specified value with the specified key in this map.
|
V |
remove(Object key)
Removes the mapping for the specified key from this map if present.
|
boolean |
remove(Object key, Object value)
Removes the entry for the specified key only if it is currently mapped to the specified value.
|
V |
replace(K key, V value)
Replaces the entry for the specified key only if it is currently mapped to some value.
|
boolean |
replace(K key, V oldValue, V newValue)
Replaces the entry for the specified key only if currently mapped to the specified value.
|
int |
size()
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 Type | Method and Description |
---|---|
boolean |
equals(Object o)
Compares the specified object with this entry for equality.
|
K |
getKey()
Returns the key corresponding to this entry.
|
V |
getValue()
Returns the value corresponding to this entry.
|
int |
hashCode()
Returns the hash code value for this map entry.
|
V |
setValue(V value)
Replaces the value corresponding to this entry with the specified value (optional operation).
|
Iterator<E> |
iterator()
Returns an iterator over the elements in this set.
|
關於Iterator:
boolean |
hasNext()
Returns
true if the iteration has more elements. |
E |
next()
Returns the next element in the iteration.
|
void |
remove()
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();