视频链接:13.35 HashMap使用(1)_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1zD4y1Q7Fw?spm_id_from=333.788.videopod.episodes&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5&p=35
1.创建Student类,添加无参构造器、有参构造器、get()和set()方法、重写hashCode()方法和equals()方法;
package com.yundait.demo02;
import java.util.Objects;
public class Student {
private String name;
private int stuNo;
public Student() {
}
public Student(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 instanceof Student)) return false;
Student student = (Student) o;
return getStuNo() == student.getStuNo() && Objects.equals(getName(), student.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getStuNo());
}
}
2.创建HashMap类并演示添加元素、删除元素、遍历集合、判断操作
package com.yundait.demo02;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo01 {
public static void main(String[] args) {
//创建HashMap集合
HashMap<Student, String> students = new HashMap<>();
//1添加元素
Student s1 = new Student("孙悟空", 100);
Student s2 = new Student("猪八戒", 101);
Student s3 = new Student("沙和尚", 102);
students.put(s1,"北京");
students.put(s2,"南京");
students.put(s3,"杭州");
students.put(new Student("孙悟空", 100),"杭州");
System.out.println("元素个数为:" + students.size());
System.out.println(students.toString());
//2删除元素
// students.remove(s1);
System.out.println("删除后元素的个数:" + students.size());
System.out.println(students.toString());
//3遍历元素
//3.1使用keySet()方法遍历
System.out.println("-------使用keySet()方法遍历-------");
for(Student key : students.keySet()){
System.out.println(key + "------------" + students.get(key));
}
//3.2使用entrySet()方法进行遍历
System.out.println("-----使用entrySet()方法遍历--------");
for (Map.Entry<Student, String> entry : students.entrySet()) {
System.out.println(entry.getKey() + "------------" + entry.getValue());
}
//4判断元素
System.out.println(students.containsKey(s1)); //输出true
//因为重写了hashCode()和equals方法所以可以判定为相同元素
System.out.println(students.containsKey(new Student("孙悟空", 100))); //输出true
System.out.println(students.containsValue("东营")); //输出false
}
}