Comparable,hashcode和equals

本文详细解析了如何正确重写Java中的hashcode和equals方法,确保在使用HashSet等集合类时能够准确判断对象的相等性,避免重复元素的加入。通过具体的People类示例,演示了正确的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说到hashcode和equals不的不想到集合类的SET,set能清楚重复的东西。

假如:

public class People {
     private String fistName;
     private String lastName;
     People(String fname,String lname){
       this.fistName = fname;
      this.lastName = lname;
   }

}

你在hashSet时想根据姓名相同的为条件来去掉重复的,重写OBJECT类的hashcode和equals一定要写对了。

public class People {
 private String fistName;
 private String lastName;
 People(String fname,String lname){
  this.fistName = fname;
  this.lastName = lname;
 }

public int hashCode(){
  return this.fistName.hashCode()*this.lastName.hashCode();
 }
 public boolean equals(Object o){  
  if( o instanceof People){
   People p = (People)o;
   if(this.fistName.equals(p.fistName)&&this.lastName.equals(p.lastName)){
    return true;
   }else{
    return false;
   }
  }else{
   return false;
  }  
 }

}

当你要对一个类做比较的时候你的实现接口compareable,实现方法public int compareTo(People o)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值