浅谈Java中的equals和==

xiaoxiao2021-02-28  118

public class Main { /** * @param args */ public static void main(String[] args) { int n=3; int m=3; System.out.println(n==m); String str = new String("hello"); String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1==str2); str1 = str; str2 = str; System.out.println(str1==str2); String str3 = "Hello"; String str4 = "Hello"; System.out.println("str3 == str4 : " + (str3 == str4)); } }

运行的结果依次为:true false true true

 

  对于Java中的基本数据类型,==是直接比较两个的值是否相等。

     对于引用类型的变量,则==是比较所指向的对象的地址。

  而equals方法不能作用于基本数据类型的变量!!!

     如果没有对equals方法进行重写,则比较的是引用类型的变量所指向的对象的地址。

 

——————————————————————————————————————

其中,对于String str1 = new String ("hello"); 称作为 引用类型的变量。引用类型的变量存储的并不是 “值”本身,而是于其关联的对象在内存中的地址。

  String str1;

  这句话声明了一个引用类型的变量,此时它并没有和任何对象关联。

  而 通过new String("hello")来产生一个对象(也称作为类String的一个实例),并将这个对象和str1进行绑定:

  str1= new String("hello");

  那么str1指向了一个对象(很多地方也把str1称作为对象的引用),此时变量str1中存储的是它指向的对象在内存中的存储地址,并不是“值”本身,也就是说并不是直接存储的字符串"hello"。这里面的引用和C/C++中的指针很类似。

  因此在用==对str1和str2进行第一次比较时,得到的结果是false。因此它们分别指向的是不同的对象,也就是说它们实际存储的内存地址不同。

 

转载请注明原文地址: https://www.6miu.com/read-41532.html

最新回复(0)