标签:
classUser{
String name;
int age;
publicUser(){
}
publicUser(String name,int age){
this.name = name;
this.age = age;
}
public boolean equals(Object obj){
if(this== obj){
returntrue;
}
//instanceof作用:判断前面的对象是不是后面对象的类型
boolean b = obj instanceof User;
if(b){
//obj向下转型为User对象
User u =(User)obj;
if(this.age == u.age &&this.name.equals(u.name)){
returntrue;
}
else{
returnfalse;
}
}
else{
returnfalse;
}
}
//复写User的hashCode
publicint hashCode(){
int result =17;
result =31* result + age;
result =31* result +name.hashCode();
return result;
}
}
import java.util.*;
publicclassTest{
publicstaticvoid main(String args []){
User u =newUser("zhangsan",12);
HashMap<User,String>map=newHashMap<User,String>();
map.put(u,"abc");
//通过计算键的hashcode来判断有没有存在相应的值
String s =map.get(newUser("zhangsan",12));
System.out.println(s);
}
}
classUser{
String name;
int age;
publicUser(){
}
publicUser(String name,int age){
this.name = name;
this.age = age;
}
public boolean equals(Object obj){
if(this== obj){
returntrue;
}
//instanceof作用:判断前面的对象是不是后面对象的类型
boolean b = obj instanceof User;
if(b){
//obj向下转型为User对象
User u =(User)obj;
if(this.age == u.age &&this.name.equals(u.name)){
returntrue;
}
else{
returnfalse;
}
}
else{
returnfalse;
}
}
//复写User的hashCode
publicint hashCode(){
int result =17;
result =31* result + age;
result =31* result +name.hashCode();
return result;
}
publicString toString(){
String result ="age:"+age+","+"name:"+ name;
return result;
}
}
import java.util.*;
publicclassTest{
publicstaticvoid main(String args []){
User u =newUser("zhangsan",12);
System.out.println(u);
}
}
标签:
原文地址:http://www.cnblogs.com/arroneve/p/5815481.html