java map
Collection集合的特点是每次进行单个对象的保存,如果现在要进行一对对象的保存,就只能用Map集合来完成,即Map集合中会一次性保存两个对象,且这两个对象的关系:key = value结构。这种结构的最大特点是可以通过key找到对应的value内容。
1.Map接口
Map接口定义:
public interface Map
在Map接口中有如下常用方法:
Map本身是一个接口,要使用Map需要通过子类进行对象实例化。Map接口的常用子类有如下四个:HashMap、HashTable、TreeMap、ConcurrentHashMap。
2.HashMap子类
如:基本操作public class Test{
public static void main(String[] args) {
Map map = new HashMap<>();
map.put(1, "A");
map.put(1, "A+");
map.put(2, "B");
map.put(3, "C");
System.out.println(map);
System.out.println(map.get(2)); //根据key取得value
System.out.println(map.get(10)); //找不到返回null
//取得Map中所有key信息
Set set = map.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}注意:
(1)key值不允许重复,如果重复,则会把对应value值更新;
(2)key和value都允许为null,key为null有且只有一个。
HashMap原理:在数据量小的(jdk1.8后阈值为8)时候,HashMap是按照链表的模式存储的;当数据量变大之后,为了进行快速查找,会将这个链表变为红黑树(均衡二叉树)来进行保存,用hash来进行查找。
3.HashTable子类
如:HashTable使