Map集合
Map是一个双列集合接口,如果实现了Map接口,
特点
- 数据以键值对形式存在,
- 键不可重复,(唯一)
- 值可以重复。
Map父接口
Map中存放的是两种对象,一种称为key(键),一种称为value(值),它们在在Map中是一一对应关系,这一对对象又称做Map 中的一个Entry(项)。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值
//创建
Map <String,String>map= new HashMap<>();
map.put("0122","阿娆");
map.put("02","Kimi");
map.put("03","Alice");
//map.put("03","john")
System.out.println("Map个数"+map.size());
System.out.println(map.toString());
//删除
//map.remove("02");
//遍历
//3.1KeySet()
Set<String> keyset=map.keySet();
for (String key:keyset) {
System.out.println(key+"****"+map.get(key));
}
//3.2 EntrySet
Set<Map.Entry<String,String>> entrySet=map.entrySet();
for (Map.Entry<String,String> entry:entrySet) {
System.out.println(entry.getKey()+"****"+entry.getValue());
}
Map个数3
{02=Kimi, 03=Alice, 0122=阿娆}
02Kimi
03Alice
0122阿娆
02Kimi
03Alice
0122阿娆
Map集合实现类
HashMap<Student,String> s=new HashMap<Student, String>();
//添加元素
Student s1 = new Student("Kimi",21);
Student s2 = new Student("阿娆",20);
Student s3 = new Student("Alice",19);
s.put(s1,"A");
s.put(s2,"B");
s.put(s3,"C");
s.put(new Student("Alice",200),"D");//可以添加,内存地址不一样,new了新的
System.out.println("元素个数" + s.size());
System.out.println(s.toString());
//删除
//s.remove(s1);
//遍历
//3.1 keySet();
for (Student key:s.keySet()){
System.out.println(key.toString() + "----" + s.get(key));
}
//3.2 entrySet
for (Map.Entry<Student,String> entry:s.entrySet()){
System.out.println(entry.getKey() + "***"+entry.getValue());
}
Map个数3
{02=Kimi, 03=Alice, 0122=阿娆}
02Kimi
03Alice
0122阿娆
02Kimi
03Alice
0122阿娆
源码
[](Java HashMap | 菜鸟教程 (runoob.com))
- HashMap刚创建时,table是null,为了节省空间,当添加第一个元素是,table容量调整为16
- 当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大小为原来的2倍。目的是减少调整元素的个数。
- jdk1.8当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的提高执行效率
- jdk1.8 当链表长度小于6时,调整成链表
- jdk1 .8以前,链表时头插入,jdk1 .8以后时是尾插入
HashTable
- HashMap【重点】
- JDK1.2版本,线程不安全,运行效率快 ;允许用null 作为key或是value。
- Hashtable
- JDK1.0版本,线程安全,运行效率慢;不允许null作为key或是value。
- Properties
- Hashtable的子类,要求key和value都是String。通常用于配置文件的读取。
- TreeMap
- 实现了SortedMap接口(是Map的子接口),可以对key自动排序。
TreeMap