HELLO WORLD--一起加油(🍺)!|

kingwzun

园龄:3年6个月粉丝:111关注:0

JAVA常用方法及其常用重写

.equals

判断两个对象的是否完全相同(地址是否相同)
未重写时和“==”一样
代码:

System.out.println(p1.equals(p2));

标准重写:

public boolean equals(Object obj) {
if (this == obj)//是否是同一地址
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())//是否是同一类型
return false;
Product other = (Product) obj;//上转型对象强制转化为实际子类
if (Double.doubleToLongBits(count) != Double.doubleToLongBits(other.count))//高精度对比double类型
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

重写:

public class Product implements Comparable<Product> {
String id;
String name;
int count;
public Product(String a, String b, int c) {
id = a;
name = b;
count = c;
}
public boolean equals(Product other) {
if (this.getClass() != other.getClass())
return false;
else if (!this.id.equals(other.id))
//等于(this.id.equals(other.id)==false)
return false;
else if (!this.name.equals(other.name))
//等于(this.name.equals(other.name)==false)
return false;
else if (this.count != other.count)
return false;
else
return true;
}
}

本文作者:kingwzun

本文链接:https://www.cnblogs.com/kingwz/p/15470599.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   kingwzun  阅读(59)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起