String类不是一个整型,所以不能直接进行%。
这里要用到方法的重写(hash和equals)把他们转换成整数才能进行%。
代码:
import java.util.Objects;
class Person{
public String id;
public Person(String id) {
this.id = id;
}
//方法的重写
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(id, person.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
public class HashBack2<K,V> {
static class Node<K,V>{
public K key;
public V val;
public Node<K,V> next;
//构造方法
public Node(K key, V val) {
this.key = key;
this.val = val;
}
}
public Node<K,V>[] array;
public int usedSize;
public HashBack2(){//初始化
array=(Node<K, V>[]) new Node[10];
}
public void put(K key,V val){
int hash=key.hashCode();
int index=hash%array.length;
Node<K,V> cur=array[index];
//遍历数组
while (cur!=null){
if(cur.key.equals(key)){//字符串要用equals
cur.val=val;
return;
}
cur=cur.next;
}
//没有找到key
Node<K,V> node=new Node<>(key,val);//插入的数实例化
//头插
node.next=array[index];
array[index]=node;
usedSize++;
}
public V get(K key){
int hash=key.hashCode();
int index=hash%array.length;
Node<K,V> cur=array[index];
while (cur!=null){
if(cur.key.equals(key)){
return cur.val;
}
cur=cur.next;
}
return null;
}
}
测试类:
public static void main(String[] args) {
Person person=new Person("123");
Person person1=new Person("123");
HashBack2<Person,String> hashBack2=new HashBack2<>();
hashBack2.put(person1,"wangyuan");
System.out.println(hashBack2.get(person1));
}
结果: