Java中==和equals的区别
==(==可以用于比较基本类型和引用类型)
基本类型:==比较(byte/short/int/long/float/double/char/boolean)时直接比较值是否相等
例如:
char c1 = 'A';
char c2 = 'A';
System.out.println(c1 == c2); // true(字符编码值相等)
引用类型: ==比较对象的内存地址是否相同(即是否指向同一个对象)。
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false(地址不同)每次调用 new 都会在堆内存中创建一个新的 String 对象,即使内容相同,地址也不同。
特殊情况:Integer 的缓存机制
对于 Integer
对象,当值在 -128 到 127 之间时,会复用缓存对象,导致 ==
也返回 true
:
Integer a = 100; // 自动装箱,实际调用 Integer.valueOf(100)
Integer b = 100;
System.out.println(a == b); // true(缓存复用,地址相同)
Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false(超出缓存范围,地址不同)
equals(Object方法)只适用于引用类型如 String
、Integer
等
equals本质上和==是一样的都是比较的对象的地址是否相同,而String中 equals比较的是字符串的值是否相同是因为String重写了 equals方法,所以 equals的作用取决于子类是否重写 equals方法,不然 equals的作用就是比较地址是否相同
public boolean equals(Object obj) {return (this == obj); // Object类的原始实现
}
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2)); // true(内容相同)