Java中equals与==的区别(全面)

本文深入探讨Java中equals与==的区别,特别是引用和值的比较,并详细解析非String对象的==与equals行为。通过举例分析,帮助开发者理解在不同场景下如何正确使用这些方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java中equals与 == 的区别是什么呢?关于这个问题的回答大家都听说过,==是比较引用是否相同,equals是比较值是否相等。

这个答案对,但是不全面。引用是否相同其实就是它们指向的地址是否为同一个。

下面举一些例子:
   
String source="abc";
String str1 = "abc";
String str2 = new String(source);
String str3 = new String("abc");
String str4 = source;
String str5="ab"+"c";
System.out.println(source == str1);//1
System.out.println(source == str2);//2
System.out.println(source == str3);//3
System.out.println(source == str4);//4
System.out.println(source == str5);//5
请问:下面5条打印什么结果?最好自己先想一下再看结果。









结果为:true
                false
                 false
                true
                true



好的,容我一一解释。
1打印true 是因为Java中有一个 字符串池, Java会缓存所用过的字符串变量,例如:执行String a  = "Java";语句之后,
系统的字符串池中就会缓存一个字符串“Java”;如果程序再次执行String b = "Java"后,系统将会让
b直接指向字符串池中的"Java"字符串,因此a==b将会返回true。
记住这一点 ==是比较引用是否相同"就不难理解。因为它们都指向了同一块内存。

2打印false因为  str2 = new String ( source ); 通过new 调用了String类构造器方法创建了一个对象,并将它的引用赋值给了 str2 变量。
所以会有两个内容为"abc"的对象,分别通过source与str2引用。

3打印false原因见上一条。

4打印true就很好理解了, str4 = source ;就是让str4指向source引用的对象,它们引用的都是同一个地址。


5打印true让我展开来讲一下

   
String str1 = "abc";
String str2 = "abcabc";
String str3 = str1+str1;
String str4 = "abc"+"abc";
final String str5 = "abc";
String str6 = str5+str5;
System.out.println(str2==str3);//6
System.out.println(str2==str4);//7
System.out.println(str2==str6);//8
结果为:
    
false
true
true
6  str3,它是由str1+str1得到,由于str1只是个普通变量,因此
编译器无法在编译时确定str3的值,不会让str3指向字符串池中缓存中的“abcabc”,所以false.


7 str4的值是两个字符串直接进行连接运算,由于编译器可以在编译阶段就确定str4的值为“abcabc”,所以
系统会让str4直接指向字符串池中缓存中的“abcabc”字符串。所以true。

对于final实例变量而言,只有在定义该变量时指定初始值才会有“宏变量”的效果。此处正好符合要求,
所以编译器会对str5进行“宏替换”, 可以在编译阶段就确定str6的值为“abcabc",因此为;true。

 由 7,8 得, str4 = "abc" + "abc" ; 编译器可以在编译阶段就确定str4的值,也就是直接字符串拼接等同于宏变量替换。

对两个内容相等的String 变量进行equals判断,结果为true。没有什么好讲的了。

String 字符串池以及==问题就讲到这里。



接下来讲非String对象的==与equals问题

   
Integer i1 = 5;
Integer i2 = 5;
System.out.println(i1+"=="+i2+":"+(i1==i2));
i1 = 128;
i2 = 128;
System.out.println(i1+"=="+i2+":"+(i1==i2));
i1 = 127;
i2 = 127;
System.out.println(i1+"=="+i2+":"+(i1==i2));
i1 = -128;
i2 = -128;
System.out.println(i1+"=="+i2+":"+(i1==i2));
i1 = -129;
i2 = -129;
System.out.println(i1+"=="+i2+":"+(i1==i2));
结果:

   
5==5:true
128==128:false
127==127:true
-128==-128:true
-129==-129:false
当我们给Integer赋值时,实际上调用了Integer.valueOf(int)方法,查看源码,其实现如下:
  
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache实现如下:
   
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
 
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;
 
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
 
private IntegerCache() {}
}
总之,如果范围[-128,127]的整数,会使用Integer常量池。所以==返回true,不在这个范围:  return new Integer ( i ); 所以为false

另外: Java的8种基本类型(Byte, Short, Integer, Long, Character, Boolean, Float, Double), 除Float和Double(小数)以外, 其它六种都实现了常量池, 但是它们只在大于等于-128并且小于等于127时才使用常量池。

   
Integer int1 = 12911;
Integer int2 = 12911;
System.out.println(int1.equals(int2));//true
所以,同一基本类型之间的比较最好用equals。
但是,不同基本类型之间呢,比如short和Integer呢
   
Integer i = 1;
short s = 1;
System.out.println(i.equals(s));//false
System.out.println(i == s);//true
为什么。看源码:
Integer.class的源码
   
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

if ( obj instanceof Integer ) {
}
return false;

就是说如果参数obj不是Integer的实例,就会返回false。

先写到这里,果然好累。

参考:
http://www.cnblogs.com/ydpvictor/archive/2012/09/09/2677260.html


<Java疯狂编程>系统 李刚著






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愤怒的可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值