zoukankan      html  css  js  c++  java
  • java中equals和==的使用

    ==可以用来比较基本数据类型和引用数据类型,在进行基本数据类型的比较时,比较的具体的值,进行引用数据类型比较,比较的是引用指向对象在内存中的地址,但是String进行比较需要注意

    package cn.yqg.day1;
    
    public class B {
       public static void main(String[] args) {
        String a="123";
        String b="123";
        String c=new String("123");
        System.out.println(a==b);
        System.out.println(a==c);
    }
    }

    结果为true,false

    因为String直接赋值,值会存放在常量池中。

    但是使用equals进行比较,比较的是对象内存中的内容

    package cn.yqg.day1;
    
    public class B {
       public static void main(String[] args) {
        String a="123";
        String b="123";
        String c=new String("123");
        System.out.println(a==b);
        System.out.println(a==c);
    }
    }

    结果为true;

    为什么会这样?我们可以去看看Object类中如何定义的equals方法。

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

    观察代码,我们发现object中的equals比较的是对象的引用,即对象的内存地址。那么为什么String比较的是对象内存的内容哪?我们去看看String类中有没有重写Object的equals方法。

    public boolean equals(Object anObject) {
            if (this == anObject) {
                return true;
            }
            if (anObject instanceof String) {
                String anotherString = (String)anObject;
                int n = value.length;
                if (n == anotherString.value.length) {
                    char v1[] = value;
                    char v2[] = anotherString.value;
                    int i = 0;
                    while (n-- != 0) {
                        if (v1[i] != v2[i])
                            return false;
                        i++;
                    }
                    return true;
                }
            }
            return false;
        }

    我们发现String类重写了equals方法,比较的内容是对象内存里的内容,即字符串是否相同。

    ----------------------------------------------------------------------------------------------------------------------

    注意equals不能用于基本数据类型的比较。

    如果没有对equals方法进行重写,比较的就是对象内存地址,如果重写,比较内容自定义。

  • 相关阅读:
    最常见VC++编译错误信息集合
    网站运营最全总结
    KdPrint/DbgPrint and UNICODE_STRING/ANSI_STRING
    poj 2155 matrix
    【hdu2955】 Robberies 01背包
    【hdu4570】Multi-bit Trie 区间DP
    2014 SCAU_ACM 暑期集训
    qpython 读入数据问题: EOF error with input / raw_input
    【转】Python version 2.7 required, which was not found in the registry
    华农正方系统 登录地址
  • 原文地址:https://www.cnblogs.com/zzuli/p/9319398.html
Copyright © 2011-2022 走看看