Java笔记:用哈希表记录自定义类数据(hashCode)

如果以后要向哈希表当中存放自定义类型必须重写equals和hashCode方法

  • 重写hashCode是为了获取对象地址值对应的哈希值,然后通过哈希函数将哈希值转换为int类型的数组下标。
  • 重写equals是为了实现自定义类型key的比较。
import java.util.Objects;
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

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

//自定义一个hashMap
class HashBack2<K,V> {

    static class Node<K,V> {
        private K key;
        private V value;
        private Node<K,V> next;
        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node<K,V>[] array = (Node<K,V>[])new Node[8];
    //存放单链表的头结点
    private int size;//当前数据的个数

    public void put(K key,V value) {
        //int index = key % array.length;
        int hashCode = key.hashCode();
        int index = Math.abs(hashCode) % array.length;
        System.out.println("index:"+index);
        for(Node<K,V> cur = array[index]; cur != null; cur = cur.next) {
            if(cur.key.equals(key)) {
                cur.value = value;
                return;
            }
        }
        //头插法
        Node<K,V> node = (Node<K,V>)new Node(key,value);
        node.next = array[index];
        array[index] = node;
        this.size++;
    }

    public V getValue(K key) {
        int hashCode = key.hashCode();
        int index = Math.abs(hashCode) % array.length;

        Node<K,V> head = array[index];
        for(Node<K,V> cur = head;cur != null;cur = cur.next) {
            if(cur.key.equals(key)) {
                return cur.value;
            }
        }
        return null;
    }

}

public class TestDemo2 {

    public static void main(String[] args) {
        Person person = new Person("gao",18);
        Person person2 = new Person("gao",18);
        System.out.println(person.hashCode());
        System.out.println(person2.hashCode());
        HashBack2<Person,String> hashBack2 = new HashBack2<>();
        hashBack2.put(person,"131200036");

        String id = hashBack2.getValue(person2);
        System.out.println(id);

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值