java中==和equals和hashCode的区别
1.==符号
对于Java的8种基本类型:数值型(byte、short、int、long、float、double)、字符型(char)、布尔型(boolean),比较的是变量存储的值; 对于非基本类型,也就是常说的引用数据类型:类、接口、数组,由于变量种存储的是内存中的地址,并不是值本身,所以真正比较的是该变量存储的地址;
情况1:
int a=1; int b=1; System.out.print( a==b)
结果:true ,比较他们的值。
情况2:
Integer a= new Integer(100); Integer b= new Integer(100); System.out.print(a == b);
结果:false ,new创建的两个对象,其内存地址不同。
情况3:
Integer a = new Integer(100); Integer b = 100; System.out.print(a == b);
结果:false, 非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同
情况4:
Integer a = new Integer(100); int b = 100; System.out.print(a == b);
/结果:true ,Integer变量和int变量比较时,java会自动拆包装为int,实际上就变为两个int变量的比较。
情况5:
Integer a = 127; Integer b = 127; System.out.print(a == b); // 结果: true Integer c = 128; Integer d = 128; System.out.print(c == d); // 结果: false
java在编译Integer i = 127 ;时,会翻译成为Integer i = Integer.valueOf(127);java API中对Integer类型的valueOf的定义如下
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);
}
java对于-128到127之间的数,会进行缓存,Integer i = 127时,会将127进行缓存,下次再写Integer j = 127时,就会直接从缓存中取,就不会new了。所以对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false。
2.equals()方法
默认情况equals等同于==,Object类中equals源码:
public boolean equals(Object obj) {
return (this == obj);
}
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;
}
equals方法判断相等的步骤:
- 使用==,检查对象引用是否相同。
- 使用instanceof,检查对象类型是否相同。
- 检查参数中的域是否与该对象中对应的域相匹配。
