总体来说kotlin中==比较的是数值是否相等, 而===比较的是两个对象的地址是否相等。
code1:
val a: Int = 999
val b: Int? = a
val c: Int? = a
println(b == c) //true
println(b === c) //false
这个和java中运行结果是在意料之中, == 比较数值, 而===比较的是地址, 前者为true, 后者为false.
code1代码对应的java代码为:
short a = 999;
Integer b = Integer.valueOf(a);
Integer c = Integer.valueOf(a);
boolean var4 = Intrinsics.areEqual(b, c);
System.out.println(var4);
var4 = b == c;
System.out.println(var4);
继续看下面这段代码的运行情况。
code2:
val a: Int = 999
val b: Int = a
val c: Int = a
println(b == c) // true
println(b === c) // true
这段代码和第一段代码的区别就是Int和Int?的区别, 为什么===的运算结果会不一样呢? 不要急, 再看下面这段代码
code3:
val a: Int? = 999
val b: Int? = a
val c: Int? = a
println(b == c) //true
println(b === c) //true
Code3 对应Java代码:
Integer a = Integer.valueOf(999);
boolean var4 = Intrinsics.areEqual(a, a);
System.out.println(var4);
var4 = a == a;
System.out.println(var4);
code3代码和code1代码的区别就是第一行的Int?和Int的区别, 而运行出来的结果===也是true, 这是为什么呢?
下面这个就是对上述现象的最好的解释
注意一点: 在 java 平台上,数值被 JVM 虚拟机以字节码的方式物理存储的,除非我们需要做可空标识(比如说 Int?) 或者涉及泛型。在后者中数值是装箱的(参考http://www.kotlindoc.cn/Basics/Basic-Types.html 这个文章)。
也就是说如果我们使用的是val a : Int = 999, 这种方式, 其实a就是个数值, 不涉及装箱的问题, 也就是不是个对象, 而如果我们使用的是val a: Int? = 999, 这样的话, a是一个Int型对象, 涉及到装箱问题, 这样就很好解释为什么第一段代码的===是false, 因为a是数值, 而b, c是装箱后的对象, 而第二段代码a, b, c都是数值, 第三段代码a, b, c都是同一个对象
下面再看一个特殊的情况
code4:
val a: Int = 100
val b: Int? = a
val c: Int? = a
println(b == c) //true
println(b === c) //true
Code4 对应Java代码:
byte a = 100;
Integer b = Integer.valueOf(a);
Integer c = Integer.valueOf(a);
boolean var4 = Intrinsics.areEqual(b, c);
System.out.println(var4);
var4 = b == c;
System.out.println(var4);
code4代码和code1代码很奇怪吧!除了数值不一样意外对应的java源码也是类似的,源码中就只有数值的类型不一样,原因只可能这个了,我们继续看看valueOf的源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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) {
try {
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);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
看完valueOf源码,稍微有点java基础的就明白为什么吧,在-128到127之间的数值没有重新包装成新对象而是使用的IntegerCache里缓存的数据,所以b和c的地址和值都是同一个对象。