Tải bản đầy đủ - 0 (trang)
Chapter 5.  The Java Platform

Chapter 5.  The Java Platform

Tải bản đầy đủ - 0trang

5.1.JavaPlatformOverview

Table5-1summarizesthekeypackagesoftheJavaplatform

thatarecoveredinthisbook.

Table5-1.KeypackagesoftheJavaplatform

Package



Description



java.io



Classesandinterfacesforinputandoutput.Althoughsomeofthe

classesinthispackageareforworkingdirectlywithfiles,mostare

forworkingwithstreamsofbytesorcharacters.



java.lang



Thecoreclassesofthelanguage,suchasString,Math,System,

THRead,andException.



java.lang.annotation



AnnotationtypesandothersupportingtypesfortheJava5.0

annotationfeature.(SeeChapter4.)



SupportclassesforJavavirtualmachineinstrumentationagents,

java.lang.instrument whichareallowedtomodifythebytecodeoftheprogramtheJVM

isrunning.NewinJava5.0.



java.lang.management



AframeworkformonitoringandmanagingarunningJavavirtual

machine.NewinJava5.0.



java.lang.ref



Classesthatdefineweakreferencestoobjects.Aweakreference

isonethatdoesnotpreventthereferentobjectfrombeing

garbage-collected.



java.lang.reflect



ClassesandinterfacesthatallowJavaprogramstoreflecton

themselvesbyexaminingtheconstructors,methods,andfieldsof

classes.



java.math



Asmallpackagethatcontainsclassesforarbitrary-precision

integerandfloating-pointarithmetic.



java.net



Classesandinterfacesfornetworkingwithothersystems.



java.nio



BufferclassesfortheNewI/OAPI.AddedinJava1.4.



java.nio.channels



Channelandselectorinterfacesandclassesforhigh-performance,

nonblockingI/O.



java.nio.charset



CharactersetencodersanddecodersforconvertingUnicode

stringstoandfrombytes.



java.security



Classesandinterfacesforaccesscontrolandauthentication.This

packageanditssubpackagessupportcryptographicmessage

digestsanddigitalsignatures.



java.text



Classesandinterfacesforworkingwithtextininternationalized

applications.



java.util



Variousutilityclasses,includingthepowerfulcollectionsframework

forworkingwithcollectionsofobjects.



java.util.concurrent



Threadpoolsandotherutilityclassesforconcurrentprogramming.

Subpackagessupportatomicvariablesandlocks.NewinJava5.0.



java.util.jar



ClassesforreadingandwritingJARfiles.



java.util.logging



Aflexibleloggingfacility.AddedinJava1.4.



java.util.prefs



AnAPItoreadandwriteuserandsystempreferences.Addedin

Java1.4.



java.util.regex



Textpatternmatchingusingregularexpressions.AddedinJava

1.4.



java.util.zip



ClassesforreadingandwritingZIPfiles.



javax.crypto



Classesandinterfacesforencryptionanddecryptionofdata.



javax.net



Definesfactoryclassesforcreatingsocketsandserversockets.

Enablesthecreationofsockettypesotherthanthedefault.



javax.net.ssl



ClassesforencryptednetworkcommunicationusingtheSecure

SocketsLayer(SSL).



Thetop-levelpackagefortheJAASAPIforauthenticationand

javax.security.auth authorization.Varioussubpackagesholdmostoftheactual

classes.AddedinJava1.4.



javax.xml.parsers



Ahigh-levelAPIforparsingXMLdocumentsusingpluggableDOM

andSAXparsers.



Ahigh-levelAPIfortransformingXMLdocumentsusinga

pluggableXSLTtransformationengineandforconvertingXML

javax.xml.transform documentsbetweenstreams,DOMtrees,andSAXevents.

SubpackagesprovidesupportforDOM,SAXandstream

transformations.AddedinJava1.4.



Table5-1doesnotlistallthepackagesintheJavaplatform,

onlythemostimportantofthosedocumentedinthisbook.Java

alsodefinesnumerouspackagesforgraphicsandgraphicaluser

interfaceprogrammingandfordistributed,orenterprise,

computing.ThegraphicsandGUIpackagesarejava.awtand

javax.swingandtheirmanysubpackages.Thesepackagesare

documentedinJavaFoundationClassesinaNutshellandJava

Swing,bothfromO'Reilly.TheenterprisepackagesofJava

includejava.rmi,java.sql,javax.jndi,org.omg.CORBA,

org.omg.CosNaming,andalloftheirsubpackages.These

packages,aswellasseveralstandardextensionstotheJava

platform,aredocumentedinJavaEnterpriseinaNutshell

(O'Reilly).



5.2.Text

Mostprogramsmanipulatetextinoneformoranother,andthe

Javaplatformdefinesanumberofimportantclassesand

interfacesforrepresenting,formatting,andscanningtext.The

sectionsthatfollowprovideanoverview.



5.2.1.TheStringClass

Stringsoftextareafundamentalandcommonlyuseddata

type.InJava,however,stringsarenotaprimitivetype,like

char,int,andfloat.Instead,stringsarerepresentedbythe

java.lang.Stringclass,whichdefinesmanyusefulmethods

formanipulatingstrings.Stringobjectsareimmutable:oncea

Stringobjecthasbeencreated,thereisnowaytomodifythe

stringoftextitrepresents.Thus,eachmethodthatoperateson

astringtypicallyreturnsanewStringobjectthatholdsthe

modifiedstring.

Thiscodeshowssomeofthebasicoperationsyoucanperform

onstrings:



//Creatingstrings

Strings="Now";//Stringobjectshaveaspecia

Stringt=s+"isthetime.";//Concatenatestringswith+o

Stringt1=s+""+23.4;//+convertsothervaluestos

t1=String.valueOf('c');//Getstringcorrespondingto

t1=String.valueOf(42);//Getstringversionofintege

t1=object.toString();//Convertobjectstostringsw



//Stringlength

intlen=t.length();//Numberofcharactersinthe

//Substringsofastring



Stringsub=t.substring(4);//Returnschar4toend:"ist

sub=t.substring(4,6);//Returnschars4and5:"is"

sub=t.substring(0,3);//Returnschars0through2:"

sub=t.substring(x,y);//Returnscharsbetweenposx

intnumchars=sub.length();//Lengthofsubstringisalway



//Extractingcharactersfromastring

charc=t.charAt(2);//Getthe3rdcharacteroft:

char[]ca=t.toCharArray();//Convertstringtoanarrayo

t.getChars(0,3,ca,1);//Put1st3charsoftintoca

//Caseconversion

Stringcaps=t.toUpperCase();//Converttouppercase

Stringlower=t.toLowerCase();//Converttolowercase



//Comparingstrings

booleanb1=t.equals("hello");//Returnsfalse:strin

booleanb2=t.equalsIgnoreCase(caps);//Case-insensitivecom

booleanb3=t.startsWith("Now");//Returnstrue

booleanb4=t.endsWith("time.");//Returnstrue

intr1=s.compareTo("Pow");//Returns<0:scomes

intr2=s.compareTo("Now");//Returns0:stringsa

intr3=s.compareTo("Mow");//Returns>0:scomes

r1=s.compareToIgnoreCase("pow");//Returns<0(Java1.



//Searchingforcharactersandsubstrings

intpos=t.indexOf('i');//Positionoffirst'i':4

pos=t.indexOf('i',pos+1);//Positionofthenext'i':

pos=t.indexOf('i',pos+1);//Nomore'i'sinstring,re

pos=t.lastIndexOf('i');//Positionoflast'i'inst

pos=t.lastIndexOf('i',pos-1);//Searchbackwardsfor'i'f



pos=t.indexOf("is");//Searchforsubstring:retu

pos=t.indexOf("is",pos+1);//Onlyappearsonce:returns

pos=t.lastIndexOf("the");//Searchbackwardsforastr

Stringnoun=t.substring(pos+4);//Extractwordfollowing"th



//Replaceallinstancesofonecharacterwithanothercharacte

Stringexclaim=t.replace('.','!');//Worksonlywithchars

//Stripblankspaceoffthebeginningandendofastring

Stringnoextraspaces=t.trim();



//Obtainuniqueinstancesofstringswithintern()

Strings1=s.intern();//Returnss1equaltos

Strings2="Now";//Stringliteralsareautomatic

booleanequals=(s1==s2);//Nowcantestforequalitywit



5.2.2.TheCharacterClass

Asyouknow,individualcharactersarerepresentedinJavaby

theprimitivechartype.TheJavaplatformalsodefinesa

Characterclass,whichcontainsusefulclassmethodsfor

checkingthetypeofacharacterandforconvertingthecaseof

acharacter.Forexample:



char[]text;//Anarrayofcharacters,initializedsomewhere

intp=0;//Ourcurrentpositioninthearrayofcharacter

//Skipleadingwhitespace

while((p
//Capitalizethefirstwordoftext

while((p
text[p]=Character.toUpperCase(text[p]);

p++;

}



5.2.3.TheStringBufferClass



SinceStringobjectsareimmutable,youcannotmanipulatethe

charactersofaninstantiatedString.Ifyouneedtodothis,use

ajava.lang.StringBufferorjava.lang.StringBuilder

instead.Thesetwoclassesareidenticalexceptthat

StringBufferhassynchronizedmethods.StringBuilderwas

introducedinJava5.0andyoushoulduseitinpreferenceto

StringBufferunlessitmightactuallybemanipulatedby

multiplethreads.Thefollowingcodedemonstratesthe

StringBufferAPIbutcouldbeeasilychangedtouse

StringBuilder:

//Createastringbufferfromastring

StringBufferb=newStringBuffer("Mow");



//GetandsetindividualcharactersoftheStringBuffer

charc=b.charAt(0);//Returns'M':justlikeString.c

b.setCharAt(0,'N');//bholds"Now":can'tdothatwi



//AppendtoaStringBuffer

b.append('');//Appendacharacter

b.append("isthetime.");//Appendastring

b.append(23);//Appendanintegeroranyother



//InsertStringsorothervaluesintoaStringBuffer

b.insert(6,"n't");//bnowholds:"Nowisn'tthetim



//Replacearangeofcharacterswithastring(Java1.2andla

b.replace(4,9,"is");//Backto"Nowisthetime.23"



//Deletecharacters

b.delete(16,18);//Deletearange:"Nowisthetim

b.deleteCharAt(2);//Delete2ndcharacter:"Noisth

b.setLength(5);//Truncatebysettingthelength:



//Otherusefuloperations

b.reverse();//Reversecharacters:"sioN"

Strings=b.toString();//Convertbacktoanimmutablest



s=b.substring(1,2);//Ortakeasubstring:"i"

b.setLength(0);//Erasebuffer;nowitisreadyf



5.2.4.TheCharSequenceInterface

AsofJava1.4,boththeStringandtheStringBufferclasses

implementthejava.lang.CharSequenceinterface,whichisa

standardinterfaceforqueryingthelengthofandextracting

charactersandsubsequencesfromareadablesequenceof

characters.Thisinterfaceisalsoimplementedbythe

java.nio.CharBufferinterface,whichispartoftheNewI/O

APIthatwasintroducedinJava1.4.CharSequenceprovidesa

waytoperformsimpleoperationsonstringsofcharacters

regardlessoftheunderlyingimplementationofthosestrings.

Forexample:



/**

*ReturnaprefixofthespecifiedCharSequencethatstartsat

*characterofthesequenceandextendsupto(andincludes)t

*occurrenceofthecharactercinthesequence.Returnsnull

*notfound.smaybeaString,StringBuffer,orjava.nio.Char

*/

publicstaticCharSequenceprefix(CharSequences,charc){

intnumChars=s.length();//Howlongisthesequen

for(inti=0;i
if(s.charAt(i)==c)//Ifwefindc,

returns.subSequence(0,i+1);//thenreturntheprefix

}

returnnull;//Otherwise,returnnull

}



5.2.5.TheAppendableInterface

AppendableisaJava5.0interfacethatrepresentsanobject

thatcanhaveacharoraCharSequenceappendedtoit.

ImplementingclassesincludeStringBuffer,StringBuilder,

java.nio.CharBuffer,java.io.PrintStream,and

java.io.Writerandallofitscharacteroutputstream

subclasses,includingPrintWriter.Thus,theAppendable

interfacerepresentsthecommonappendabilityofthetext

bufferclassesandthetextoutputstreamclasses.Aswe'llsee

below,aFormatterobjectcansenditsoutputtoany

Appendableobject.



5.2.6.StringConcatenation

The+operatorconcatenatestwoStringobjectsoroneString

andonevalueofsomeothertype,producinganewString

object.Beawarethateachtimeastringconcatenationis

performedandtheresultstoredinavariableorpassedtoa

method,anewStringobjecthasbeencreated.Insome

circumstances,thiscanbeinefficientandcanresultinpoor

performance.Itisespeciallyimportanttobecarefulwhendoing

stringconcatenationwithinaloop.Thefollowingcodeis

inefficient,forexample:



//Inefficient:don'tdothis

publicStringjoin(Listwords){

Stringsentence="";

//EachiterationcreatesanewStringobjectanddiscards

for(Stringword:words)sentence+=word;

returnsentence;

}



Whenyoufindyourselfwritingcodelikethis,switchtoa

StringBufferoraStringBuilderandusetheappend()

method:

//Thisistherightwaytodoit

publicStringjoin(Listwords){

StringBuildersentence=newStringBuilder();

for(Stringword:words)sentence.append(word);

returnsentence.toString();

}



Thereisnoneedtobeparanoidaboutstringconcatenation,

however.Rememberthatstringliteralsareconcatenatedbythe

compilerratherthantheJavainterpreter.Also,whenasingle

expressioncontainsmultiplestringconcatenations,theseare

compiledefficientlyusingaStringBuilder(orStringBuffer

priortoJava5.0)andresultinthecreationofonlyasinglenew

Stringobject.



5.2.7.StringComparison

Sincestringsareobjectsratherthanprimitivevalues,they

cannot,ingeneral,becomparedforequalitywiththe==

operator.==comparesreferencesandcandetermineiftwo

expressionsevaluatetoareferencetothesamestring.It

cannotdetermineiftwodistinctstringscontainthesametext.

Todothat,usetheequals()method.InJava5.0youcan

comparethecontentofastringtoanyotherCharSequencewith

thecontentEquals()method.

Similarly,therelationaloperatorsdonotworkwith

strings.Tocomparetheorderofstrings,usethecompareTo()

method,whichisdefinedbytheComparableinterface



andisillustratedinthesamplecodeabove.Tocomparestrings

withouttakingthecaseofthelettersintoaccount,use

compareToIgnoreCase().

NotethatStringBufferandStringBuilderdonotimplement

Comparableanddonotoverridethedefaultversionsofequals(

)andhashCode()thattheyinheritfromObject.Thismeans

thatitisnotpossibletocomparethetextheldintwo

StringBufferorStringBuilderobjectsforequalityorfor

order.

Oneimportant,butlittleunderstoodmethodoftheStringclass

isintern().Whenpassedastrings,itreturnsastringtthat

isguaranteedtohavethesamecontentass.What'simportant,

though,isthatforanygivenstringcontent,italwaysreturnsa

referencetothesameStringobject.Thatis,ifsandtaretwo

Stringobjectssuchthats.equals(t),then:

s.intern()==t.intern()



Thismeansthattheintern()methodprovidesawayofdoing

faststringcomparisonsusing==.Importantly,stringliteralsare

alwaysimplicitlyinternedbytheJavaVM,soifyouplanto

compareastringsagainstanumberofstringliterals,youmay

wanttointernsfirstandthendothecomparisonwith==.

ThecompareTo()andequals()methodsoftheStringclass

allowyoutocomparestrings.compareTo()basesits

comparisononthecharacterorderdefinedbytheUnicode

encodingwhileequals()definesstringequalityasstrict

character-by-characterequality.Thesearenotalwaystheright

methodstouse,however.Insomelanguages,thecharacter

orderingimposedbytheUnicodestandarddoesnotmatchthe

dictionaryorderingusedwhenalphabetizingstrings.InSpanish,

forexample,theletters"ch"areconsideredasingleletterthat



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5.  The Java Platform

Tải bản đầy đủ ngay(0 tr)

×