您的位置:首页 > 编程语言 > Java开发

编写高质量代码改善java程序的151个建议——[52-57]String !about String How to use them?

2014-08-24 10:57 621 查看



原创地址:http://www.cnblogs.com/Alandre/(泥沙砖瓦浆木匠),须要转载的,保留下!
Thanks

Althoughtheworldisfullofsuffering,itisfullalsooftheovercomingofit.-HellenKeller
相信自己看得懂就看得懂了,相信自己能写下去,我就開始写了.事实上也简单—泥沙砖瓦浆木匠

WrittenInTheFont

Threepieces[52-3]:

52.Suggestion:UsetheStringdirectvaluefortheassignment[推荐使用String直接量赋值]

54.HowtousetheString,StringBuffer,StringBuilder[正确的使用String,StringBuffer,StringBuilder]

55.EasyTime:PayattentiontotheaddressofString[注意字符串的位子]

57.Complexstringmanipulationusingregularexpressions[复杂字符串操作使用正則表達式]

Suggestion:UsetheStringdirectvaluefortheassignment

DouknwtheStringObject?Ifudosomeprojects,ucanseetheStringisusedusually.Aobjectiscreatedbythekeyword:new.Therefore,wecancreateaStringObejctby:“

Stringstr3=newString("Jeff");”.

Here,inmyword,usingtheStringdirectvaluefortheassignmentisabetterway.


forexample:

publicclassString01
{
publicstaticvoidmain(String[]args)
{
Stringstr1="Jeff";
Stringstr2="Jeff";
Stringstr3=newString("Jeff");
Stringstr4=str3.intern();

booleanb1=(str1==str2);
booleanb2=(str1==str3);
booleanb3=(str1==str4);

System.out.println("b1:"+b1+""+"b2:"+b2+""+"b3:"+b3+"");
}
}
#outputs:
b1:trueb2:falseb3:true


b1:trueb2:false

uwillthink,thatswhytheyrdifferent.

Asweallkno,theoperator“==”showwhethertwoobjects’address
referencesarethesame.JavadesignedaStringPoolforstoringalltheStringusedtoavoidtherearetomanyStringObjectscreatedinasystem.SoStringstr3=
newString("Jeff");iscreatingaobjectinjava
heapmemorynotthe
StringPool.

intern()isamethodofString.wecanseefromthejdkhelpdoc.

publicStringintern()
Returnsacanonicalrepresentationforthestringobject.
Apoolofstrings,initiallyempty,ismaintainedprivatelybytheclassString.

Whentheinternmethodisinvoked,ifthepoolalreadycontainsastringequaltothisStringobjectasdeterminedbytheequals(Object)method,thenthestringfromthepoolisreturned.Otherwise,thisStringobjectisaddedtothepoolandareferencetothisStringobjectisreturned.


Itfollowsthatforanytwostringssandt,s.intern()==t.intern()istrueifandonlyifs.equals(t)istrue.

Allinall,usingStringstr="Jeff";udontmindtheThread-securityorGarbagecollectionmechanism.Stringisaniceman,treatitasalittleboypelasse.



HowtousetheString,StringBuffer,StringBuilder

Lookatthepic:



String,StringBuffer,StringBuilderimplementtheCharSequence.Buttheyaredifferent.

String

StringObjectisanon-variable.itcannotbe
changedandinthememorywhenucreateit.

forexample:

Stringstr="abc";
Stringstr1=str.substring(1);

System.out.println("str1"+str1);

#outputs:
bc


substring()methodcreatesanewStringObjectandlinksthereferenceofittostr1.Butwhen“str.substring(0)”,str1andstrbothlinktothe“abc”bytheJVM.

StringBufferStringBuilder

theyareverysimilarandtheyrvariablesofthesequenceofcharacters.Onlydifferent,theStringBufferhasthemethodswhicharesynchronizedwherenecessary.Stringbuffersaresafeforusebymultiplethreads.DifferentfromString,if
z
referstoastringbufferobjectwhosecurrentcontentsare"
start
",thenthemethodcall
z.append("le")
wouldcausethestringbuffertocontain"
startle
",whereas
z.insert(4,"le")
wouldalterthestringbuffertocontain"
starlet
".

Allinall:

Stringcanbeusedfortheconstants.



StringBuffercanbeusedforsomeoperatingmethodsinmultithreadedenvironment.like
XMLanalyze,theparametersofHTTPanalyzeetc.

StringBuildercanbeusedforHQL/SQLsplice,
JSONpackageetc.



EasyTime:PayattentiontotheaddressofString

forexample:

publicstaticvoidmain(String[]args)
{
Stringstr1=1+2+"apples";
Stringstr2="apples"+1+2;

System.out.println(str1);
System.out.println(str2);
}
#outputs:
3apples
apples12



whatwecanseefromtheresult-values.why?how?theydid.

BecausetheJAVAhandlingmechanismtotheoperator“+”.whenthereisastringintheexpression,alltheexpressiondatawillchangeitselftotheStringclass.ifthedataisanObject,itwillcallitstoStringmethod.

So,Stringstr1=1+2+"apples"justlikeStringstr1=(1+2)+"apples".thatsall.

Complexstringmanipulationusingregularexpressions

justreading!!thepart,iwillwriteinthefuture.



WritetoReader

basedon


.

Thanku!

道可道也,非恒道也。名可名也,非恒名也。无名,万物之始也;有名,万物之母也。故恒无欲也,以观其眇;恒有欲也,以观其所徼。两者同出,异名同谓。玄之又玄,众眇之门。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: