总是会遇到 == 和 equals 的使用,对其区别和各自的原理总是不太清晰,今天好好看一下并记录下来。
== 和 equals
通常 == 和 equals 是用来比较两个对象的大小的
- 当我们使用 == 进行比较时,如果两个变量时基础数据类型,并且都是数值类型,那么比较两个变量值得大小;但是如果两个变量是引用类型数据的话,那么只有这两个变量只想了同一个对象的时候,== 判断才会返回true。
例如:
public class Test {
public static void main(String args[]){
int i = 65;
float f = 65.0f;
System.out.println(i == f); // true
char c = 'A';
System.out.println(i == c); // true
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2); // false
System.out.println(str1.equals(str2)); // true
System.out.println("hello" == new Test()); // 编译错误
}
}
请问:new String("hello") 生成了一个对象 答:JVM 会先使用常量池来管理 “hello” 直接量,然后再调用 String 类的构造器来创建一个新的 String 对象,新创建的 String 对象保存在堆内存中。所以一共产生了两个对象。
常量池 专门用于管理在编译器被确定并保存在已编译的 .class 文件中的一些数据。 包括了关于类、方法和接口中的敞亮,同时还包括字符串常量。
例如:
public class Test {
public static void main(String args[]){
String s1 = "疯狂Java";
String s2 = "疯狂";
String s3 = "Java";
String s4 = "疯狂" + "Java";
String s5 = "疯" + "狂" + "Java";
String s6 = s2 + s3;
String s7 = new String("疯狂Java");
System.out.println(s1 == s4); // true
System.out.println(s1 == s5); // true
System.out.println(s1 == s6); // false
System.out.println(s1 == s7); // false
}
}
未完待续...
继续: 重写 equals 方法需要满足的条件:
- 自反性, 对任意的 x ,x.equals(x)一定返回 true
- 对称性, 对任意的 x 和 y,y.equals(x) 返回true,则 x.equals(y) 返回 true
- 传递性, dui 任意 x,y和z, x.equals(y) 返回true,y.equals(z) 返回 true,则 x.equals(y) 返回 true
- 一致性,如果对象中进行等价比较的信息没有改变,无论比较多少次都是相同的结果
- 对任何不是null 的 x, x.equals(null) 返回 false