HashMap的特点:
- HashMap是Map里面的一个实现类。
- 可直接使用Map里的方法。
- HashMap跟HashSet一样底层是哈希表结构的
小练习(HashMap的使用):
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
HashMap<Student,String> hm = new HashMap<>();
Student s1 = new Student("小a",22);
Student s2 = new Student("小b",21);
Student s3 = new Student("小d",25);
Student s4 = new Student("小c",20);
hm.put(s1,"福建");
hm.put(s2,"北京");
hm.put(s3,"天津");
hm.put(s4,"上海");
// System.out.println(hm);
System.out.println("------------------------------------------");
//第一种:获取键值对
Set<Map.Entry<Student, String>> entries = hm.entrySet();//获取到所有的键值对
for (Map.Entry<Student, String> entry : entries) {
Student key = entry.getKey();//获取键
String value = entry.getValue();//获取值
System.out.println(key + value);//输出键和值
}
System.out.println("------------------------------------------");
//第二种:先获取键,再通过键获取到值
Set<Student> k = hm.keySet();//获取到所有的键
for (Student student : k) {
String s = hm.get(student);//获取到值
System.out.println(s + student);//输出键和值
}
System.out.println("===========================================");
hm.forEach(
//小括号里直接写键和值,大括号里是写如何处理键和值
(Student key,String value)->{
System.out.println(key + value);
}
);
小结:
- HashMap底层是哈希表结构的
- 遗憾hashCode方法和equals方法保证键的唯一
- 如果键要存储的是自定义对象,需要重写hashCode和equals方法