"=="与equals在比较时,"=="注重的是对内存地址的比较,而equals 则更注重内容上的比较,强调值是否相等。
'''==''适用于 基本数据类型或者引用类型,通过在常量池中查找,如果没有则开辟一个新的内存空间,等下一次调用时直接在常量池中查找,
举一个例子:
public class Work01 {
public static void main(String[] args) {
String str1 = "bbb";
String str2 = "aaa";
System.out.println(str1 == str2); //false
System.out.println(str1.equals(str2)); //false
int a = 123;
int b = 123;
System.out.println(a == b); //true
}
}
但是在char类型的数组中,查找是否有目标元素时,可以使用“==”:
public class Demo09 {
public static void main(String[] args) {
char[] characters = { 'A', 'E', 'G', 'K', 'a', 'b', 'd', 'f', 'm' };
char target = 'a';
int low = 0, high = characters.length - 1;
int index = -1;
while(low <= high) {
int mid = (low + high) / 2;
if(characters[mid] == target) {
index = mid;
break;
}else if(characters[mid] > target) {
high = mid -1;
}else if(characters[mid] < target) {
low = mid + 1;
}
}
System.out.println(index);
}
}
equals则更注重对字符串“值”的比较,通过自带的char类型常量数组对字符串的每一位进行判断,如果相等则继续判断下一位。