首先通过一段代码来进入今天的主题吧
package test2;
/**
*
* @author 10916
*
*/
public class tset2 {
public static void main(String[] args) {
int a = 10;
int b = 10;
System.out.println("当ab为基本数据类型整型使用==:");
System.out.println(a == b); // 普通类型,比较的就是变量的值 得到true
test3 the_1 = new test3(); // 声明两个引用类型变量 the_1\the_2
test3 the_2 = new test3();
the_1.c = 5;
the_1.d = 5;
the_2.c = 5;
the_2.d = 5;
System.out.println("当比较的是引用类型变量使用==:");
System.out.println(the_1 == the_2); // 得到flase
System.out.println("当比较的是引用类型变量使用equals:");
System.out.println(the_1.equals(the_2)); // 得到flase
String the_4 = "yes";
String the_5 = "yes";
System.out.println("当比较的是String类型使用equals:");
System.out.println(the_4.equals(the_5)); //得到的是true
}
}
class test3 {
int c;
int d;
}
通过这段代码,可以得到结果如下
那么为什么the_1 和 the_2的c、d都是5,而得到结果是flase呢?这就是由于堆栈模型导致,
引用变量的变量名存在栈中,而具体内容存在堆中,通过引用名指向堆地址,而the_1和the_2通过new在堆中创建了两个空间,注意:这里的两个空间是不同的,空间的内容(c、d是相同),而这个时候,==和equals比较的都是地址,因为两个引用变量名指向的地址是不同的,所以最后得到的结果是flase,通过简单图片观察:
而String类型用equals得到的是true是因为在java中,有一部分类中equals被重载了,所以比较的是内容,但大部分引用变量中比较的还是地址。
==在基本数据变量类型中比较的是变量值,在引用类型变量中,比较的是地址,equals在引用类型变量中,比较的也是地址(部分中,如String中,equals比较的是内容)