java中equals与==的区别,结合源码分析

java中equals与==的区别

首先看一下,jvm是如何分配内存的,jvm主要包含:堆区、栈区和方法区。
堆区:是共享的,主要存放的是引用对象本身和class信息(class操作指令),不存放基本类型和引用。
栈区:每个线程中都包含一个栈区,栈区与栈区之间不能共享,是私有的。
      栈区存放基本类型的变量和引用地址。
      栈区主要包含有:基本类型变量区、执行环境上下文和操作指令。
方法区:全局唯一的,存放所有的class和static变量,共享的。
基础类型的变量比较简单,这里不多说,直接说引用对象。上代码:
引用对象:
 
StudentPO
public class StudentPO {
    private String name ;
    private int age;
    private String gender;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {

        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }



}
测试方法:
public static void main(String[] args) {
    StudentPO stu = new StudentPO();
    stu.setName("aa");
    StudentPO stu1 = new StudentPO();
    stu1.setName("aa");
    System.out.println(stu==stu1);//false
    System.out.println(stu.equals(stu1));//false
}
/**
 * Indicates whether some other object is "equal to" this one.
 * <p>
 * The {@code equals} method implements an equivalence relation
 * on non-null object references:
 * <ul>
 * <li>It is <i>reflexive</i>: for any non-null reference value
 *     {@code x}, {@code x.equals(x)} should return
 *     {@code true}.
 * <li>It is <i>symmetric</i>: for any non-null reference values
 *     {@code x} and {@code y}, {@code x.equals(y)}
 *     should return {@code true} if and only if
 *     {@code y.equals(x)} returns {@code true}.
 * <li>It is <i>transitive</i>: for any non-null reference values
 *     {@code x}, {@code y}, and {@code z}, if
 *     {@code x.equals(y)} returns {@code true} and
 *     {@code y.equals(z)} returns {@code true}, then
 *     {@code x.equals(z)} should return {@code true}.
 * <li>It is <i>consistent</i>: for any non-null reference values
 *     {@code x} and {@code y}, multiple invocations of
 *     {@code x.equals(y)} consistently return {@code true}
 *     or consistently return {@code false}, provided no
 *     information used in {@code equals} comparisons on the
 *     objects is modified.
 * <li>For any non-null reference value {@code x},
 *     {@code x.equals(null)} should return {@code false}.
 * </ul>
 * <p>
 * The {@code equals} method for class {@code Object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * Note that it is generally necessary to override the {@code hashCode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashCode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @param   obj   the reference object with which to compare.
 * @return  {@code true} if this object is the same as the obj
 *          argument; {@code false} otherwise.
 * @see     #hashCode()
 * @see     java.util.HashMap
 */
public boolean equals(Object obj) {
    return (this == obj);
}

解析:因为所有的对象的父类都是object类型的,看了jdk的源码你就会知道,equals是和==效果一样的,直接比较的引用地址,而不是value值,因此我们在比较应用对象的时候要重写equals方法。我重写了equals方法后如下:
public class StudentPO {
    private String name ;
    private int age;
    private String gender;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {

        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
  //添加了重写equals方法
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof StudentPO) {
            return this.name == ((StudentPO)obj).name;
        }
        return false;
    }


}
测试结果:
public static void main(String[] args) {
    StudentPO stu = new StudentPO();
    stu.setName("aa");
    StudentPO stu1 = new StudentPO();
    stu1.setName("aa");
    System.out.println(stu==stu1);//false
    System.out.println(stu.equals(stu1));//true
}
那么有人会问了,为什么在Integer和String中,使用equals方法是可以的呢,先看看jdk源码。
Integer:
/**
 * Compares this object to the specified object.  The result is
 * {@code true} if and only if the argument is not
 * {@code null} and is an {@code Integer} object that
 * contains the same {@code int} value as this object.
 *
 * @param   obj   the object to compare with.
 * @return  {@code true} if the objects are the same;
 *          {@code false} otherwise.
 */
public boolean equals(Object obj) {
    if (obj instanceof Integer) {//如果类型一致,就会获取vaule值进行比较
        return value == ((Integer)obj).intValue();//
    }
    return false;
}
String:
	
/**
 * 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;
}
解析:
因为Integer和String中是重写了equals方法了的。
Integer源码中
	(a)直接判断类型相同的话,就判断value值。
String源码中
	(a)如果引用地址相同,地址中指向的值也肯定是相同的呀。
	(b)如果引用地址不相同,判断是不是同一个类型,类型相同的话,则逐一判断每个字符,每个字符相同的话,则该对象相同。
欢迎转载,如有问题,请多多指出。转载请注明出处。
http://blog.csdn.net/weixin_40372756/article/category/7386336

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值