讲解在java中equals函数的定义、用法利用
2012-12-21 16:11
141 查看
equals函数在基类object中已经定义,源码如下
public boolean equals(Object obj) {
return (this == obj);
}
从源码中可以看出默认的equals()方法与"=="是一致的,都是比较的对象的引用,而非对象值(这里与我们常识中equals()用于对象的比较是相饽的,原因是java中的大多数类都重写了equals()方法,下面已String类举例,String类equals()方法源码如下:)
/** 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]
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;
}
String类的equals()非常简单,只是将String类转换为字符数组,逐位比较。
综上,使用equals()方法我们应当注意:
1. 如何equals()应用的是自定义对象,你一定要在自定义类中重写系统的equals()方法。
2. 小知识,大麻烦。
本文出自 “网络侠客” 博客,转载请与作者联系!
public boolean equals(Object obj) {
return (this == obj);
}
从源码中可以看出默认的equals()方法与"=="是一致的,都是比较的对象的引用,而非对象值(这里与我们常识中equals()用于对象的比较是相饽的,原因是java中的大多数类都重写了equals()方法,下面已String类举例,String类equals()方法源码如下:)
/** 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]
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;
}
String类的equals()非常简单,只是将String类转换为字符数组,逐位比较。
综上,使用equals()方法我们应当注意:
1. 如何equals()应用的是自定义对象,你一定要在自定义类中重写系统的equals()方法。
2. 小知识,大麻烦。
本文出自 “网络侠客” 博客,转载请与作者联系!
相关文章推荐
- 详细讲解如何利用Java实现组合式解析器?
- Java数据结构之有效队列定义与用法示例
- Java Calendar 的用法讲解
- Java EL 详细用法讲解
- 举例讲解Java的JSON类库GSON的基本用法
- Java入门系列:实例讲解ArrayList用法
- JAVA数组的定义及用法
- Java适配器模式定义与用法示例
- JAVA数组的定义及用法
- JAVA数组的定义及用法
- Java EL 详细用法讲解
- java的AbstractAction类用法示例(利用java的AbstractAction处理事件)
- Java多态性定义与用法实例详解
- JAVA数组的定义及用法
- 在Java中使用下划线分隔数的字面值的用法讲解
- JAVA数组的定义及用法
- Java设计模式之策略模式定义与用法详解
- 【JAVA】java中CyclicBarrier的用法,实例讲解
- Java的类路径讲解以及参数-cp的用法
- JAVA数组的定义及用法