彻底弄懂Java中的equals()方法以及与"=="的区别

一、问题描述:

今天在用Java实现需求的时候,发现equals()和“==”的功能傻傻分不清,导致结果产生巨大的偏差。所以,我决定花费时间把equals()和“==”的功能彻底弄懂,前事不忘后事之师嘛,分享给大家,希望对大家理解equals()和“==”的功能有所帮助。

二、分析探索解决问题的方法:

1、Object 中的equals()方法:

(1)通过查找API,说明如下:

equals

public boolean equals(Object obj)指示其他某个对象是否与此对象“相等”。
equals 方法在非空对象引用上实现相等关系:

自反性:对于任何非空引用值 x,x.equals(x) 都应返回 true。
对称性:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应返回 true。

传递性:对于任何非空引用值 x、y 和 z,如果 x.equals(y) 返回 true,并且 y.equals(z) 返回 true,那么 x.equals(z)

应返回 true。

一致性:对于任何非空引用值 x 和 y,多次调用 x.equals(y) 始终返回 true 或始终返回 false,前提是对象上 equals

比较中所用的信息没有被修改。

对于任何非空引用值 x,x.equals(null) 都应返回 false。

Object 类的 equals 方法实现对象上差别可能性最大的相等关系;即,对于任何非空引用值 x 和 y,当且仅当 x 和

y引用同一个对象时,此方法才返回 true(x == y 具有值 true)。


注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相

等对象必须具有相等的哈希码。


参数:
obj - 要与之比较的引用对象。
返回:

如果此对象与 obj 参数相同,则返回 true;否则返回 false。


(2)源码为:
 public boolean equals(Object obj) {
        return (this == obj);
    }

===================================================================================
2、String中的equals()方法:
(1)通过查找API,说明如下:

equals

public boolean equals(Object anObject)将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此

对象表示相同字符序列的 String 对象时,结果才为 true。


覆盖:
类 Object 中的 equals
参数:
anObject - 与此 String 进行比较的对象。
返回:

如果给定对象表示的 String 与此 String 相等,则返回 true;否则返回 false。


(2)源码为:

/**
     * 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) {//anObject是传进来的要进行比较的对象
	       //如果当前对象和传进来要进行比较的对象anObject是同一个对象(即地址相同eg同一辆汽车(只有一辆))则返回true
		 if (this == anObject) {
	            return true;
	        }
	        if (anObject instanceof String) {//如果传进来的需要进行比较的对象anObject是String类的实例,则把anObject转换成String类型
	            String anotherString = (String) anObject;
	            //value是一个private final char value[];
	            //String类的构造函数已经给value[]初始化了
	            //value.length代表原先要比较对象的字符个数
	            int n = value.length;
	            //如果两者的字符个数不相等,意味着两者不可能相等,所以返回false;否则,依次遍历比较两者的每一个字符,若每一个字符都相等则相等,否则不想等
	            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;
	    }
=====================================================================================

三、代码演示:

package Demo;

import java.util.ArrayList;
import java.util.Stack;

class person{
	
	private String name;
	private int age;
	person(String name , int age){
		this.name=name;
		this.age=age;
	}
	
	
}


public class DemoStringEquals {
	public static void main(String[] args) {
		test2();
	}
	
	public static void test2(){
		//基本数据类型
		int a = 5;
		int b = 6;
		int c = 5;
		System.out.println("a==b:"+(a==b));
		System.out.println("a==c:"+(a==c));
	
		//类类型变量
		person p1=new person("a",1);
		person p2=new person("a",1);
		System.out.println("p1==p2:"+(p1==p2));
		System.out.println("p1.equals(p2):"+p1.equals(p2));
		
		//String 类重写了equals()方法
		
		//str1和str2是两个不同的类(即共两辆汽车),但是str1和str2的内容相同,都是"a"(即,这两辆汽车一模一样,完全相同)
		String str1= new String("a") ;
		String str2= new String("a");
		
		String str3= "ab" ;
		String str4= "ab" ;
		String str5= "1" ;
		String str6= "1" ;
		String str7= "22" ;
		String str8= "22" ;
		String str9= "" ;
		String str10= " " ;
		String str11= null ;
		String s=str1;
		//==比较的是对象,.equals()比较的是内容
		System.out.println("str1==str2 : "+(str1==str2));
		System.out.println("str1.equals(str2) : "+(str1.equals(str2)));
		System.out.println("str1==str3 : "+(str1==str3));
		System.out.println("str1.equals(str3) : "+(str1.equals(str3)));
		System.out.println("str1==str10 : "+(str1==str10));
		System.out.println("str1.equals(str10): "+(str1.equals(str10)));
		System.out.println("str1==str11 : "+(str1==str11));
		System.out.println("str1.equals(str11) : "+(str1.equals(str11)));
		System.out.println("str10.equals(str11) : "+(str10.equals(str11)));
		System.out.println("str1==s : "+(str1==s));
		System.out.println("str1==str11 : "+(str1==str11));
		System.out.println("str1.equals(s) : "+(str1.equals(s)));
		System.out.println("str1.equals(a) : "+(str1.equals("a")));
		System.out.println("str1==a : "+(str1=="a"));
		System.out.println("str11==null : "+(str11==null));
		System.out.println("str11!=null : "+(str11!=null));
		//System.out.println("str11.equals(null): "+(str11.equals(null)));//Exception in thread "main" java.lang.NullPointerException 不能是Null.equals()
		
		
	}
}
运行结果为:


四、结论总结:

1、对于基本数据类型,“==”比较的是两者的值是否相等。

2、对于引用数据类型,(1)“==”比较的是引用的地址是否相同(即是否是同一辆汽车(注意,只有一辆汽车));

Object中的.equals()方法和"==’功能一样

(2)但是String类中的.equals()方法重写了,比较的是两个引用对象的内容是否想同(即是否是完全相同的汽车(注意,有两辆汽车,且一模一样,完全相同))。

猜你喜欢

转载自blog.csdn.net/G_66_hero/article/details/71081315