equals(Object obj)有什么作用? [英] What does equals(Object obj) do?
问题描述
我经常在不同的地方找到一个equals方法.它实际上是做什么的?在每个班级都必须有这个重要吗?
I´ve often found an equals method in different places. What does it actually do? Is it important that we have to have this in every class?
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
if (obj == null)
{
return false;
}
if (obj instanceof Contact)
{
Contact other = (Contact)obj;
return other.getFirstName().equals(getFirstName()) &&
other.getLastName().equals(getLastName()) &&
other.getHomePhone().equals(getHomePhone()) &&
other.getCellPhone().equals(getCellPhone());
}
else
{
return false;
}
}
推荐答案
它重新定义了对象的相等性".
It redefines "equality" of objects.
默认情况下(在java.lang.Object
中定义),仅当一个对象是同一实例时,该对象才等于另一个对象.但是当您覆盖它时,您可以提供自定义相等逻辑.
By default (defined in java.lang.Object
), an object is equal to another object only if it is the same instance. But you can provide custom equality logic when you override it.
例如,java.lang.String
通过比较内部字符数组来定义相等性.这就是为什么:
For example, java.lang.String
defines equality by comparing the internal character array. That's why:
String a = new String("a"); //but don't use that in programs, use simply: = "a"
String b = new String("a");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
即使您可能不需要测试是否相等,使用的类也可以.例如,List.contains(..)
和List.indexOf(..)
的实现使用.equals(..)
.
Even though you may not need to test for equality like that, classes that you use do. For example implementations of List.contains(..)
and List.indexOf(..)
use .equals(..)
.
检查 equals(..)
方法所需的确切合同的javadoc .
Check the javadoc for the exact contract required by the equals(..)
method.
在许多情况下,覆盖equals(..)
时,您还必须覆盖hashCode()
(使用相同的字段).这也在javadoc中指定.
In many cases when overriding equals(..)
you also have to override hashCode()
(using the same fields). That's also specified in the javadoc.
这篇关于equals(Object obj)有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!