概述
- 底层数据结构是哈希表,是Map集合类的一个子类,它的数据结构只针对键有效。
- 没有特有的方法,使用参考Map集合。
HashMapDemo
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/*
* HashMapDemo
*/
public class HashMapDemo {
public static void main(String[] args) {
//定义一个HashMap并放入元素
HashMap<String,String> hm =new HashMap<>();
hm.put("001", "张三");
hm.put("002", "李四");
hm.put("003", "王五");
hm.put("004", "赵六");
//============遍历方法一================
//获取key的集合
Set<String> keySet = hm.keySet();
System.out.println("\t\t编号\t\t姓名");
//遍历key集合
for (String key : keySet) {
//用key获取值
System.out.println("\t\t"+key+"\t\t"+hm.get(key));
}
System.out.println("---------------------------------------------");
//============遍历方法二================
System.out.println("\t\t编号\t\t姓名");
//获取Entry对象
Set<Entry<String, String>> entrySet = hm.entrySet();
for (Entry<String, String> entry : entrySet) {
//用Enrty分别获取键和值
System.out.println("\t\t"+entry.getKey()+"\t\t"+entry.getValue());
}
}
}
HashMap集合键是String值是自定义类Singer的Demo
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import com.itbull.map.traversal.Singer;
/*
* HashMap集合键是String值是自定义类Singer的Demo
*/
public class HashMapDemo1 {
public static void main(String[] args) {
//定义Singer对象
Singer s1 = new Singer("邓紫棋", "泡沫");
Singer s2 = new Singer("银 临", "牵丝戏");
Singer s3 = new Singer("谢春花", "只道寻常");
Singer s4 = new Singer("Taylor", "TikTok");
//定义HashMap集合
HashMap<String,Singer> hm = new HashMap<>();
//将Singer对象放入HashMap
hm.put("001", s1);
hm.put("002", s2);
hm.put("003", s3);
hm.put("004", s4);
//获取Entry集合
Set<Entry<String, Singer>> entrySet = hm.entrySet();
//打印标题
System.out.println("\t\t"+"编号"+"\t\t"+"歌手"+"\t\t"+"歌曲");
//遍历Entry对象
for (Entry<String, Singer> entry : entrySet) {
//分别用Entry获取键和值
System.out.println("\t\t"+entry.getKey()+"\t\t"+entry.getValue().getName()+"\t\t"+entry.getValue().getSongName());
}
}
}
HashMap集合键是自定义类Singer值是String的Demo
- 注意:自定义类需要重写hashCode**和equals方法才能保证元素唯一**
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;
import com.itbull.map.traversal.Singer;
/*
* HashMap集合键是自定义类Singer值是String的Demo
*/
public class HashMapDemo2 {
public static void main(String[] args) {
//定义Singer对象
Singer s1 = new Singer("邓紫棋", "泡沫");
Singer s2 = new Singer("银 临", "牵丝戏");
Singer s3 = new Singer("谢春花", "只道寻常");
Singer s4 = new Singer("Taylor", "TikTok");
//定义HashMap集合
HashMap<Singer,String> hm = new HashMap<>();
//将Singer对象放入HashMap
hm.put(s1,"001");
hm.put(s2,"002");
hm.put(s3,"003");
hm.put(s4,"004");
//获取Entry集合
Set<Entry<Singer, String>> entrySet = hm.entrySet();
//打印标题
System.out.println("\t\t"+"编号"+"\t\t"+"歌手"+"\t\t"+"歌曲");
//遍历Entry对象
for (Entry<Singer, String> entry : entrySet) {
//分别用Entry获取键和值
System.out.println("\t\t"+entry.getValue()+"\t\t"+entry.getKey().getName()+"\t\t"+entry.getKey().getSongName());
}
}
}
HashMap嵌套HashMap(理解)
HashMap嵌套ArrayList(理解)
HashMap嵌套ArrayList(理解)
HashMap与Hashtable的区别
- 通过查看API可以知道:
- HashMap: 线程不安全 , 效率高;允许null值和null键
- Hashtable: 线程安全 , 效率低;不允许null值和null键