1.Map集合类和Collection集合类的区别:
Collection中的集合,元素是孤立存在的(理解为单身),向集合中存储元素采用一个个元素的方式存储;
Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的值;
Collection中的集合称为单列集合,Map中的集合称为双列集合;
2.常见的实现类
Collection:
-----List
-----LinkedList 非同步
----ArrayList 非同步,实现了可变大小的元素数组
----Vector 同步
------Stack
-----Set 不允许有相同的元素
Map:
-----HashTable 同步,实现一个key–value映射的哈希表
-----HashMap 非同步,
-----WeakHashMap 改进的HashMap,实现了“弱引用”,如果一个key不被引用,则被GC回收
3.Map集合类常见方法
get方法:获取指定键(key)所对应的值(value);
put方法:将指定的键与值对应起来,并添加到集合中,方法返回值为键所对应的值;
remove方法:根据指定的键(key)删除元素,返回被删除元素的值(value);
Map map = new HashMap();
map.put("A", 100);
map.put("B", 90);
map.put("C", 110);
System.out.println(map);
//D 不存在,不会改变
map.replace("D", 80);
System.out.println(map);
//重新计算A
map.merge("A", 20, (oldVal, newVal) -> (Integer)oldVal + (Integer) newVal);
System.out.println(map);
//遍历
map.forEach((key, value) -> System.out.println("key : " + key + " , value:" + value));
//D 不存在,不存在时计算
map.computeIfAbsent("D", (key) -> ((String) key).length());
System.out.println(map);
//D存在了, 存在计算
map.computeIfPresent("D", (key, value) -> ((String) key).length() * 10);
System.out.println(map);
//Output
{A=100, B=90, C=110}
{A=100, B=90, C=110}
{A=120, B=90, C=110}
key : A , value:120
key : B , value:90
key : C , value:110
{A=120, B=90, C=110, D=1}
{A=120, B=90, C=110, D=10}
4.Collections集合类常见方法:
add方法:直接add元素
get方法:通过index获取元素
remove方法:通过index或者value来移除
List<String> person=new ArrayList<>();
person.add("jackie"); //索引为0 //.add(e)
person.add("peter"); //索引为1
person.add("annie"); //索引为2
person.add("martin"); //索引为3
person.add("marry"); //索引为4
person.remove(3); //.remove(index)
person.remove("marry"); //.remove(Object o)
String per="";
per=person.get(1);
System.out.println(per); .get(index)
for (int i = 0; i < person.size(); i++) {
System.out.println(person.get(i)); //.get(index)
}
5.几个注意的点:
5.1 HashMap和Hashtable是Map接口的实现类。
Hashtable 和 HashMap区别:
Hashtable 是线程安全的, HashMap是线程不安全的。
Hashtable 使用 null作为key和value, HashMap可以使用null作为key或value。 由于key不能重复, 最多只能有一个key为null。
Hashtable 比较古老,性能较差, 不推荐使用,
5.2 为了线程安全,可以使用 Collections 工具类。
扩展:什么是线程安全?
线程安全就是多线程访问时,采用了加锁机制,当一个线程访问该类的某个数据时,进行保护,其他线程不能进行访问直到该线程读取完,其他线程才可使用。不会出现数据不一致或者数据污染。
线程不安全就是不提供数据访问保护,有可能出现多个线程先后更改数据造成所得到的数据是脏数据
ArrayList是非线程安全的,Vector是线程安全的;HashMap是非线程安全的,HashTable是线程安全的;StringBuilder是非线程安全的,StringBuffer是线程安全的。
5.3Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值;
Map中常用的集合为HashMap集合、LinkedHashMap集合;