HashMap的底层数据结构就是哈希表,哈希表就是数组+单向链表(Node数组里面存放的是链表)
优点:哈希表的增删检索效率都相对较高,他是数组和单向链表的结合体
缺点:在检索方面没有数组的效率高,在增加和删除的方面没有单向链表效率高
package Work03;
import java.util.Objects;
public class Student{
private String name;
private int age;
private float degree;
//分数
public Student() {
}
public Student(String name, int age, float degree) {
this.name = name;
this.age = age;
this.degree = degree;
}
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 float getDegree() {
return degree;
}
public void setDegree(float degree) {
this.degree = degree;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", degree=" + degree +
'}';
}
@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 && Float.compare(student.degree, degree) == 0 && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, degree);
}
}
package Work03;
import java.util.*;
public class TestStudent02 {
public static void main(String[] args) {
//使用hashSet和hashMap都需要重写equals方法和hashCode方法
Map<Integer,String> map=new HashMap();
map.put(1,"鲁班七号");
map.put(2,"达摩");
map.put(3,"吕布");
map.put(4,"凯");
//这里相当于会把之前的key为1的单向链表的里面的值替换成艾琳
map.put(1,"艾琳");
//通过entrySet去获取里面的值
Set<Map.Entry<Integer, String>> entries = map.entrySet();
Iterator<Map.Entry<Integer, String>> iterator=entries.iterator();
while(iterator.hasNext()){
Map.Entry<Integer,String> next = iterator.next();
System.out.println(next.getKey()+"======"+next.getValue());
}
}
}