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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步