HashMap
HashMap
概述
HashMap是Map接口的十分重要的实现类
底层实现是数组+链表+红黑树
特点:无序,无脚标,键不可重复,值可重复
实践
如果HashMap的key或value是自定义类,想要两个内容相同的实例定义为同一个实例,需要重写hashcode和equals方法,总结:包含hash的集合元素如果是自定义类,内容相同的实例想要定义为一个实例,需要重写hashcode和equals,比如HashSet和HashMap;List实现类仅需要重写equals方法;Tree相关集合仅需重写比较方法
package com.qianfeng.collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* 功能描述
*
* @since 2022-05-16
*/
public class HashMapDemo {
public static void main(String[] args) {
Student1 student1 = new Student1("zhangsan", 1);
Student1 student2 = new Student1("lisi", 2);
Student1 student3 = new Student1("wangwu", 3);
HashMap<Student1, String> scores = new HashMap<>();
scores.put(student1, "89");
scores.put(student2, "80");
scores.put(student3, "78");
System.out.println(scores);
scores.remove(student1);
for (Student1 score : scores.keySet()) {
System.out.println(score + "========" + scores.get(score));
}
for (Map.Entry entry : scores.entrySet()) {
System.out.println(entry.getKey() + "---------" + entry.getValue());
}
System.out.println(scores.containsKey(new Student1("lisi", 2)));
System.out.println(scores.containsValue("88"));
}
}
class Student1 {
private String name;
private int stuNo;
public Student1() {
}
public Student1(String name, int stuNo) {
this.name = name;
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", stuNo=" + stuNo +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student1 student1 = (Student1) o;
return stuNo == student1.stuNo && Objects.equals(name, student1.name);
}
@Override
public int hashCode() {
return Objects.hash(name, stuNo);
}
}
package com.qianfeng.collection;
import java.util.HashMap;
import java.util.Map;
/**
* 功能描述
*
* @since 2022-05-16
*/
public class HashMapDemo2 {
public static void main(String[] args) {
Student1 student1 = new Student1("zhangsan", 1);
Student1 student2 = new Student1("lisi", 2);
Student1 student3 = new Student1("wangwu", 3);
HashMap<Student1, Student1> scores = new HashMap<>();
scores.put(student1, student1);
scores.put(student2, student2);
scores.put(student3, student3);
System.out.println(scores);
scores.remove(student1);
for (Student1 score : scores.keySet()) {
System.out.println(score + "========" + scores.get(score));
}
for (Map.Entry entry : scores.entrySet()) {
System.out.println(entry.getKey() + "---------" + entry.getValue());
}
System.out.println(scores.containsKey(new Student1("lisi", 2)));
System.out.println(scores.containsValue(new Student1("lisi", 2)));
}
}