【冰啤-恒】== 和 equals 的区别是什么?
基本数据类型:
byteshortcharintlongdoublefloatboolean
实例方法: 实例方法是相对于静态方法 没有
static前缀
==运算符:
- 基础数据类型比较值的大小是否相同
- 引用数据类型比较对象的地址是否相同
public class Test {
public static void main(String[] args) {
int a = 0;
int b = 0;
System.out.println(a == b); // true
Integer c = 1;
Integer d = 1;
System.out.println(c == d); // true
Integer e = 321;
Integer f = 321;
System.out.println(e == f); // false
}
}
原因解析:
// Integer源码中的IntegerCache 存储了从[-128, 127)
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;
}
equals方法:
equals方法是基类Object中的实例方法- 如果类中没有对
equals方法进行重写 比较的就是这两个对象的地址 - 如果类对
equals方法进行了重写 一般用来比较两个对象之间的值是否相同 常见的是String中的equals方法
Object objectA = new Object();
Object objectB = new Object();
System.out.println(objectA.equals(objectB)); // false
objectB = objectA;
System.out.println(objectA.equals(objectB)); // true
扩展: String
String s1 = "hello";
String s2 = new String("world");
[1] s1在字符串常量池中创建对象 并将对象引用赋值给s1
[2] s2通过new关键字在堆中创建对象 并将对象引用赋值给s2
此外StringBuffer和StringBuilder并没有重写equals方法,其比较的还是引用类型的地址。
private final char value[];
// String 重写的equals()方法
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;
}

浙公网安备 33010602011771号