equals的作用:用于判断两个变量是否是对同一个对象的引用,即堆中的内容是否相同,返回值为布尔类型
“==”操作符的作用:
1、用于基本数据类型的比较
2、判断引用是否指向堆内存的同一块地址。
public static void main(String[] args){
String a = "Hello";
String b = "Hello";
String c = new String("Hello");
String d = new String("Hello");
/**String作为一个基本类型来使用**/
System.out.println(a==b);//ture
System.out.println(a.equals(b));//true
System.out.println(a==c); //false
System.out.println(a.equals(c)); //true
/**String作为引用类型来使用**/
System.out.println(c == d); //引用不同,false
System.out.println(c.equals(d)); //内容相同,true
}
public static void main(String[] args) {
Integer a = 150;
Integer b = 150;
Integer c = new Integer(150);
Integer d = new Integer(150);
int e = 150;
System.out.println(a==b); //false
System.out.println(a.equals(b));//true
System.out.println(a==c);//false
System.out.println(a.equals(c));//true
System.out.println(c==d);//false
System.out.println(c.equals(d));//true
//因为与初始化值做比较的时候,会将封装类型进行拆箱操作,转换为基本类型。这里比较的就是基本类型的值了*
System.out.println(a==e);//true
System.out.println(a.equals(e));//true
System.out.println(c==e);//true
System.out.println(c.equals(e));//true
}
public int intValue() {
return value;
}
其中有个特例:
public static void test(){
Integer a=1;
Integer b=1;
System.out.println(a==b); //true
System.out.println(a.equals(b));//true
}
Integer a=150;//会将int类型通过valueof转换成Integer类型。下面是valueof源码。
static final int low = -128;
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
也就是说在-128到127之间的值会缓存到IntegerCache.cache中,所以在Integer x=在-128到127之间时,返回的是同一个对象,所以出现了上文的情况。(如果换成 >、>=、<、<=会出现什么情况呢?这中情况会自动拆箱比较值。)