HashMAp存储自定义类型键值和LinkedHashMap集合
HashMap存储自定义类型键值
练习:每名学生(姓名,年龄)都有自己的家庭住址。那么既然有对应关系,则将学生对象和家庭住址存储到map集合中,学生作为键,家庭住址作为值
注意:学生姓名相同比国内且年龄相同视为同一名学生
HashMap存储自定义类型的键值
Map集合保证key是唯一的:
作为key的元素,必须重写hashCode方法和equals方法,以保证key唯一
代码实现:
//学生类
class Student{
private String name;
private int 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;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, 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;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
}
//测试类
public class Test{
public static void main(String[] args) {
HashMap<Student, String> map = new HashMap<>();
map.put(new Student("张三",17),"河北");
map.put(new Student("李四",20),"山东");
map.put(new Student("王五",15),"重庆");
map.put(new Student("赵六",20),"大连");
map.put(new Student("赵六",20),"大连");
map.forEach((student, s) -> {
System.out.println("学生姓名:"+student.getName()+"学生年龄:"+student.getAge()+"学生地址:"+s);
});
}
}
LinkedHashMap集合
public class Test{
/**
* java.util.LinkedHashMap<K,V> extends HashMap<K,V>
* Map接口的哈希表和链表列表实现,具有可与之的迭代顺序。
* 底层原理:
* 哈希表+链表(记录元素的顺序)
* @param args
*/
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("c","c");
map.put("a","a");
map.put("b","b");
map.put("b","b");
System.out.println(map);//{a=a, b=b, c=c} key不允许重复,无序
LinkedHashMap<String, String> linked = new LinkedHashMap<>();
linked.put("c","c");
linked.put("a","a");
linked.put("b","b");
linked.put("b","b");
System.out.println(linked);//{c=c, a=a, b=b} key不允许重复,有序
}
}