Java基础--集合框架<二>

时间:2022-03-26 19:21:12


MapCollection在集合框架是并列存在的。

Map存储的是键对值。一对一对往里存,而且要保证键的唯一性。
Map存储元素使用的是put方法,Collection使用的是add方法。
Map集合没有直接取出元素的方法,而是先转换成Set集合,再通过迭代器获取元素。

Map
     |--Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。jdk1.0.效率低。
     |--HashMap:底层是哈希表数据结构,允许使用 null 值和 null 键,该集合是不同步的。将hashtable替代,jdk1.2.效率高。
     |--TreeMap:底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。

public class MapDemo {
public static void main(String[] args)
{
HashMap<String, String> map=new HashMap<String, String>();
//添加元素,如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
//并put方法会返回被覆盖的值。
map.put("01", "zhangsan1");
map.put("01", "wangwu"); //存入相同键,新的值会替换老的值

map.put("02", "zhangsan2");
map.put("03", "zhangsan3");
map.put("04", "zhangsan4");
System.out.println("containsKey:"+map.containsKey("05"));
//System.out.println("remove:"+map.remove("01"));
System.out.println("get:"+map.get("02"));
//可以同过get方法的返回值来判断一个键是否存在
map.put(null, "adidas");

//获取map集合中所有的值
Collection<String> collection= map.values();
System.out.println(collection);

System.out.println(map);

}
}