Java中的"=="与"equals()"的对比,Java的字符串常量池概念
Java中的"=="在判断基本类型数据时
当比较基本数据类型的时候比较的是数值。
public class Demo_1 {
public static void main(String[] args){
int i = 10;
int j = 10;
boolean b = (i==j);
System.out.println(b);
}
}
/*
输出结果:
true
*/
"=="在判断引用数据类型时
当比较引用类型数据时比较的是引用(指针)。
public class Demo_1 {
public static void main(String[] args) {
String str1 =new String ("zzh");
String str2 = "zzh";
System.out.println(str1==str2);
}
}
/*
输出结果:
false
*/
equals()方法
对比上一个Java实例
public class Demo_1 {
public static void main(String[] args) {
String str1 =new String ("zzh");
String str2 = "zzh";
System.out.println(str1==str2);
System.out.println(str1.equals(str2));
}
}
/*
输出结果:
false
true
*/
用equals()方法对比str1与str2时发现返回的布尔类型的值为true
在0bject中就存在equals()方法,但仍需要引用同一个对象时才返回true,Object时所有类的父类,所以一般定义的类中都会根据自己的需要重写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 s1 = "hello,world!";
String s2 = "hello,world!";
在执行完第一行代码后,常量池就已经存在了"hello,world",在当第二句代码运行时,就不会重新申请内存空间,而是将已有字符串的地址返回给引用变量时s2,
所以这时判断s1==s2会返回true
public class Demo {
public static void main(String[] args) {
String str1 =new String ("zzh");
String str2 = "zzh";
System.out.println(str1==str2);
System.out.println(str1.equals(str2));
String str3 = "zzh";
String str4 = "zzh";
System.out.println(str3==str4);
System.out.println(str3.equals(str4));
}
}
/*
输出结果:
false
true
true
true
*/