java中==和equals的区别是什么?

3 篇文章 0 订阅

== :它的作用是判断两个对象的地址是不是相等。即:判断两个对象是不是同一个对象(基本数据类型比较的是值,引用数据类型比较的是内存地址)。

equals() :它的作用也是判断两个对象是否相等。但它一般有两种使用情况:

  • 情况 1:类没有覆盖 equals() 方法。则通过 equals() 比较该类的两个对象时,等价于通过 ”==“ 比较这两个对象。
// Object类中的equals() 方法
public boolean equals(Object obj) {
    return (this == obj);
}
  • 情况 2:类覆盖了 equals() 方法。一般,我们都覆盖 equals() 方法来比较两个对象的内容是否相等;若他们的内容相等,则返回true(即,认为这两个对象相等)。
 /**
    *  String类中的equals() 方法,已覆盖,用于比较内容
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    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;
    }

举个例子:

public class test1 {
    public static void main(String[] args){
        String a = new String("ab"); // a为一个引用
        String b = new String("ab"); // b为另一个引用,对象的内容一样
        String aa = "ab"; // 放在常量池中
        String bb = "ab"; // 从常量池中查找
        if(aa == bb) // true
            System.out.println("aa==bb");
        if(a == b) // false,非同一对象
            System.out.println("a==b");
        if(a.equals(b)) // true
            System.out.println("aEQb");
        if(42 == 42.0) { // true
            System.out.println("true");
        }
    }
}

结果:

 

说明:

  • String 中的 equals 方法是被重写过的,因为 object 的 equals 方法是比较对象的内存地址,而 String 的 equals 方法比较的是对象的值。
  • 当创建 String 的类型的对象时,虚拟机会在常量池中查找有没有已经存在的值和要创建的值相同的对象,如果有就把它赋给当前引用。如果没有就在常量池汇总重新创建一个 String 对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值