equals()与==的区别。

Java 发表评论


首先了解基础类型与引用类型

值类型直接存储在栈中(基本类型)

引用类型的变量在栈存储值在堆中创建变量的引用

equals()与==的区别

  1. “==”在Java语言中是一个二元操作符,equals()为Object类里面定义的一个方法.

  2. “==”比较的是基础类型的是否相等.equals()用于比较两个对象的引用否相等,String类则覆盖了equals(),在String中equals()的作用是比较引用地址的值所有字符是否相等。覆盖方法如下:

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span>(Object anObject) {
            <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span> == anObject) {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
            }
            <span class="hljs-keyword">if</span> (anObject <span class="hljs-keyword">instanceof</span> String) {
                String anotherString = (String)anObject;
                <span class="hljs-keyword">int</span> n = count;
                <span class="hljs-keyword">if</span> (n == anotherString.count) {
                    <span class="hljs-keyword">char</span> v1[] = value;
                    <span class="hljs-keyword">char</span> v2[] = anotherString.value;
                    <span class="hljs-keyword">int</span> i = offset;
                    <span class="hljs-keyword">int</span> j = anotherString.offset;
                    <span class="hljs-keyword">while</span> (n-- != <span class="hljs-number">0</span>) {
                        <span class="hljs-keyword">if</span> (v1[i++] != v2[j++])
                            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
                    }
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
                }
            }
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
        }

发表回复

您的电子邮箱地址不会被公开。

昵称 *