码迷,mamicode.com
首页 > 其他好文 > 详细

HashMap用法总结

时间:2014-09-08 06:27:06      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   java   ar   

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).
关于set:

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();

HashMap用法总结

标签:des   style   blog   http   color   os   io   java   ar   

原文地址:http://blog.csdn.net/he_wolf/article/details/39132323

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!