java equals函数详解

来源:互联网 发布:索尼网络电视怎么用 编辑:程序博客网 时间:2024/06/04 19:52
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;

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. 小知识,大麻烦。


原创粉丝点击