JAVA的EQUAL和==解析


概述

本文主要解析JAVA中equal和==的区别和理解。

Equal

在Object类当中,而Object是所有类的父类,包含在jdk里面,但并不适合绝大多数场景,通常需要重写.

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


    public boolean equals(Object obj) {
        return obj instanceof Date && getTime() == ((Date) obj).getTime();//date 类重写的equals方法
    }

    public boolean equals(Object anObject) { //String 类重写的equals方法
            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;
    }

equals的作用

用于判断两个变量是否是对同一个对象的引用,即堆中的内容是否相同,返回值为布尔类型。
从String的重写代码中可以看出,String类型比较不同对象内容是否相同,应该用equals.
因为==用于比较引用类型和比较基本数据类型时具有不同的功能.

String作为一个对象来使用

例一:对象不同,内容相同,”==”返回false,equals返回true

    String s1 = new String("deep");
    String s2 = new String("deep");

    System.out.println(s1==s2);            //false cuz the object is not same.
    System.out.println(s1.equals(s2));     //true  cuz String overwrite the equals method.

例二:同一对象,”==”和equals结果相同

    String s1 = new String("deep");
    String s2 = s1;

    System.out.println(s1==s2);            //true cuz the object is same .
    System.out.println(s1.equals(s2));     //true cuz the value is same .

String作为一个基本类型来使用

例三:如果值不相同,对象就不相同,所以”==” 和equals结果一样

    String s1 = "deep";
    String s2 = "deep";// if the value is different ,then the results are both false.

    System.out.println(s1==s2);            //true cuz the basic type == compare the value of object, and the value is same.
    System.out.println(s1.equals(s2));     //true cuz the value is same

String对象的创建过程

如果String缓冲池内不存在与其指定值相同的String对象,那么此时虚拟机将为此创建新的String对象,并存放在String缓冲池内。
如果String缓冲池内存在与其指定值相同的String对象,那么此时虚拟机将不为此创建新的String对象,而直接返回已存在的String对象的引用。

总结

equals和==在基础类型和对象的比较是不一样的,对象的==比较的是引用地址是否一样,而equals则要更具不同的对象是否从写equals方法来判定.

一盏灯, 一片昏黄; 一简书, 一杯淡茶。 守着那一份淡定, 品读属于自己的寂寞。 保持淡定, 才能欣赏到最美丽的风景! 保持淡定, 人生从此不再寂寞。



   Reprint policy


《JAVA的EQUAL和==解析》 by jackromer is licensed under a Creative Commons Attribution 4.0 International License
 Previous
JAVA关键字解读 JAVA关键字解读
概述 本文主要介绍JAVA的一些比较难以理解的关键字和用法 protected 关键字protected定义 顾明思议,因为受保护,但是保护的范围是有限的,可以保护所处的包,子类和自己.限制了使用范围.如果希望超类中的某些方法允许被子类
2019-08-27
Next 
DOCKER镜像启动报no such file or directory问题 DOCKER镜像启动报no such file or directory问题
概述 在通过dockerfile搭建docker镜像,启动镜像时常常会报no such file or directory提示,今天说明一下异常产生的原因。 原因分析 原因大概分为两类,第一类确实无该文件,第二类文件编码问题 1.文件
2019-08-27
  目录