Posted on 2008-12-06 19:39
遲來(lái)的兵 閱讀(234)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
Java
一.String對(duì)象的比較,+操作和intern方法
這里從一個(gè)問(wèn)題入手來(lái)看看。
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
主要要點(diǎn)有:
1.所有內(nèi)容相同的String指向同一個(gè)內(nèi)存塊。但String對(duì)象不能是通過(guò)new操作創(chuàng)建出來(lái)。主要原因是JVM對(duì)String做了優(yōu)化,String加載之后會(huì)持有一個(gè)常量池,
只要在常量池中找到內(nèi)容相同的String就會(huì)把其引用返回。而new操作是直接在內(nèi)存中分配新空間。
2.Java中有兩種綁定,靜態(tài)和動(dòng)態(tài)。如果+操作的兩邊是常量表達(dá)式那么會(huì)在采用靜態(tài)綁定,也就是說(shuō)編譯之后值已經(jīng)定下來(lái)了。而如果有一邊是通過(guò)new操作創(chuàng)建出
來(lái)的那么會(huì)采用動(dòng)態(tài)綁定,只有在運(yùn)行的時(shí)候才知道其具體的值。
3.String的intern方法會(huì)到常量池里面找是否有相同內(nèi)容的String,如果有則返回其引用。如果沒(méi)有則把這個(gè)String對(duì)象添加到常量池之中并放回其引用。額外說(shuō)
下,intern在英文中有保留區(qū)的意思,這樣好理解其作用。intern方法還是native的。
二.String中的正則表達(dá)式使用
String中有些方法是需要正則表達(dá)式作為參數(shù)的。這個(gè)時(shí)候就要主要不要傳錯(cuò)參數(shù)。最典型的例子就是replaceAll(String regex, String replacement)。第一個(gè)
參數(shù)是需要正則表達(dá)式的,而第二參數(shù)是普通的字符串。
String ss = "???";
ss = ss.replaceAll("?", "=");//運(yùn)行到這里會(huì)拋出PatternSyntaxException,因?yàn)?#8220;?”在正則表達(dá)式里面是特殊符號(hào),需要轉(zhuǎn)義。
ss = ss.replaceAll("[?]", "=");//正確,我個(gè)人比較傾向于這種寫(xiě)法。
ss = ss.replaceAll("\\?", "=");//正確,對(duì)“?”做轉(zhuǎn)義。
因此在使用split,replaceAll,replaceFirst等方法時(shí)要特別注意是不是需要轉(zhuǎn)義.