java - 哪个更快:int比较与对象比较
问题描述
在 JAVA 中,我将 id numbers(int) 分配给我的对象。我想比较给定的对象是否是预期的对象。
我应该使用哪个?哪个更快?
if(civ!=this)
或者
if(civ.id!=id)
编辑:
额外的信息:
Class Civ {
int id;
public Civ(int i){
id = i;
}
public boolean checkIfOther(Civ civ){
这个:
return (civ.id !=id);
或这个:
return(civ !=this);
-
}
}
解决方案
civ != this
比 . (稍微几乎可以肯定地)快civ.id != id
。但是,请注意,两者只有在与共指civ
时才相同。看这个例子:this
String a = new String("hello")
String b = a;
a == b // true
String c = new String("hello")
a == c // false!
如果您是,例如civ
从数据库加载,或从用户输入构建它,或以任何其他方式创建它,而不是直接分配this
(反之亦然),第一种方法将失败,因为它们将是两个不同的 - 即使可能相等 - 对象。如果不确定,请使用id
以确保安全。
推荐阅读
- excel - 复制和插入具有系列增加的形状
- c# - 我们如何在没有执行查询的情况下读取 SharePoint 文件流?
- python - 尽管我尝试了任何解决方案,pydub 都找不到 ffprobe
- python-3.x - Matplotlib doucmentation 示例代码在axis.plot 上给出属性错误
- c++ - C++ 中 operator= 的奇怪行为
- ios - 在 GraphQL 中编辑类时的正确工作流程
- postgresql - 如何在 Spring Boot 和 Postgres 中将 XY 插入几何?
- pandas - 计算 DataFrame 中重复出现的次数
- html - HTML 输入元素仅在 Iphone 上未按预期显示
- windows - 在 Admin Cmd (Windows Cmd) 中找不到启动时的子驱动器(已修复)