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方法我的重写了啊,谢谢帮看看!

解决方案 »

  1.   


    public boolean equlas(Object o){
    我还没学那么多,代码看不懂,不知是不是equlas->改成equals?
      

  2.   

    @Override public boolean equals(Object o){
       ...
    }
      

  3.   

    本来Object的hashCode是调用系统的   但是你改变了 可能是这点导致map不能键值对应的吧  map对比也是用hashCode来的说
      

  4.   

    1L眼神不错
    equlas 改成 equals,注意单词拼写
      

  5.   

    public boolean equlas(Object o)方法名写错了,额,equals
      

  6.   

    恩。是不是你equal写错了!试试看那
      

  7.   

    this.name==t.name应该是this.name.equals(t.name)
      

  8.   

    public boolean equlas(Object o){
    名字写错啦 ,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) ;
      

  9.   

    加上 @Override ,这种错误编译都通不过
      

  10.   

    hashmap放的是键值对,你这里map里面只放了map.put(tu,"zhangsan");,tu这一个对象!注意他是引用类型的数据。。然而你在System.out.println( map.containsKey(new Tu("zhangsan",2)));判断的是map里面的键里面有没有new Tu("zhangsan",2)!这个对象他不等于tu,他们指向的完全是两个不同的对象。。
    所以map里面没有new Tu("zhangsan",2),只有一个对象tu!所以是false
      

  11.   

    亲~注意引用类型数据的特点!String str1 = new String("haha");String str2 = new String("haha");str1与str2指向不同对象
      

  12.   


    先抛开那个equals的拼写错误不谈哈,当然那个是肯定要改过来的啦,不然就没有起到覆写的作用了哇^_^
    这边LZ已经覆写了hashcode和equals方法了,就是为了只要表面上看着是同一个元素的就是存在的,而不会因为重新new了一个对象就不算那个同名同形式的key的存在。这边本来key就是tu类型的呀,所以这样完全可以的~
      

  13.   


    确实是拼写错了,这种错误最难查,建议使用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;
    } }
      

  14.   

    不过建议最后这样写:
    public int hashCode(){ return this.name.hashCode();
    }
    避开自己写hashcode,而又达到目的。。
      

  15.   

    单词写错了 另外字符串的比较应该用equals 我也写过楼主的程序 犯过相同的错误
      

  16.   

    学习了!看看java的文档也许会有帮助,你自己就知道那个地方错了。