JAVA的==与Equals

以下是我的理解,可能有误 Java中的“==”用来判断是否是同一个对象(对象的引用是不是一样),equals方法一般会被覆盖,主要是比较值,而且一般只和同一类对象比较。

String的比较

public class TestEqual {
	
	public static void main(String[] args) {
		String a = "abc";
		String b = "abc";
		String c = new String("abc");//新建了一个对象
		String d = new String("abc");
		String e = "ab"+"c";//使用常量池中的对象
		String f = "ab";
		String g = f + "c";//string是固定字符,需要新建对象
		System.out.println(a == b);//true,第一次a把字符串放在常量池,那b继续用这个常量,e也一样
		System.out.println(a.equals(b));//true
		System.out.println("a == c?"+(a == c));//false
		System.out.println(a.equals(c));//true
		System.out.println(c==d);//false
		System.out.println(a==e);//true
		System.out.println(a==g);//false
	}
}

还有个String.intern()不太理解
更多的信息可以看这里:http://developer.51cto.com/art/200602/21445.htm

数字的比较

需要理解autoBoxing的概念!

public class TestEqual {
	
	public static void main(String[] args) {
		Integer i1 = new Integer(9); 
		Integer i2 = new Integer(9); 
		int i3 = 9;
		int i4 = 9;
		Integer i5 = 9;//自动装箱(box)操作,基本类型int 9可以自动box成对象Integer
		Integer i6 = 9;
		Long long1 = new Long(9);
		System.out.println(i1==i2);//false
		System.out.println(i1==i3);//true
		System.out.println("i3==i4?"+(i3==i4));//true,常量池
		System.out.println("i1==i3?"+(i1==i3));//true
		System.out.println("i5==i6?"+(i5==i6));//true,当-128<i5<127时为true,其他为false
		//http://blog.csdn.net/newsonglin/archive/2008/10/15/3079865.aspx
		// If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
		System.out.println("i3==i5?"+(i3==i5));//false
		System.out.println("i1==i5?"+(i1==i5));//false
		System.out.println(i1.equals(i2));//true,同类型比较值
		System.out.println(i1.equals(long1));//false,不同类型不进行比较

	}

}

更多的信息可以参考这篇文章:http://blog.csdn.net/newsonglin/archive/2008/10/15/3079865.aspx

updatedupdated2023-12-062023-12-06