代码实现
package com.Keafmd.April.test; import java.util.HashMap; /** * Keafmd * * @ClassName: TestHashMap * @Description: * @author: 牛哄哄的柯南 * @Date: 2021-04-21 14:37 * @Blog: https://keafmd.blog.csdn.net/ */ public class TestHashMap { public static void main(String[] args) { /*HashMap<Integer,String> hashMap = new HashMap<>(); hashMap.put(1,"hello"); hashMap.put(2,"hello2"); hashMap.forEach((key,value)->{ System.out.println(key+" == "+value); });*/ HashMap<Person, String> map = new HashMap<Person, String>(); map.put(new Person("keafmd"), "6666"); map.put(new Person("keafod"), "8888"); map.put(new Person("keafod"), "9999"); // 这样就会覆盖掉8888 System.out.println(map.toString()); System.out.println("==============="); System.out.println(map.get((new Person("keafmd")))); System.out.println(map.get((new Person("keafod")))); System.out.println("==============="); System.out.println(new String("keafmd").hashCode()); System.out.println("keafmd".hashCode()); System.out.println(map.get("keafmd")); System.out.println("==============="); map.forEach((key, value) -> { System.out.println(key.toString() + ".hashCode() = " + key.hashCode()); System.out.println(key + ".value = " + value); }); } } class Person { private String name; Person(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) return false; Person person = (Person) obj; if (name != null ? !name.equals(person.name) : person.name != null) return false; return true; } @Override public int hashCode() { int result = 17; return 31 * result + name.hashCode(); // 这样写的话,字符串"keafmd" 和 new Person("keafmd") 的哈希值就是一样的, // return name != null ? name.hashCode() : 0; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } }
运行效果
{Person{name='keafod'}=9999, Person{name='keafmd'}=6666} =============== 6666 9999 =============== -1135381290 -1135381290 null =============== Person{name='keafod'}.hashCode() = -1135380701 Person{name='keafod'}.value = 9999 Person{name='keafmd'}.hashCode() = -1135380763 Person{name='keafmd'}.value = 6666 Process finished with exit code 0
总结
我们想要将自定义的类作为HashMap的key我们必须重写equals()和hashCode()方法,这样才能给每个作为key的对象一个唯一的hashcode值,这样就可以成功的使用自定义的类作为HashMap的key。
以上就是使用自定义的类作为HashMap的key的全部内容。