equal 和 ==

刚才看了一下别人的博客,想加深一下对 equal 和 == 的了解。

总结了几点:

1.equal 每个类都有必要覆盖一下,对于String 类,已经覆盖,比较的是String对象的字符序列是否相等。

2.== 比较的是内存中两个对象是否为同一个,即地址是否相等;而对于基本数据类型,比较的是字面数值是否一样。

package com.java.test;

import org.junit.Test;

public class MyEqual {

	@Test
	public void test() {
		
		int a1 = 10;
		int a2 = 10;
		
		Integer b1 = 10;
		Integer b2 = 10;
		
		String s1 = "abcd";
		String s2 = "abcd";
		String s3 = new String("abcd");
		
		
		System.out.println(a1 == a2);//true
		
		System.out.println(b1 == b2);//true
		System.out.println(b1.equals(b2));//true
		
		System.out.println(b1 == a1);//true
		System.out.println(b1.equals(a1));//true
		
				
		System.out.println(s1 == s2);//true
		System.out.println(s1 == s3);//false
		System.out.println(s1.equals(s3));//true
	}

}

  

原文地址:https://www.cnblogs.com/gy19920604/p/4722072.html