关系操作符:==
- 可以使用在基本数据类型变量和非基本数据类型变量(引用类型变量)中
- 基本数据类型变量之间比较的是储存的“值”是否相等
- 引用类型变量之间比较的是所关联的对象地址是否相等
在Java中游8种基本数据类型:
浮点型:float(4 byte), double(8 byte)
整型:byte(1 byte), short(2 byte), int(4 byte) , long(8 byte)
字符型: char(2 byte)
布尔型: boolean(JVM规范没有明确规定其所占的空间大小,仅规定其只能够取字面值"true"和"false")
对于这8种基本数据类型的变量,变量直接存储的是“值”,因此在用关系操作符 == 来进行比较时,比较的就是 “值” 本身。要注意浮点型和整型都是有符号类型的,而char是无符号类型的(char类型取值范围为0~2^16-1).
也就是说比如:
int n=3;
int m=3;
变量n和变量m都是直接存储的"3"这个数值,所以用==比较的时候结果是true。
而对于非基本数据类型的变量,在一些书籍中称作为 引用类型的变量。比如上面的str1就是引用类型的变量,引用类型的变量存储的并不是 “值”本身,而是于其关联的对象在内存中的地址。比如下面这行代码:
String str1;
这句话声明了一个引用类型的变量,此时它并没有和任何对象关联。
而 通过new String(“str”)来产生一个对象(也称作为类String的一个实例),并将这个对象和str1进行绑定:
str1= new String(“str”);
那么str1指向了一个对象(通常把str1称作为对象的引用),此时变量str1中存储的是它指向的对象在内存中的存储地址,并不是“值”本身(存储的字符串"str")。
Test1:
public class EqualsTest {
public static void main(String[] args) {
int a = 3;
int b = 3;
System.out.println(a == b);
String str1 = new String("str");
String str2 = new String("str");
String str3 = new String("str");
System.out.println(str1 == str2);
str1 = str3;
str2 = str3;
System.out.println(str1 == str2);
}
}
/*
true
false
true
*/
Object类中的equals()方法
Object类中的equals()方法源码实现如下:
–可以得出:在Object类中,equals方法是用来比较两个对象的引用是否相等,即是否指向同一个对象
public boolean equals(Object obj) {
return (this == obj);
}
Test2:
public class EqualsTest {
String name;
int age;
EqualsTest(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
EqualsTest et1 = new EqualsTest("mofei", 22);
EqualsTest et2 = new EqualsTest("mofei", 22);
System.out.println(et1 == et2);
System.out.println(et1.equals(et2));
}
}
/*
false
false
*/
然而,将Test1中的 == 替换为equals()方法是又会得到与Test2不一样的结果;
Test3:
public class EqualsTest {
public static void main(String[] args) {
int a = 3;
int b = 3;
System.out.println(a == b);
String str1 = new String("str");
String str2 = new String("str");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
}
}
/*
true
false
true
*/
这是因为:String类对equals()方法进行了重写,用来比较指向的字符串对象所存储的字符串是否相等。
String类中equals()方法源码实现如下:
public boolean equals(Object anObject) {
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;
}
像String,,Integer,Double,Date,File, 包装类等都重写了Object类中的equals()方法,而重写之后,比较的不再是两个引用的地址是否相同,而是比较的是所指向的对象的内容是否相等。