根据java1.6 的API整理一下HashMap的几个常用方法。
1.size
public int size();
返回此映射中的键-值映射关系数
2.isEmpty
public boolean isEmpty()
判断此map是否不包含键-值映射关系
3.get
public V get(Object key)
返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回
null。返回 null 值并不一定表明该映射不包含该键的映射关系;也可能该映射将该键显示地映射为
null。
4.containsKey
public boolean containsKey(Object key)
判断map中是否包含指定键,包含则返回true
5.containsValue
public boolean containsValue(Object value)
判断map中是否包含指定值
6.put
public V put(K key, V value);
在此map中关联指定值与键。如果该映射以前包含了一个该键的映射关系,则旧值被替换。返回值是与 key 关联的旧值;如果 key 没有任何映射关系,则返回 null。(返回 null 还可能表示该映射之前将 null 与 key 关联。)
7.putAll
public void putAll(Map<K,V> m)
指定映射的所有映射关系复制到此map中
8.remove
public V remove(Object key);
从此map中移除指定键的映射关系(如果存在)。返回值是与 key 关联的旧值;如果 key 没有任何映射关系,则返回 null。(返回 null 还可能表示该映射之前将 null 与 key 关联。)
9.clear
public void clear()
从此map中移除所有映射关系。此调用返回后,map将为空。
10.keySet
public Set<K> keySet()
返回此映射中所包含的键的Set视图
11.values
public Collection<V> values()
返回此映射所包含的值的Collection视图
12.entrySet
public Set<Entry<K,V>> entrySet();
返回此映射所包含的映射关系的set视图
package collection;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
//hashMap是Map接口的实现,存储键值对,并允许null值和null键,此实现是非同步的
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
//插入一些键值对
for(int i = 0; i < 10 ; i++){
map.put(i, i + 1);
}
//1.返回此映射中的键-值映射关系数。
int size = map.size();
System.out.println("共有键值对:" + size);
//2.判断map中是否不包含键值对
boolean isEmpty = map.isEmpty();
System.out.println("判断map中包含键值对:" + isEmpty);
//3.得到指定键映射的值,如果对于该键来说,此映射不包含任何映射关系,则返回 null
int value = map.get(1);
System.out.println("键1映射的值是:" + value);
//4.判断map中是否包含指定键
boolean isExist = map.containsKey(1);
System.out.println("map中包含键为1的映射关系:" + isExist);
//5.判断map中是否包含指定值
isExist = map.containsValue(-1);
System.out.println("map中包含值为-1的映射关系" + isExist);
//6.在map中关联指定键与值,如果该映射以前包含了一个该键的映射关系,则旧值被替换。
//返回值为与 key 关联的旧值;如果 key 没有任何映射关系,则返回 null。
map.put(11,56);
//7.将指定map的所有映射关系复制到当前map中
Map<Integer, Integer> map2 = new HashMap<Integer,Integer>();
map2.put(12, 23);
map.putAll(map2);
//8.移除指定键的映射关系
map.remove(1);
System.out.println("键为1的映射关系存在吗" + map.containsKey(1));
//9.得到map中的所有键
Set<Integer> set = map.keySet();
System.out.println("map中的键为:");
for(Integer integer : set){
System.out.println(integer);
}
//10.得到map中的所有值
Collection<Integer> collection = map.values();
System.out.println("map中的键为:");
for(Integer integer : collection){
System.out.println(integer);
}
//11.得到map中的所有键值对
Set<Entry<Integer,Integer>> set2 = map.entrySet();
for(Entry<Integer,Integer> entry : set2){
System.out.println("键 " + entry.getKey() + "值 " + entry.getValue());
}
//12.从此map中移除所有映射关系。此调用返回后,map将为空。
map.clear();
System.out.println("map中的映射数为:" + map.size());
}
}
原文地址:http://blog.csdn.net/stellar1993/article/details/44907695