Map 双列数据,存储key-value对
HashMap:作为Map的主要实现类,线程不安全,效率高,可以存储null值的key和value
linkedHashMap:可以保证在遍历Map时,按照添加的顺序遍历map。
原因是底层在HashMap存储元素的基础上面,添加了指向前一个和后一个map元素的指针。
对于频繁遍历的map操作可以考虑使用linkedHashMap。
TreeMap:保证按照添加key-value对进行排序,可以实现排序遍历。此时考虑key的自然排序还是定时排序
底层是红黑树的数据结构。
Hashtable:作为map古老的实现类,线程安全,效率低;不能存储null值的key和value
Properties:常用来处理配置文件,key和value都是string类型的
HashMap的底层数据结构在jdk7和jdk8里面的区别?
jdk7:数组+链表
jdk8:数组+链表/红黑树
常见面试题:
(1)HashMap的底层实现原理?
(2)HashMap和Hashtable的区别?
(3)Hashtable和CurrentHashMap的区别?
package com.sf.MavenLearning0930;
import org.junit.Test;
import java.util.*;
public class MapTest {
@Test
public void test(){
HashSet hashSet = new HashSet();
HashMap hashMap = new HashMap();
hashMap.put(1,1);
hashMap.put(2,null);
hashMap.put(null,null);
hashMap.put(null,1);
System.out.println(hashMap);
}
@Test
public void test02(){
HashMap map = new HashMap();
map.put("ww","12");
map.put("qq","14");
map.put("ee","13");
System.out.println(map.get("ee"));
// map.remove("qq");
System.out.println(map);
// System.out.println(map.size());
System.out.println("-------------------");
//遍历key
Set key = map.keySet();
Iterator iterable = key.iterator();
while (iterable.hasNext()){
System.out.println(iterable.next());
}
System.out.println("------------------");
//遍历value
Collection collection = map.values();
Iterator iterator1 = collection.iterator();
while (iterator1.hasNext()){
System.out.println(iterator1.next());
}
System.out.println("------------------");
//遍历key-value 方法1
Set entries = map.entrySet();
Iterator iterator3 = entries.iterator();
while (iterator3.hasNext()){
Map.Entry a = (Map.Entry)iterator3.next();
System.out.println(a.getKey() + "----" + a.getValue());
}
//遍历key-value 方法2
Set key1 = map.keySet();
Iterator iterable4 = key1.iterator();
while (iterable4.hasNext()){
String keys = iterable4.next();
String values = map.get(keys);
System.out.println(keys + "=" + values);
}
}
}
Properties举例子:
jdbc.Properties里面的内容 name=jin password=123456
package com.sf.MavenLearning0930;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) {
FileInputStream fis = null;
try{
Properties pros = new Properties();
fis = new FileInputStream("jdbc.Properties");
pros.load(fis);
String name = pros.getProperty("name");
String password = pros.getProperty("password");
System.out.println(name + "-------" + password);
}catch (IOException e){
e.printStackTrace();
}finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}



