美文网首页
Object类中的hashCode(),toString(),e

Object类中的hashCode(),toString(),e

作者: 安安静静写代码 | 来源:发表于2017-08-03 10:59 被阅读17次

hashCode():返回对象的哈希值(散列函数将十六进制地址进行特定运算转成int类型)
toString() :返回对象的包名+类名+@地址,String类重写了toString()输出的是String类的属性值
快捷键source->Generate toString() 能够重写当前类的toString方法返回当前类的属性值
重写该方法后打印该对象系统会自动调用toString()


public class Father {
    
     private  int id;
     public Father()
     {
         
     }
     
    public Father(int id) {     
        this.id = id;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Father [id=" + id + "]";
    }
    public void show(Father father)
    {
        
        System.out.println(father);         //打印father,系统会默认调用重写之后的方法
        System.out.println(this.toString());//功能与上句相同
        
    }
    
}

equals(): 比较的是内存的地址值(但是String类重写了equals(),比较的是内容)

public class Test {

  public static void main(String[] args) {
      
       String str1 = new String("123");
       String str2 = "123";
       System.out.println(str1.equals(str2));//true String类重写了equals方
法 
       String str3  = str1;
       System.out.println(str1.equals(str3));//true 
      
       son s1 = new son(3);
       son s2 = new son(3);
       System.out.println(s1.equals(s2));//输出flase
       //重写equals()后
       System.out.println(s1.equals(s2));//输出true 
  }
}

以下是son类


public class son {
       
      
      private int id;
      public son(int id)
      {
          this.id = id;
      } 
      public boolean equals(son s) //重写equals()
      {
          if(this.id==s.id)
              return true; 
          else
              return false;
      }
}

相关文章

网友评论

      本文标题:Object类中的hashCode(),toString(),e

      本文链接:https://www.haomeiwen.com/subject/qmvulxtx.html