Posted on 2008-12-06 19:39
遲來的兵 閱讀(239)
評論(0) 編輯 收藏 所屬分類:
Java
一.String對象的比較,+操作和intern方法
這里從一個問題入手來看看。
package testPackage;

public class Test
{

public static void main(String[] args)
{
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel" + "lo")) + " ");
System.out.print((hello == ("Hel" + lo)) + " ");
System.out.println(hello == ("Hel" + lo).intern());
}
}

class Other
{
static String hello = "Hello";
}
package other;

public class Other
{
static String hello = "Hello";
}
正確答案:true true true true false true
主要要點有:
1.所有內(nèi)容相同的String指向同一個內(nèi)存塊。但String對象不能是通過new操作創(chuàng)建出來。主要原因是JVM對String做了優(yōu)化,String加載之后會持有一個常量池,
只要在常量池中找到內(nèi)容相同的String就會把其引用返回。而new操作是直接在內(nèi)存中分配新空間。
2.Java中有兩種綁定,靜態(tài)和動態(tài)。如果+操作的兩邊是常量表達式那么會在采用靜態(tài)綁定,也就是說編譯之后值已經(jīng)定下來了。而如果有一邊是通過new操作創(chuàng)建出
來的那么會采用動態(tài)綁定,只有在運行的時候才知道其具體的值。
3.String的intern方法會到常量池里面找是否有相同內(nèi)容的String,如果有則返回其引用。如果沒有則把這個String對象添加到常量池之中并放回其引用。額外說
下,intern在英文中有保留區(qū)的意思,這樣好理解其作用。intern方法還是native的。
二.String中的正則表達式使用
String中有些方法是需要正則表達式作為參數(shù)的。這個時候就要主要不要傳錯參數(shù)。最典型的例子就是replaceAll(String regex, String replacement)。第一個
參數(shù)是需要正則表達式的,而第二參數(shù)是普通的字符串。
String ss = "???";
ss = ss.replaceAll("?", "=");//運行到這里會拋出PatternSyntaxException,因為“?”在正則表達式里面是特殊符號,需要轉(zhuǎn)義。
ss = ss.replaceAll("[?]", "=");//正確,我個人比較傾向于這種寫法。
ss = ss.replaceAll("\\?", "=");//正確,對“?”做轉(zhuǎn)義。
因此在使用split,replaceAll,replaceFirst等方法時要特別注意是不是需要轉(zhuǎn)義.