目录
Map
特点:无序、以键值对的形式添加元素,键不能重复,值可以重复
它没有继承Collection接口
遍历
先取出保存所有键的Set,再遍历Set即可(2种)
先取出保存所有Entry的Set,再遍历此Set即可
public static void main(String[] args) {
//map特点:无序 键值对 键不能重复 值能重复
Map<String, Object> map =
new HashMap<String, Object>();
map.put("张三", "aa");
map.put("李四", "bb");
map.put("王五", "cc");
//map集合遍历方式 获取map集合中所有key的Set集合,再通过key获取value值
Set<String> keySet = map.keySet();
for (String key : keySet) {
// System.out.println(key);
Object value = map.get(key);
System.out.println(key+"="+value);
}
map.put("张三", "ab");
map.put("王五", "ab");
System.out.println("-----------------------------");
Collection<Object> values = map.values();
for (Object value : values) {
System.out.println(value);
}
for (String key : keySet) {
// System.out.println(key);
Object value = map.get(key);
System.out.println(key+"="+value);
}
System.out.println("-----------------------------");
//遍历方式 2.先取出保存所有键值对(Entry)的Set,再遍历此Set即可
Set<Entry<String, Object>> entrySet = map.entrySet();
for (Entry<String, Object> entry : entrySet) {
System.out.println(entry);
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
HashMap与HashTable之间的区别
同步既排队 线程安全的 hashtable 键不可以为null,值也不能为null
异步 非安全的 hashmap 键可以为null,值也可以为null
public static void main(String[] args) {
Map<String, Object> map =
new HashMap<String, Object>();
Map<String, Object> map1 =
new Hashtable<String, Object>();
map1.put("wq", null);
map1.put(null, "asds");
Set<Entry<String, Object>> entrySet = map1.entrySet();
for (Entry<String, Object> entry : entrySet) {
System.out.println(entry);
}