我想澄清一下我的理解是否正确:
==是一个引用比较,即两个对象都指向相同的内存位置 .equals()计算为对象中值的比较
我想澄清一下我的理解是否正确:
==是一个引用比较,即两个对象都指向相同的内存位置 .equals()计算为对象中值的比较
当前回答
对于String类:
equals()方法比较String实例中的“值”(在堆上),而不考虑两个对象引用是否引用同一个String实例。如果任意两个String类型的对象引用引用同一个String实例,那就太好了!如果两个对象引用引用两个不同的String实例..这没什么区别。它是每个被比较的String实例中的“值”(即:字符数组的内容)。
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
就像任何解释一样,让它深入人心。
我希望这能让你清楚一点。
其他回答
简单地说,==检查两个对象是否指向相同的内存位置,而.equals()计算对象中值的比较。
==操作符总是比较引用。但是如果
equals()方法
这取决于我们的实现,如果我们是overridden equals method,而不是在overridden method中给出的实现的基础上比较对象。
class A
{
int id;
String str;
public A(int id,String str)
{
this.id=id;
this.str=str;
}
public static void main(String arg[])
{
A obj=new A(101,"sam");
A obj1=new A(101,"sam");
obj.equals(obj1)//fasle
obj==obj1 // fasle
}
}
在上面的代码中,obj和obj1对象包含相同的数据,但引用不相同,所以=也返回false和==。 但如果我们重写equals method than
class A
{
int id;
String str;
public A(int id,String str)
{
this.id=id;
this.str=str;
}
public boolean equals(Object obj)
{
A a1=(A)obj;
return this.id==a1.id;
}
public static void main(String arg[])
{
A obj=new A(101,"sam");
A obj1=new A(101,"sam");
obj.equals(obj1)//true
obj==obj1 // fasle
}
}
知道签出它将返回true和false对于相同的情况,只是我们覆盖了
等于方法。
它以对象的内容(id)为基础对对象进行比较
但= =
还比较对象的引用。
==运算符测试两个变量是否有相同的引用 (又名指向内存地址的指针)。
String foo = new String("abc");
String bar = new String("abc");
if(foo==bar)
// False (The objects are not the same)
bar = foo;
if(foo==bar)
// True (Now the objects are the same)
而equals()方法测试两个变量是否引用对象 具有相同的状态(值)。
String foo = new String("abc");
String bar = new String("abc");
if(foo.equals(bar))
// True (The objects are identical but not same)
欢呼:-)
它是恒等和等价的区别。
A == b意味着A和b是相同的,也就是说,它们是内存中相同对象的符号。
A.equals (b)意味着它们是等价的,它们是在某种意义上具有相同值的对象的符号——尽管这些对象可能在内存中占据不同的位置。
注意,对于等价性,如何评估和比较对象的问题开始发挥作用——复杂的对象可能被认为是等效的,即使它们的一些内容不同。有了身份,就没有这样的问题了。
要在自定义类中使用equals函数,您必须重写equals函数(以及其他函数)。
equals方法比较对象。
==二进制操作符比较内存地址。