HashMap集合底层是哈希表/散列表的数据结构,是一个数组和单向链表的结合体。 数组:在查询方面效率很高,随即增删方面效率很低 单向链表:在随机增删方面效率很高,在查询仿麦呢效率很低 哈希表将以上两种数据结构结合在一起,充分发挥它们各自的优点 放在HashMap集合key部分的元素,以及放在HashSet集合中的元素,需要同时重写hashCode和equals方法 HashMap集合默认初始化容量是16(必须是2的倍数),加载因子0.75,加载因子就是当HashMap集合底层数组的容量达到75%的时候,数组开始扩容
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapTest {
    public static void main(String[] args) {
        // Integer是key,它的hashCode和equals都重写了
        Map<Integer,String> map = new HashMap<>();
        map.put(2,"eYuJun2");
        map.put(3,"eYuJun3");
        map.put(1,"eYuJun1");
        map.put(3,"eYuJun3");// key重复,value会被覆盖
        System.out.println(map.size());//3
        // 遍历map集合
        Set<Map.Entry<Integer,String>> set = map.entrySet();
        for (Map.Entry<Integer,String> entry:set){
            System.out.println(entry);
        }
    }
}
import java.util.*;

public class HashMapTest {
    public static void main(String[] args) {
        Student s1 = new Student("eYuJun1");
        Student s2 = new Student("eYuJun2");
        Student s3 = new Student("eYuJun3");
        Student s4 = new Student("eYuJun3");
        System.out.println(s4.equals(s3));

        System.out.println("s3的hashCode:" + s3.hashCode());
        System.out.println("s4的hashCode:" + s4.hashCode());
        Set<Student> students = new HashSet<>();
        students.add(s3);
        students.add(s4);
        System.out.println(students.size());
    }
}

class Student{
    private String name;

    public Student() {
    }
    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

发表评论