每天学会一点点(重写equals一定要重写hashcode)
package com.example.demo.javaError; import java.util.HashMap; /** * Created by yyy on 2019/01/24. */ public class MyTest { private static class Person{ int idCard; String name; public Person(int idCard, String name) { this.idCard = idCard; this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()){ return false; } Person person = (Person) o; //两个对象是否等值,通过idCard来确定 return this.idCard == person.idCard; } @Override public int hashCode() { int hash = 7; hash = 31*hash+idCard; // hash = 31*hash+name.hashCode(); return hash; } } public static void main(String []args){ HashMap<Person,String> map = new HashMap<Person, String>(); Person person = new Person(1234,"乔峰"); //put到hashmap中去 map.put(person,"天龙八部"); //get取出,从逻辑上讲应该能输出“天龙八部” System.out.println("结果:"+map.get(new Person(1234,"萧峰"))); } }
程序员的眼里,不止有代码和bug,还有诗与远方和妹子!!!