java中的equals()与==_Java中的equals()与==

equals()是Object类的一个方法,而Object是所有类的父类,因此实际上所有类都会继承到equals()方法。

equals()方法在java.lang.Object中的说明为:

public boolean equals(obj)

Indicates whether some other object is "equal to" this one.

Theequalsmethod implements an equivalence relation:

It is reflexive: for any reference valuex,x.equals(x)should returntrue.

It is symmetric: for any reference valuesxandy,x.equals(y)should returntrueif and only ify.equals(x)returnstrue.

It is transitive: for any reference valuesx,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue.

It is consistent: for any reference valuesxandy, multiple invocations ofx.equals(y)consistently returntrueor consistently returnfalse, provided no information used inequalscomparisons on the object is modified.

For any non-null reference valuex,x.equals(null)should returnfalse.

Theequalsmethod for classObjectimplements the most discriminating possible equivalence relation on objects; that is, for any reference valuesxandy, this method returnstrueif and only ifxandyrefer to the same object (x==yhas the valuetrue).

其源码为:

public boolean equalss(Object obj) {

return (this = = obj);

}

由以上的注释可知Object中的equals()方法和 = =操作符是完成了相同的比较功能,都是对对象的引用进行了比较。

String类的equals()方法又是如何实现的呢?源代码:

public boolean equals(Object anObject) {

if (this == anObject) {

return true;

}

if (anObject instanceof String) {

String anotherString = (String)anObject;

int n = count;

if (n == anotherString.count) {

char v1[] = value;

char v2[] = anotherString.value;

int i = offset;

int j = anotherString.offset;

while (n-- != 0) {

if (v1[i ] != v2[j ])

return false;

}

return true;

}

}

return false;

}

说明为:

public boolean equals(anObject)

Compares this string to the specified object. The result istrueif and only if the argument is notnulland is aStringobject that represents the same sequence of characters as this object.

因此String中的equals()方法比较的是String对象中的内容,而不是它们的引用的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值