test equals

 

package test;

public class TestEqals {
 public static void main(String args[]){
  OverWrite first=new OverWrite(6);
  OverWrite second=new OverWrite(6);
  System.out.println(first.equals(second));
  System.out.println(first==second);
  NoOverWrite three=new NoOverWrite(6);
  NoOverWrite four=new NoOverWrite(6);
  System.out.println(three.equals(four));
  System.out.println(three==four);
 }
}

class OverWrite{
 private int number;
 OverWrite(int i){
  this.number=i;
 }
 
 public int hashCode(){
  return this.number;
 }
 
 public boolean equals(Object o){
  if(this.hashCode()==o.hashCode())
   return true;
  else{
   return true;
  }
 }
}

class NoOverWrite{
 private int number;
 NoOverWrite(int i){
  this.number=i;
 }
}

/**

*1.如果不重写hashCode和equal,那么用new运算符,新建的对象都会是不同的对象(String对象除外,因为他已经默认重写了)。

*2.如果不重写hashCode,则hashCode是jdk根据对象的地址或者字符串或者数字算出来的int类型的数值 public int hashCode()返回该对象的哈希码值。

*3.HashMap对象是根据其Key的hashCode来获取对应的Value。

  在重写父类的equals方法时,也重写hashcode方法,使相等的两个对象获取的HashCode也相等,这样当此对象做Map类中的Key时,两个equals为true的对象其获取的  value都是同一个,比较符合实际。
*4.hashTable就是根据对象,求出hashcode所谓的哈希码,然后在进行哈希函数,查找出键值。这就是hashtable的原理
**/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值