Chinaunix首页 | 论坛 | 博客
  • 博客访问: 756566
  • 博文数量: 190
  • 博客积分: 2991
  • 博客等级: 少校
  • 技术积分: 2400
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-24 18:11
文章分类

全部博文(190)

文章存档

2015年(3)

2014年(1)

2013年(65)

2012年(121)

我的朋友

分类: Python/Ruby

2012-11-24 17:21:26

equals函数在基类object中已经定义,源码如下
 
public boolean equals(Object obj) {  
       return (this == obj);  
   }  
从源码中可以看出默认的equals()方法与“==”是一致的,都是比较的对象的引用,而非对象值(这里与我们常识中equals()用于对象的比较是相饽的,原因是java中的大多数类都重写了equals()方法,下面已String类举例,String类equals()方法源码如下:)
[java] view plaincopyprint?
/** 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;  
            }  
        }  //
        return false;  
    }  
String类的equals()非常简单,只是将String类转换为字符数组,逐位比较。
综上,使用equals()方法我们应当注意:
 1. 如何equals()应用的是自定义对象,你一定要在自定义类中重写系统的equals()方法。
 2. 小知识,大麻烦。
 原文:
阅读(771) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~