equals()方法与==的区别

在Object类中的equals()方法:

1
2
3
public boolean equals(Object obj) {
return (this == obj);
}

很明显的看出他就是用==来比较对象所占空间的地址,而我们所说的==是比较地址,equals()是比较值,这种说发在严格意义上讲是不对的,equals()比较值,是基于很多类根据自己的一些需要来重写Object中的equals()方法,例如String中的equals():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}

Integer装箱问题

1
2
3
4
5
6
7
public class Demo {
public static void main(String[] args) {
Integer a = 100, b = 100, c = 200, d = 200;
System.out.println(a == b);
System.out.println(c == d);
}
}

对于将int赋值给Integer,会直自动用Integer下的valueOf();方法,属于自动装箱过程,而valueOf();中是这样写的:

1
2
3
4
5
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

IntegerCache是Integer的内部类,其代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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() {}
}

如果整型字面量的值在-128到127之间,那么不会new新的Integer对象,而是直接引用常量池中的Integer对象,所以上面的面试题中a==b的结果是true,而c==d的结果是false。


Java八种基本数据类型的大小,以及他们的包裹类

  • byte(Byte):8位,取值范围是负的2的7次方到正的2的7次方减1。
  • short(Short):16位,取值范围是负的2的15次方到正的2的15次方减1。
  • int(Integer):32位,取值范围是负的2的31次方到正的2的31次方减1。
  • long(Long):64位,取值范围是负的2的63次方到正的2的63次方减1。
  • float(Float):32位,取值范围是3.402823e+38 ~ 1.401298e-45(e+38表示是乘以10的38次方,同样,e-45表示乘以10的负45次方)。
  • double(Double):64位,取值范围是1.797693e+308~ 4.9000000e-324。
  • boolean(Boolean):只有两个值,true和false。
  • char(Character):采用unicode编码,它的前128字节编码与ASCII兼容。