一、HashMap
HashMap<Student3,String>
Map的唯一性指的是键的唯一性,HashMap中需要键的类型要重写hashCode()方法和equals方法
二、HashMap的使用
1.编写Student3类,里面需要重写hashCode()方法和equals方法
import java.util.Objects;
public class Student3 {
private String name;
private int age;
public Student3() {
}
public Student3(String name, int age) {
this.name = name;
this.age = age;
}
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 boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student3 student3 = (Student3) o;
return age == student3.age && Objects.equals(name, student3.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.编写测试类
public class HashMapDemo1 {
public static void main(String[] args) {
HashMap<Student3, String> map1 = new HashMap<>();
Student3 s1 = new Student3("李刚", 21);
Student3 s2 = new Student3("钱志强", 22);
Student3 s3 = new Student3("江川", 21);
Student3 s4 = new Student3("李刚", 21);
Student3 s5 = new Student3("吴问强", 23);
map1.put(s1, "打羽毛球");
map1.put(s2, "唱");
map1.put(s3, "跳");
map1.put(s4, "看美女");
map1.put(s5, "打游戏");
System.out.println("map1: " + map1);
}
}
跟HashSet相似,都需要重写里面的方法
标签:Map,HashMap,Student3,子类,age,map1,public,name From: https://www.cnblogs.com/ndmtzwdx/p/18470833