Java编程思想读书笔记——字符串

/**
 * 对于String类的equal()方法来讲,它是判断当前字符串与传进来的字符串的内容是否一致
 * 对于String对象的相等性判断来讲,请使用equals()方法,不要使用==
 * String是常量,其对象一旦创建完毕就无法改变
 * Java中String是通过String Pool来维护的
 * 所有new出来的对象都会在堆中,String Pool是在栈中
 * “基本类型”用 == 或者 != 来进行判断就行,复杂类型用equals方法,但是equals方法也是
 * 用引用来进行比较相等与否,所以有时候需要自己重写equals方法
 * 对于ActionScript 3中,字符串可以使用==和!=来进行判断
 * @author aisajiajiao
 * @see Java编程思想第四版
 */
public class StringTest
{
	public static void main(String[] args)
	{
		String str = new String("aaa");
		String str2 = new String("aaa");
		System.out.println(str == str2);	//输出false
		
		String str3 = "aaa";
		String str4 = "aaa";
		System.out.println(str3 == str4);	//输出true
		System.out.println(str3.intern() == str4);
		
		String str5 = new String("as");
		String str6 = "as";
		System.out.println(str5 == str6);	//输出false
		
		Integer n1 = new Integer(47);
		Integer n2 = new Integer(47);
		System.out.println(n1 == n2);		//输出false
		System.out.println(n1 != n2);		//输出true
	}
}
/**
 * Java doc 中队String.intern()方法解析
 * public String intern()
 * Returns a canonical representation for the string object. 
 * A pool of strings, initially empty, is maintained privately by the class String. 
 * When the intern method is invoked, if the pool already contains a string equal to
 * this String object as determined by the equals(Object) method, then the string from the pool is returned.
 * Otherwise, this String object is added to the pool and a reference to this String object is returned. 
 * It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. 
 */

你可能感兴趣的:(Java编程思想读书笔记——字符串)