package zhang;import java.util.HashMap;
import java.util.Map;public class hashcode {
public static void main(String[] args) {
Map<Tu,String> map=new HashMap<Tu,String>();
Tu tu=new Tu("zhangsan",2);
map.put(tu,"zhangsan");
System.out.println( map.containsKey(new Tu("zhangsan",2)));
}
}
class Tu{
String name;
int id;
public Tu(String name, int id){
this.name=name;
this.id=id;
}
public boolean equlas(Object o){
if(o instanceof Tu){
Tu t=(Tu)o;
return this.name==t.name&&this.id==t.id;
}
return true;
}
public int hashCode(){
return this.id*63223;
}
}为什么返回的是false,equals和hashcode方法我的重写了啊,谢谢帮看看!
import java.util.Map;public class hashcode {
public static void main(String[] args) {
Map<Tu,String> map=new HashMap<Tu,String>();
Tu tu=new Tu("zhangsan",2);
map.put(tu,"zhangsan");
System.out.println( map.containsKey(new Tu("zhangsan",2)));
}
}
class Tu{
String name;
int id;
public Tu(String name, int id){
this.name=name;
this.id=id;
}
public boolean equlas(Object o){
if(o instanceof Tu){
Tu t=(Tu)o;
return this.name==t.name&&this.id==t.id;
}
return true;
}
public int hashCode(){
return this.id*63223;
}
}为什么返回的是false,equals和hashcode方法我的重写了啊,谢谢帮看看!
public boolean equlas(Object o){
我还没学那么多,代码看不懂,不知是不是equlas->改成equals?
...
}
equlas 改成 equals,注意单词拼写
名字写错啦 ,equals
public boolean equlas(Object o){
if(o instanceof Tu){Tu t=(Tu)o;
return this.name==t.name&&this.id==t.id;
}
name 为字符串String ,比较相等 应该用 this.name.equals(t.name) ;
所以map里面没有new Tu("zhangsan",2),只有一个对象tu!所以是false
先抛开那个equals的拼写错误不谈哈,当然那个是肯定要改过来的啦,不然就没有起到覆写的作用了哇^_^
这边LZ已经覆写了hashcode和equals方法了,就是为了只要表面上看着是同一个元素的就是存在的,而不会因为重新new了一个对象就不算那个同名同形式的key的存在。这边本来key就是tu类型的呀,所以这样完全可以的~
确实是拼写错了,这种错误最难查,建议使用eclipse的工具自动生成代码。
不过java真的有关键字“Override”吗?我记得C#有。
public class hashcode extends Object{
public static void main(String[] args) {
Map<Tu,String> map=new HashMap<Tu,String>();
Tu tu=new Tu("zhangsan",2);
map.put(tu,"zhangsan");
System.out.println( map.containsKey(new Tu("zhangsan",2))); }
}
class Tu{
String name;
int id;
public Tu(String name, int id){
this.name=name;
this.id=id;
}
public boolean equals(Object o){
if(o instanceof Tu){ Tu t=(Tu)o;
return this.name==t.name&&this.id==t.id;
}
return true;
}
public int hashCode(){ return this.id*63223;
} }
public int hashCode(){ return this.name.hashCode();
}
避开自己写hashcode,而又达到目的。。