1. Trang chủ
  2. » Công Nghệ Thông Tin

head first java second edition phần 9 ppsx

68 476 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 3,2 MB

Nội dung

16 collections and generics Data structures Sorting is a snap in Java You have all the tools for collect ing and manipulating your data without having to write your own sort algorithms (unless you're reading this right now sitting in your Computer Science 101 class,in which case, trust us-you are SO going to be writing sort code while the rest of us Just call a method In the Java API) The Java Collections Framework has a data structure that should work for virtually anything you'll ever need to Want to keep a list that you can easily keep adding to? Want to find something by name?Want to create a list that automatically takes out all the duplicates? Sort your co-workers by the number of times they've stabbed you in the back? Sort your pets by number of tricks learned? It 's all here t his is a new chapter 529 sorting a list fracki"Q SOt1g popularity 0., your jukebox Congratulations on your new j ob managing the automated jukebox system at Lou's Diner There's no Java inside the jukebox itself, but each time someone plays a song, the song data is appended to a simple text file Your job is to manage the data to track song popularity, generate reports, and manipulate the playlists, You're not writing the entire ap~ome of the other software developer/ waiters are involved as well but you're responsible for managing and sorting the data inside the java app And since Lou has a thing against databases, this is strictly an in-memory data collection All you get is the file the jukebox keeps adding to Your job is to take it from there You've already figured out how to read and parse the file, and so far you've been storing the data in an ArrayList SongLlst txt Pink Moon/Nick Drake Somersault/Zero Shiv& Moon/Prem Joshua Circles/BT Deep Channel/Afro Celts Passenger/Headmix Listen/Tahiti 80 Challenge #1 Sort the songs in alphabetical order You have a list of songs in a file where each line represents one song, and the title and artist are separated with a forward slash So it should be simple to parse the line, and put all the songs in an ArrayList Your boss cares only about the song titles, so for now you can simply make a list thatjust has the song titles But you can see that the list is not in alphabetical order what can you do? You know that with an Arrayl.ist, the elements are kept in the order in which they were inserted into the list, 50 putting them in an ArrayList won't take care of alphabetizing them, unless maybe there's a sortj) method in the ArrayList class? 530 chapter 16 collections with generics Here's what you have so far; without the sort: impo4t java.util.*; import java.io.*; pUblic class Jukeboxl ArrayList songList : new ArrayList() i public static void main (String () args I new Jukeboxl() ge ( ) ; public void go() I ~ getSongs(); System.out.println(songList); 1: Y'tilO the t 'lle il"d Not.hi,,~ syet."lill he e J~oo ~a eat" \il'le· t.a\\ -\:.he ilod$of ~O '" void gatSonqa () try { File file new File("SongList.txt H ) ; BufferedReader reader = new BufferedReader(new FileReader(file»: String line = null; whi Le « line= r e ade r , readLine () ! = null) ( addSong(line); catch(Exception ex) ( ex.printStackTrace(); r void addSong(Strinq lineToParse) I String (1 tokens = lineToParse split ("/") ; songList.add(tokens[Ol); The tiddSon j th "'eiJ od \\/orh (J -J Ln e I/O thdpU JIISf likl! i~1! /.I " ~"t; both th tifl yOk b k "i'l !hi> USl all ~ ~ dcm! that it keeps your data sorted r wonder if r should be using a TreeSet inste.ad of an ArrayList o o ArrayLisf is.!Q1the ot1ly collectiot1 Although ArrayList is the one you'll use most often, there are others for special occasions Some of the key collection classes include: D 't 'NcKY'f C1nOl>t b-'tl~ ~ese oth~ Ol'Ies Of' ~ TreeSet t.o \eClyY\ '\I il'l-to yiaht "0 · We ~c ~e o~il~ a \iH:le C1~' ,1._ Keeps the elements sorted and prevents duplicates HashMap Let's you store and access elements as namelvalue pairs ~ L1nkedLlst Designed togive better performance when you insert ordelete elements from the middle ofthe collection (In practice, an ArrayUst isstill usually what you want.) ~ HashSet Prevents duplicates inthe collection, and given an element, can find that element in the collection qulcldy ~ L1nkedHashMap Like a regular HashMap, except it can remember the order in which elements (name/value pairs) were Inserted, orit can be configured to remember the order In which elements were last accessed you are here ~ 533 Collectlons.sortO You could use a freeSet Or you could use the Coliectiotts.sortCl tttethod lfyou put all the Strings (the song titles) into a TreeSet instead of an ArrayList, the Strings would automatically land in the right place, alphabetically sorted Whenever you printed the list, the elements would always come out in alphabetical order And that's great when you need a set (we'll talk about sets in a few minutes) or when you know that the list must au.vays stay sorted alphabetically On the other hand, if you don't need the list to stay sorted TreeSet might be more expensive than you need-every time you insert into a Treeset; the TreeSet has to take the time to figure out where in 1M tree the new element must go With ArrayList, inserts can be blindingly fast because the new element just goes in at the end Q: lava.utll.collections public static void copy{Ust destination List source) public static Ust public static void flll(List IIstToFill, Object objToFillltWrth) public static Int trequency(Collection c, Object 0) public static void reverse{Ust list) public static void rotate(Ust list, lnt distance) public static void shuffle(Ust list) But you CAN add something to an ArrayList at a specific Index Instead of just at the end-there's an overloaded addll method that takes an Int along with the element to add So wouldn'fft be slower than Inserting at the end1 A: emptyUst() ~ sOrt{L\st listV ;~ II" Ohiect oIdVal, Object newVal) public static boole public static /I many more met -~ Yes, It's slower to insert something in an ArrayLlst somewhere other than at the end So using the verloaded add(lndex, element) method doesn't work as qui ckly as calling the add(element)-which puts the added eleme nt at the end But most of the time you use ArrayLists, you won 't need to put something at a specific Index .ij",,,,,,, !here IS a sor!() Meihod 1ft !he Collet-t;ofts tlass I! hkes a Lis!' and' Slftte ArrayList i"'ple_e i.s !he Lis! t er ate, ArrayLis! IS-A Lis! Thanks !o polyMorphisM, y~ tan pass a ~rayList to a Me!hod d , to ta et ared Ice List Q: I see there's a L1nkedllst class, so wouldn't that be better for doing Inserts somewhere In the middle1 At least if I remember my Data Structures class from college A: Yes, good spot The LinkedLlst can be quicker when you Insert or remove something from the middle, but for most applications, the difference between middle inserts Into a Linkedllst and ArrayList is usually not enough to care about unless you're dealing with a huge number of elements We'll look more at L1nkedLlst In a few minutes 534 chapter 16 + I- collectlons with generics Addit1g Coliectiot1s.sortU to the Jukebox code impo r t j a va u t i l * ; import java i o T ; The Collections.sortO lllethod sorts a list of pub l i c c l a s s J u keb oxl ArrayList songList = new ArrayList(); pub lic s t a t i c vo i d ma i n (St ri ng [] a r gs) ne w Jukebox ( ) go (); pub lic voi d got) ge r- Song s () ; StriPgs alphabetically ( r 1t.aVt CoI\et:b~ System out p ri n t l n (s o n g Li st ) ; ~ ~~~et\ the tI~ dirtt.ky, ~he rillhi patkd e ll:s) e sfr~ Yes it k_~ To compile all the java files in the com.headfirstjava package, use: %javac -d /classes cam/beadfirstjava/*.java to piles ev(;'ry / ' ( file ' · 'I' UlIS SOlorte \Ava> d,ret.U>ry r: Running your code com com %cd MyProject/classes %java cam.headfirstjava.PackaqeExeroise headf1f$f/8 heacffl IOIlOl 10 no J' 0110 001 10 001 01 PackagaExercl8&.class 590 chapter 17 PackageExe~S8~ava package, jars and deployment fhe dflag is eve" cooler tha" we said Compiling with the -d £lag is wonderful because not only does it let you send your compiled class files into a directory other than the one where the source file is, but it also knows to pllt the class into the correct directory structure for the package the class is in But it gets even better! Let's say that you have a nice directory structure all set up for your source code But you haven't set up a matching directory structure for your classes directory Not a problem! Compiling with -d tells the compiler to not just put your classes into correct directory tree, but to the directories if they don't ~: Itried to cd Into the directory where my main class was, but now the JVM says It can't find my c1assl But It's rightTHERE In the current directoryl A: 'ld com Once your class is in a package, you can't call it by its 'short' name You MUST specify, at the command -line, the fullyqualified name of the class whose mainO method you want to run But since the fully-qualified name Includes the package structure, Java insists that the class be in a matching directory structure So if at the command-line you say: %java com.foo.Book the JVM will look in its current di rectory (and the rest of Its classpath), for a directory named "corn: It will not look for a class named Boole until It has found a directory nomed "com" with a directory Inside named ufoo': On Iy PackageExercrse.java The -d flag tells the complier, "Put the class into Its package directory structure, using the class specKled after the -d as the root directory But If the directories aren't there, create them first and then put the class then will the JVM accept that its found the correct Book class If it finds a Book class anywhere else, it assumes the class isn't in the right structure, even if it isl The JVM won't for example, look back up the directory tree to saY,"Oh,1 can see that above us is a directory named com, so this must be the right package " In the right place!" you ar e here ~ 591 JARs and packages Makit1g at1 executable JAR with packages When your class is in a package, the package directory structure must be inside theJAR! You can't just pop your classes in the JAR the waywe did pre-packages And you must be sure that you don't include any other directories above your package The first directory of your package (usually com) must be the first directory within the JAR! If you were to accidentally include the directory above the package (e.g the "classes" directory), theJAR wouldn't work correctly Making an executable ,JAR • Make sure all of your class files are within the correct package structure, under the classes directory toll 0' 10UII ' IhelldtIn:tfM• ·· • ~ll: ",0\ ·,u Create a manifest txt file that states which class has the mainO method, and be sure to use the fully-qualified class namel manl1ast.lxt Make text file named manifest.txt that has a single line: Main-Class: com.headfirstjava.PackaqaExercise Put the manifest tile into the classes directory • Run the Jar tool to create aJAR file that contains the package directories plus the manifest The only thing you need to include is the 'com' directory, and the entire package (and all classes) will go into the JAR t.~ is ~t, AI\ '1~ ~"~ oAI1 ~d t.0fP' 592 chapter 17 manifest.txt V'" I ' .t ~et tvt, f\:),i\l,~ '" 'Sed MyProject/claasea %jar -cvm£ o,y tot packEx.jar - com I "Iou II _I t I pcdcEx.jor PaclalgeExerclM.dua package, jars and deployment So where did the tMat1ifest file go? Why don't we look inside theJAR and find out? From the command-line, the jar tool can more thanjust create and run a JAR You can extract the contents of aJAR (just like 'unzipping' or 'unrarring') Imagine you've put the packExjar into a directory named Skyler; jar commands for listing and extracting G) List the contents of aJAR % jar ' McrA./NF I -' com ~ _I headflrstjavl MANIFEST.MF IO\ Ul LO lib ' ~ \I t:l 00\ 1~ @ Extract the contents of Q JAR (l.e unJar) % cd Skyler % jar -xf packEx.jar 00 \ 01 PackageExerclse.c1ass META-INF stands for 'meta information' The jar tool creates MANIFEST.MF the META-INF directory as well as the MANIFEST.MF file Tt also takes the contents of your manifest file, and puts it into the MANIFEST.MF file So, your manifest file doesn't go into the JAR, but the contents of it are put into the 'real' manifest (MANIFEST.MF) yo u are her e ~ 593 organizing your classes Given the package/directory structure In this picture,figure out what you should type at the command-line to compile, ru n, create a JAR, and execute a JAR Assume we're using the standard where the package dIrectory structure starts just below source and classes In other words, the source and classes directories are not part of the package manlfesttxt Compile: %cd source %javac COWl _ COWl Run: 1CIUO lO UO'J ' %cd • U • _lO , Foot.class _ %java _ Foof.java C~Qte %cd Q JAR _ , Execute aJAR 'cd _ %_ Bonus question: What's wrong with the package name? 594 chap ter 17 package, jars and deployment Q.: What happens If you try • Organize your project so that your source code and class files are not in the same directory the end-user doesn't have Java Installed? • Astandard organization structure is to create a project directory, and then put a source directory and a classes directory inside the project directory A: • Organizing your classes into packages prevents naming collisions with other classes if you prepend your reverse domain name on to the front of a class name • To put a class inapackage, put apackage statement atthe top ofthe source code file, before any import statements: to run an uec:utable JAR and Nothing will run, since without a JVM,Java code can't run The end-user must have Java Installed Q: pac:kage com wi cJcedlysmart; How can I g@t Java installed on the end-user's machine? Ideally, you can create a custom Installer and distribute It along with your application Several companies offer Installer programs ranging from simple to ext remely powerlu I An In staIler program could, for example, detect whether or not the end-user has an approproprlate version of Java Installed, and If not, Install and conflgure Java before Installing your application Instalishleld,lnstaIlAnywhere, and DeployDlrector all offer Java Installer solutions Another cool thing about some of the Installer programs Is that you can even make a deployment CD-ROM that Includes installers for all major Java platforms, so one CD to rule them all If the user's running on Solarls, for example, the Solarls verslo n of Java is insta lied On Windows, the Windows, verslon, etc If you have the bud get, this is by far the easiest way for your end-users to get the right version of Java Installed and conflgured • To be inapackage, a class must be in a directory structure thet exactly matches the package structure For a class, com.wlckedlysmarlFoo the Foo class must be in a directory named wickedlysmart which Is in a directory named com • To make your compiled dass land inthe correct package directory structure under the classes directory, use the -d compiler flag: % cd source -d / claues aom/wicJcedlysmart/l1'oo java % javac • To run your code, cd to the classes directory, and give the fully-quallfied name ofyour class: cd classes % java com.wickedlyamart.l1'oo • You can bundle your classes into JAR (Java ARchive) flies JAR isbased on the pkzip fonnal • You can make an executable JAR file byputting amanifest Into the JAR that states which class has the malnO method To create amanifest file, make a text file with an entry like the following (for example): Main-Class: com.wicJcedlysmart.FOO • Be sure you hitthe return key atter typing the Main-elass line, oryour manifest file may not work • To create a JAR file type: jar -cvfm manifest txt MyJar jar com • The entire package directory structure (and only the directories matching the package) must be Immediately Inside the JAR file • To run an executable JAR file, type: java -jar MyJar jar you are here 595 wouldn't it be dreamy 596 chapler 17 package, jars and deployment Executable Jar Web Start 100% Local 100% Remote Java Web Start With Java Web Start (JWS), your application is launched for the first time from a Web browser (get it? Web Starf) but it runs as a stand-alone application (well, almost), without the constraints of the browser And once it's downloaded to the end-user's machine (which happens the first time the user accesses the browser link that starts the download), it stays there Java Web Start is, among other things, a small Java program that lives on the client machine and works much like a browser plug-in (the way, say, Adobe Acrobat Reader opens when your browser gets a pdf file) ThisJava program is called the Java Web Start 'helper app', and its key purpose is to manage the downloading, updating, and launching (executing) of yOUTJWS apps, WhenJWS downloads your application (an executableJAR), it invokes the main method for your app After that, the end-user can launch your application directory from the JWS helper app without having to go back through the Web page link End-users launch aJava Web Start app by clicling on a lin1 in a Web page But once the apr downloads it runs outside the browser, just like any other stand-alone Java application In fact, a Java Web Start app is just an executable JAR that's distributed over the Web But that's not the best part The amazing thing aboutJWS is its ability to detect when even a small part of application (say, a single class file) has changed on the server, and-without any end-user intervention-download and integrate the updated code There's still an issue , of course, like how does the end-user getJava and java Web Start? They need both-Java to run the app, andJava Web Stan (a small Java application itself) to handle retrieving and launching the app But even tluu has been solved You can set things up so that if your end-users don't haveJWS they can download it from Sun And if they have JWS, but their version ofJava is out-of-date (because you've specified in yourJWS app that you need a specific version ofJava), the Java Standard Edition can be downloaded to the end-user machine Best of all, it's simple to use You can serve up aJWS app much like any other type of Web resource such as a plain old HTML page or a JPEG image You set up a Web (HTML) page with a link to your JWS application, and you're in business In the end, yourJWS application isn't much more than an executable JAR that end-users can download from the Web you are he re ~ 597 ... difference that''s making the compiler fail? %javac Jukebox3 .java JukeboK3 java: 15 : cannot find symbol symbol method sort (java util.ArrayList

Ngày đăng: 12/08/2014, 19:20

TỪ KHÓA LIÊN QUAN