import java.util.HashMap; public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub Person person1 = new Person(); Person person2 = new Person(); person1.name = "furong"; person1.age = 12; person2.name = "furong"; person2.age = 12; HashMap<Person, String> map = new HashMap<Person, String>(); map.put(person1, "person1"); System.out.println(map.get(person2)); System.out.println(person1); } }
运行结果
null Person.Person@15db9742
复写hashCode和toString
package Person; public class Person { String name; int age; public Person() { // TODO Auto-generated constructor stub } public int hashCode() { int result = 17; result = 31 * result * age; result = 31 * result * name.hashCode(); return result; } public String toString() { return "name: " + name + ", age: " + age; } }
运行结果
person1
name: furong, age: 12