-
Illibro
-
HTML?CSS?JS?
-
Collections
-
DickBaldwinsays…Idon'tknowofanyemployerwhowantstheirprogrammerstospendtimeanddollarsreinventingtheclassicaldatastructures.Whatthoseemployersarelookingforisastaffofprogrammerswhounderstandthetradeoffsamongthedatastructures,andwhenitisappropriatetouseeachofthedifferentstructures.ItistimetoreinventthecurriculuminCS2coursesby• Encouragingtheunderstandingoftechniquesforsoftware
reuse.• Teachingwhen,why,andhoweachofthedifferent
structuresshouldbeused.• Discouragingthereinventionofthosestructures.
-
CollectionACollectionrepresentsagroupofobjectsknownasitselementsBasicoperations:intsize(),booleanisEmpty(),booleancontains(Objectelement),booleanadd(Eelement),booleanremove(Objectelement),andIteratoriterator().Methodsthatoperateonentirecollections:containsAll(Collectionc),booleanaddAll(Collectionc),booleanretainAll(Collectionc),andvoidclear().Arrayoperations(suchasObject[]toArray()andT[]toArray(T[]a)InJDK8andlater,theCollectioninterfacealsoexposesmethodsStreamstream()andStreamparallelStream(),forobtainingsequentialorparallelstreamsfromtheunderlyingcollection.
-
ConvertingamongcollectionsByconventionallgeneral-purposecollectionimplementationshaveaconstructorthattakesaCollectionargument.Thisconstructor,knownasaconversionconstructor,initializesthenewcollectiontocontainalloftheelementsinthespecifiedcollection,whateverthegivencollection'ssubinterfaceorimplementationtype.Inotherwords,itallowsyoutoconvertthecollection'stype.Suppose,forexample,thatyouhaveaCollectionc,whichmaybeaList,aSet,oranotherkindofCollection.ThisidiomcreatesanewArrayList(animplementationoftheListinterface),initiallycontainingalltheelementsinc.Listlist=newArrayList(c);JDK7orlater:Listlist=newArrayList(c);
-
CollectionsutilitiesSTATICmethodsofclassCollections:• disjoint(Collectionuno,Collectiondue)• sort(List..)• shuffle(Lista)• min(Collectionuno,…)• max(Collectionuno,…)• frequency(Collectionuno,Objecto)• binarySearch(List…)
-
Collections:interfacesvsimplementation
Interfaces
Set a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
SortedSet Set that maintains its elements in ascending order, sorted
according to the elements' \ordering or according to a Comparator
List an ordered Collection Queue
Deque
Map HashMap
SortedMap
-
TheListInterfaceAListisanorderedCollection).Listsmaycontainduplicateelements.Itincludesoperationsforthefollowing:• Positionalaccess—manipulateselementsbasedontheirnumerical
positioninthelist.Thisincludesmethodssuchasget,set,add,addAll,andremove.
• Search—searchesforaspecifiedobjectinthelistandreturnsitsnumericalposition.SearchmethodsincludeindexOfandlastIndexOf.
• Iteration—extendsIteratorsemanticstotakeadvantageofthelist'ssequentialnature.ThelistIteratormethodsprovidethisbehavior.
• Range-view—Thesublistmethodperformsarbitraryrangeoperationsonthelist.
-
TheSet
ASetisaCollectionthatcannotcontainduplicateelements.Itmodelsthemathematicalsetabstraction.
-
TheSet/SortedSetInterfaceASetthamaintainsitselementsinascendingorder,sortedaccordingtotheelements'naturalorderingoraccordingtoaComparatorprovidedatSortedSetcreationtime.InadditiontothenormalSetoperations,theSortedSetinterfaceprovidesoperationsforthefollowing:• Rangeview—allowsarbitraryrangeoperationsonthesortedset• Endpoints—returnsthefirstorlastelementinthesortedset• Comparatoraccess—returnstheComparator,ifany,usedtosorttheset
publicinterfaceSortedSetextendsSet{//Range-viewSortedSetsubSet(EfromElement,EtoElement);SortedSetheadSet(EtoElement);SortedSettailSet(EfromElement);
//EndpointsEfirst();Elast();//ComparatoraccessComparator
-
QueueinterfaceAQueueisacollectionforholdingelementsinorderofarrival.BesidesbasicCollectionoperations,queuesprovideadditionalinsertion,removal,andinspectionoperations.TheQueueinterfacefollows.publicinterfaceQueueextendsCollection{Eelement();booleanoffer(Ee);Epeek();Epoll();Eremove();}
-
Dequeinterface
Adouble-ended-queueisalinearcollectionofelementsthatsupportstheinsertionandremovalofelementsatbothendpoints.
Type of Operation First Element (Beginning
of the Deque instance) Last Element (End of
the Deque instance)
Insert addFirst(e) addLast(e)offerFirst(e) offerLast(e)
Remove removeFirst() removeLast()pollFirst() pollLast()
Examine getFirst() getLast()peekFirst() peekLast()
-
MapinterfaceAMapisanobjectthatmapskeystovalues.Amapcannotcontainduplicatekeys:Eachkeycanmaptoatmostonevalue.Itmodelsthemathematicalfunctionabstraction.TheMapinterfaceincludesmethodsfor• basicoperations(e.g.put,get,remove,containsKey,containsValue,size,andempty),
• bulkoperations(e.g.putAllandclear),• collectionviews(e.g.keySet,values).
-
SortedMapinterface
ASortedMapisaMapthatmaintainsitsentriesinascendingorder,sortedaccordingtothekeys'naturalordering,oraccordingtoaComparatorprovidedatthetimeoftheSortedMapcreation.
-
Collections:interfacesvsimplementation
Interfaces Hash table Implementations Resizable array
Implem. Tree
Implem. Linked list
Implem. Hash table + Linked
list Implem.
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Queue ArrayDeque LinkedList
Deque ArrayDeque LinkedList
Map HashMap TreeMap LinkedHashMap
-
Set/SortedSetimplementationsHashSetismuchfasterthanTreeSet(constant-timeversuslog-timeformostoperations)butoffersnoorderingguarantees.IfyouneedtousetheoperationsintheSortedSetinterface,orifvalue-orderediterationisrequired,useTreeSet;otherwise,useHashSet.You'llendupusingHashSetmostofthetime.LinkedHashSetisin“intermediate”betweenHashSetandTreeSet.Implementedasahashtablewithalinkedlistrunningthroughit,itprovidesinsertion-orderediteration(leastrecentlyinsertedtomostrecently)andrunsnearlyasfastasHashSet.
-
ListimplementationsTherearetwogeneral-purposeListimplementations—ArrayListandLinkedList.Positionalaccessrequireslinear-timeinaLinkedListandconstant-timeinanArrayList.IfyoufrequentlyaddelementstothebeginningoftheListoriterateovertheListtodeleteelementsfromitsinterior,youshouldconsiderusingLinkedList.Theseoperationsrequireconstant-timeinaLinkedListandlinear-timeinanArrayList.Mostofthetime,you'llprobablyuseArrayList.
-
MapimplementationsHashMap,TreeMap,LinkedHashMap.IfyouneedSortedMapoperationsorkey-orderedCollection-viewiteration,useTreeMap.Iifyouwantmaximumspeedanddon'tcareaboutiterationorder,useHashMap.ifyouwantnear-HashMapperformanceandinsertion-orderiteration,useLinkedHashMap.Inthisrespect,thesituationforMapisanalogoustoSet.
-
Queue– Dequeueimplementations
LinkedList,plusmanyothers.
-
Suggerimento
• NonscrivereMAIlabusinesslogicnelmain!
-
Anexampleimportjava.util.TreeSet;importjava.util.Collection;importjava.util.Iterator;publicclassAP400{publicstaticvoidmain(Stringargs[]){newWorker().doIt();}}
classWorker{publicvoiddoIt(){Collectionref=newTreeSet();Populator.fillIt(ref);Iteratoriter=ref.iterator();while(iter.hasNext()){System.out.print(iter.next());}System.out.println();}}
-
Anexample–part2classPopulator{publicstaticvoidfillIt(Collectionref){ref.add(newInteger(4));ref.add(newInteger(4));ref.add(newInteger(3));ref.add(newInteger(2));ref.add(newInteger(1));}}
Vedianchehttps://cnx.org/contents/[email protected]:BaPSYll8@6/Java4010-Getting-Started-with-
-
SynchronizationThesynchronizationwrappersaddautomaticsynchronization(thread-safety)toanarbitrarycollection.Eachofthecorecollectioninterfaceshasonestaticfactorymethod.publicstaticCollectionsynchronizedCollection(Collectionc);publicstaticSetsynchronizedSet(Sets);publicstaticListsynchronizedList(Listlist);publicstaticMapsynchronizedMap(Mapm);publicstaticSortedSetsynchronizedSortedSet(SortedSets);publicstaticSortedMapsynchronizedSortedMap(SortedMapm);
-
SynchronizationwrappersCollectionmyCollection=newLinkedList;Collectionc=Collections.synchronizedCollection(myCollection);synchronized(c){for(Typee:c)foo(e);}
-
CollectionsandStreams
Seehttps://docs.oracle.com/javase/tutorial/collections/streams/index.html
-
I/O
-
TypicalJavaI/O… Scanner s = null;
try { s = new Scanner(
new BufferedReader( new FileReader("xanadu.txt”)));
while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } }
Bydefault,ascanneruseswhitespacetoseparatetokens.Whitespacecharactersincludeblanks,tabs,andlineterminators.
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
-
I/OTable Byte Based Character Based
Input Output Input Output
Basic InputStream OutputStreamReader Writer
InputStreamReader OutputStreamWriter
Arrays ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
FilesFileInputStream FileOutputStream
FileReader FileWriterRandomAccessFile RandomAccessFile
Pipes PipedInputStream PipedOutputStream PipedReader PipedWriter
Buffering BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Filtering FilterInputStream FilterOutputStream FilterReader FilterWriter
ParsingPushbackInputStream PushbackReader
StreamTokenizer LineNumberReader
Strings StringReader StringWriter
Data DataInputStream DataOutputStream
Data - Formatted PrintStream PrintWriter
Objects ObjectInputStream ObjectOutputStream
Utilities SequenceInputStream
-
ReadingfromfilePathfile=...;try(InputStreamin=Files.newInputStream(file);BufferedReaderreader=newBufferedReader(newInputStreamReader(in))){Stringline=null;while((line=reader.readLine())!=null){System.out.println(line);}}catch(IOExceptionx){System.err.println(x);}
Toopenafileforreading,youcanusethenewInputStream(Path,OpenOption...)method.Thismethodreturnsanunbufferedinputstreamforreadingbytesfromthefile
-
Writingtofileimportstaticjava.nio.file.StandardOpenOption.*;importjava.nio.file.*;importjava.io.*;publicclassLogFileTest{publicstaticvoidmain(String[]args){//Convertthestringtoabytearray.Strings="HelloWorld!";bytedata[]=s.getBytes();Pathp=Paths.get("./logfile.txt");try(OutputStreamout=newBufferedOutputStream(Files.newOutputStream(p,CREATE,APPEND))){out.write(data,0,data.length);}catch(IOExceptionx){System.err.println(x);}}}
ThenewOutputStreammethodopensorcreatesafileforwritingbytesandreturnsanunbufferedoutputstream.
-
java.nio.file:fileproperties
Pathfile=...;booleanisRegularExecutableFile=Files.isRegularFile(file)&Files.isReadable(file)& Files.isExecutable(file);
-
FormattingpublicclassRoot2{publicstaticvoidmain(String[]args){inti=2;doubler=Math.sqrt(i);System.out.format("Thesquarerootof%dis%f.%n",i,r);}}Thesquarerootof2is1.414214.
publicclassFormat{publicstaticvoidmain(String[]args){System.out.format("%f,%1$+020.10f%n",Math.PI);}}3.141593,+00000003.1415926536
-
PathYoucaneasilycreateaPathobjectbyusingoneofthefollowinggetmethodsfromthePaths(notetheplural)helperclass:Pathp1=Paths.get("/tmp/foo");Pathp2=Paths.get(args[0]);Pathp3=Paths.get(URI.create("file:///Users/joe/FileTest.java"));Thiscreates/u/joe/logs/foo.logassumingyourhomedirectoryis/u/joe,orC:\joe\logs\foo.logifyouareonWindows.Pathp5=Paths.get(System.getProperty("user.home"),"logs","foo.log");
-
Watchingadirectoryforchange
https://docs.oracle.com/javase/tutorial/essential/io/notification.html
-
Seetutorial
• https://docs.oracle.com/javase/tutorial/essential/io/index.html
-
Database
-
JDBCTutorial
https://docs.oracle.com/javase/tutorial/jdbc/overview/index.htmlhttps://docs.oracle.com/javase/tutorial/jdbc/basics/index.html
-
Concurrency
-
Concurrency
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
-
IDEforJava
-
AccordingtoJavaWorld…ThreeIDEsarethemajorones:• IntellijIDEA• Eclipse• Netbeans
https://www.javaworld.com/article/3114167/development-tools/choosing-your-java-ide.html
-
ItendtorecommendthatnewJavacodersnotuseEclipse.Eventhoughit'sthemostpopularJavaIDE,ithasthesteepestlearningcurveandthemostpotentialforconfusion,bothindailyuseandwhenmaintainingtheIDE.
FornewJavacoderswithoutabudgetfortools,thechoiceisbetweenNetBeansandIntelliJIDEACommunityEdition.Ifyou'recodingJavaserverswithlittleornobudgetfortools,thenNetBeansmightbethebetterchoice
-
BlueJVantaggi:IntegrazioneconUML!
Svantaggioprincipale:mancalaautocompletion
-
BlueJVantaggi:visualizzazioneimmediatadelladocumentazionegenerata
Svantaggi:noversioning,norefactoring,nointegratedservers…
-
Netbeansbasics
Handson:1) Createproject2) Codecompletion3) Runproject–runfile4) Rebuild
-
Netbeansimportantelements
1) MaximizeWindow–ResetWindows2) Projectproperties3) Configuration
-
Netbeans–interestingfeatures1) Sourceformat2) Refactor3) Codeinspection4) Navigate5) Findusages6) Insertcode7) debug