java hashcode重载_初涉继承,关于java中重写hashcode()方法的问题

public class Idiophones extends MusicalInstrument{

public Idiophones(String origin, String hsNumber, String imageUrl,String classificationName){

this.origin = origin;

this.hsNumber = hsNumber;

this.imageUrl = imageUrl;

this.classificationName = classificationName;

}

public String getOrigin(){

return origin;

}

public String getHsNumber(){

return hsNumber;

}

public String getImageUrl(){

return imageUrl;

}

public String getClassificationName(){

return classificationName;

}

@Override public boolean equals(Object o) {

if (this == o) {

return true;

}

if (o == null || getClass() != o.getClass()) {

return false;

}

Idiophones idiophones = (Idiophones) o;

if (idiophones.origin.compareTo(origin) != 0) {

return false;

}

else if (idiophones.hsNumber.compareTo(hsNumber) != 0){

return false;

}

else if(idiophones.imageUrl.compareTo(imageUrl) != 0){

return false;

}

else{

return (idiophones.classificationName.compareTo(classificationName) == 0);

}

}

代码如上。

初涉继承,自己重写了一个.equals()方法,但是面对重写hashcode()方法时产生了疑惑,看到一个使用>>>32位移的解法,如下

public class Gps {

private final double latitude;

private final double longitude;

public Gps(double latitude, double longitude) {

this.latitude = latitude;

this.longitude = longitude;

}

public double getLatitude() {

return latitude;

}

public double getLongitude() {

return longitude;

}

@Override public boolean equals(Object o) {

if (this == o) {

return true;

}

if (o == null || getClass() != o.getClass()) {

return false;

}

Gps gps = (Gps) o;

if (Double.compare(gps.latitude, latitude) != 0) {

return false;

}

return (Double.compare(gps.longitude, longitude) == 0);

}

@Override public int hashCode() {

int result;

long temp;

temp = Double.doubleToLongBits(latitude);

result = (int) (temp ^ (temp >>> 32));

temp = Double.doubleToLongBits(longitude);

return 31 * result + (int) (temp ^ (temp >>> 32));

}

}

hashcode究竟其值范围为多少,二进制是多少位?如何理解这段代码?(latitude和longtitude都是64bit的2进制序列,感觉这个解法比较取巧?并非是一个比较通用的解法)?

另外希望各位前辈能指教一下Idiophones这个class的hashcode写法,能有完整代码解释一下就最好了

还希望请各位前辈验证一下我的Idiophones中的 .equals()方法重写的是否正确,谢谢!

P.S.哪位前辈能按照代码1的内容写一下这里hashcode()方法究竟是如何重写的啊,感觉还是不知道自己理解的对不对

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值