equals函数在基类object中已经定义,源码如下
实现代码如下:

public boolean equals(Object obj) {
return (this == obj);
}

从源码中可以看出默认的equals()方法与“==”是一致的,都是比较的对象的引用,而非对象值(这里与我们常识中equals()用于对象的比较是相饽的,原因是java中的大多数类都重写了equals()方法,下面已String类举例,String类equals()方法源码如下:)
[java]
实现代码如下:

/** The value is used for character storage. */
private final char value[];

/** The offset is the first index of the storage that is used. */
private final int offset;

/** The count is the number of characters in the String. */
private final int count;

[java] view plaincopyprint?
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;
}
} //www.software8.co
return false;
}

String类的equals()非常简单,只是将String类转换为字符数组,逐位比较。
综上,使用equals()方法我们应当注意:
1. 如何equals()应用的是自定义对象,你一定要在自定义类中重写系统的equals()方法。
2. 小知识,大麻烦。

以上就是【java equals函数用法详解】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论