java - 用 '==' 比较两个对象实际上有什么作用?
问题描述
好久没来这里发帖了,如有错误请见谅。
我正在从 MOOC fi 学习 java。我目前在第 5 周,这里提到要比较两个对象,您必须执行以下操作:
public class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the type of the compared object is not SimpleDate, the objects are not equal
if (!(compared instanceof SimpleDate)) {
return false;
}
// convert the Object type compared object
// into a SimpleDate type object called comparedSimpleDate
SimpleDate comparedSimpleDate = (SimpleDate) compared;
// if the values of the object variables are the same, the objects are equal
if (this.day == comparedSimpleDate.day &&
this.month == comparedSimpleDate.month &&
this.year == comparedSimpleDate.year) {
return true;
}
// otherwise the objects are not equal
return false;
}
@Override
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
所以我很困惑,什么是:
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
上面的代码究竟是做什么的?位于同一位置是什么意思?
仅检查对象是否属于特定类类型然后比较它们的实例变量以查看它们是否相等不是更好吗?
解决方案
this
并且compared
在您的情况下都是对对象的引用。
在 Java 中,每个对象都驻留在特定的内存位置。两个不同的对象不能同时具有相同的内存位置。
相等运算符或“==”根据它们是否位于相同的内存地址来比较两个对象。所以“==”操作符只有当它比较的两个对象引用代表完全相同的对象时才会返回true,否则“==”将返回false。
另请注意,==
运算符equals
与类上的方法不同。
推荐阅读
- php - jwt-auth 未安装 laravel (6.0.3)
- osgi - AEM 中的服务真的是单例的吗?
- python - 如何从本地驱动器将文件上传到协作?我对编码完全陌生
- azure - 未从 Azure 数据工厂中的 Azure 表存储源加载所有列
- javascript - 迭代中的 StaleElementReferenceError
- javascript - 我想使用 js 和 ajax 调用将来自 DB 的多个复选框数据发送到 spring 控制器
- webhooks - 如何使用 HMACSHA256 python 3 验证 Xero webhook 有效负载
- exception - System.IO.FileLoadException:在 RichEditBox 文档中引发异常
- c# - 如何在 Azure Devops 中使用服务帐户模拟用户
- json - 使用 jq 命令行处理器时 JSON 格式的问题