Apress beginning java 8 language features

690 1.1K 0
Apress beginning java 8 language features

Đ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

For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them Contents at a Glance About the Author��������������������������������������������������������������������������������������������������������������� xxi About the Technical Reviewers��������������������������������������������������������������������������������������� xxiii Acknowledgments������������������������������������������������������������������������������������������������������������ xxv Foreword������������������������������������������������������������������������������������������������������������������������ xxvii Introduction��������������������������������������������������������������������������������������������������������������������� xxix ■■Chapter 1: Annotations������������������������������������������������������������������������������������������������������1 ■■Chapter 2: Inner Classes�������������������������������������������������������������������������������������������������41 ■■Chapter 3: Reflection�������������������������������������������������������������������������������������������������������75 ■■Chapter 4: Generics�������������������������������������������������������������������������������������������������������103 ■■Chapter 5: Lambda Expressions������������������������������������������������������������������������������������123 ■■Chapter 6: Threads��������������������������������������������������������������������������������������������������������173 ■■Chapter 7: Input/Output�������������������������������������������������������������������������������������������������281 ■■Chapter 8: Working with Archive Files��������������������������������������������������������������������������359 ■■Chapter 9: New Input/Output�����������������������������������������������������������������������������������������389 ■■Chapter 10: New Input/Output 2������������������������������������������������������������������������������������423 ■■Chapter 11: Garbage Collection�������������������������������������������������������������������������������������485 ■■Chapter 12: Collections�������������������������������������������������������������������������������������������������519 ■■Chapter 13: Streams������������������������������������������������������������������������������������������������������597 Index���������������������������������������������������������������������������������������������������������������������������������659 v Introduction How This Book Came About My first encounter with the Java programming language was during a one-week Java training session in 1997 I did not get a chance to use Java in a project until 1999 I read two Java books and took a Java Programmer certification examination I did very well on the test, scoring 95 percent The three questions that I missed on the test made me realize that the books I read did not adequately cover all of the details on all of the necessary Java topics I made up my mind to write a book on the Java programming language So, I formulated a plan to cover most of the topics that a Java developer needs understand to use the Java programming language effectively in a project, as well as to get a certification I initially planned to cover all essential topics in Java in 700 to 800 pages As I progressed, I realized that a book covering most of the Java topics in detail could not be written in 700 to 800 hundred pages One chapter that covered data types, operators, and statements spanned 90 pages I was then faced with the question, “Should I shorten the content of the book or include all the details that I think a Java developer needs?” I opted for including all the details in the book, rather than shortening the content to keep the number of pages low It has never been my intent to make lots of money from this book I was never in a hurry to finish this book because that rush could have compromised the quality and the coverage of its contents In short, I wrote this book to help the Java community understand and use the Java programming language effectively, without having to read many books on the same subject I wrote this book with the plan that it would be a comprehensive one-stop reference for everyone who wants to learn and grasp the intricacies of the Java programming language One of my high school teachers used to tell us that if one wanted to understand a building, one must first understand the bricks, steel, and mortar that make up the building The same logic applies to most of the things that we want to understand in our lives It certainly applies to an understanding of the Java programming language If you want to master the Java programming language, you must start by understanding its basic building blocks I have used this approach throughout this book, endeavoring to build each topic by describing the basics first In the book, you will rarely find a topic described without first learning its background Wherever possible, I have tried to correlate the programming practices with activities in our daily life Most books about the Java programming language either not include any pictures at all or have only a few I believe in the adage, “A picture is worth a thousand words.” To a reader, a picture makes a topic easier to understand and remember I have included plenty of illustrations in this book to aid readers in understanding and visualizing the contents Developers who have little or no programming experience can have difficulty putting things together to make a complete program Keeping them in mind, the book contains over 290 complete Java programs that are ready to be compiled and run I spent countless hours doing research for writing this book My main sources of research were the Java Language Specification, white papers and articles on Java topics, and Java Specification Requests (JSRs) I also spent quite a bit of time reading the Java source code to learn more about some of the Java topics Sometimes it took a few months to research a topic before I could write the first sentence on it It was always fun to play with Java programs, sometimes for hours, to add them to the book xxix ■ Introduction Structure of the Book This is the second book in the three-book Beginning Java series This book contains 13 chapters The chapters contain language-level topics of Java such as annotations, generics, lambda expressions, threads, I/O, collections, streams, etc Chapters introduce Java topics in an increasing order of complexity The new features of Java are included wherever they fit in the chapter The lambda expressions and Streams API, which were added in Java 8, are covered in depth After finishing this book, take your Java knowledge to the next level by learning the Java APIs, extensions, and libraries; all of this is covered in the last book in this series, Beginning Java APIs, Extensions, and Libraries (ISBN 978-1-4302-6661-7) Audience This book is designed to be useful for anyone who wants to learn the Java programming language If you are a beginner, with little or no programming background in Java, you are advised to read the companion book Beginning Java Fundamentals before reading this book This book contains topics of various degrees of complexity As a beginner, if you find yourself overwhelmed while reading a section in a chapter, you can skip to the next section or the next chapter, and revisit it later when you gain more experience If you are a Java developer with an intermediate or advanced level of experience, you can jump to a chapter or to a section in a chapter directly If a section uses an unfamiliar topic, you need to visit that topic before continuing the current one If you are reading this book to get a certification in the Java programming language, you need to read almost all of the chapters, paying attention to all of the detailed descriptions and rules Most of the certification programs test your fundamental knowledge of the language, not the advanced knowledge You need to read only those topics that are part of your certification test Compiling and running over 290 complete Java programs will help you prepare for your certification If you are a student who is attending a class in the Java programming language, you should read the chapters of this book selectively Some topics such as lambda expressions, collections, and streams are used extensively in developing Java applications, whereas some topics such as threads and archive files are infrequently used You need to read only those chapters that are covered in your class syllabus I am sure that you, as a Java student, not need to read the entire book page by page How to Use This Book This book is the beginning, not the end, of gaining the knowledge of the Java programming language If you are reading this book, it means you are heading in the right direction to learn the Java programming language, which will enable you to excel in your academic and professional career However, there is always a higher goal for you to achieve and you must constantly work hard to achieve it The following quotations from some great thinkers may help you understand the importance of working hard and constantly looking for knowledge with both your eyes and mind open The learning and knowledge that we have, is, at the most, but little compared with that of which we are ignorant —Plato True knowledge exists in knowing that you know nothing And in knowing that you know nothing, that makes you the smartest of all —Socrates xxx ■ Introduction Readers are advised to use the API documentation for the Java programming language as much as possible while using this book The Java API documentation is where you will find a complete list of everything available in the Java class library You can download (or view) the Java API documentation from the official web site of Oracle Corporation at www.oracle.com While you read this book, you need to practice writing Java programs yourself You can also practice by tweaking the programs provided in the book It does not help much in your learning process if you just read this book and not practice by writing your own programs Remember that “practice makes perfect,” which is also true in learning how to program in Java Source Code and Errata Source code and errata for this book may be downloaded from www.apress.com/source-code Questions and Comments Please direct all your questions and comments for the author to ksharan@jdojo.com xxxi Chapter Annotations In this chapter, you will learn • What annotations are • How to declare annotations • How to use annotations • What meta-annotations are and how to use them • Commonly used annotations • How to access annotations at runtime • How to process annotations in source code What Are Annotations? Annotations were introduced in Java Before I define annotations and discuss their importance in programming, let’s discuss a simple example Suppose you have an Employee class, which has a method called setSalary() that sets the salary of an employee The method accepts a parameter of the type double The following snippet of code shows a trivial implementation for the Employee class:   public class Employee { public void setSalary(double salary) { System.out.println("Employee.setSalary():" + salary); } }   A Manager class inherits from the Employee class You want to set the salary for managers differently You decide to override the setSalary() method in the Manager class The code for the Manager class is as follows:   public class Manager extends Employee { // Override setSalary() in the Employee class public void setSalary(int salary) { System.out.println("Manager.setSalary():" + salary); } }   Chapter ■ Annotations Note that there is a mistake in the above code for the Manager class, when you attempt to override the setSalary() method (You’ll correct the mistake shortly.) You have used the int data type as the parameter type for the incorrectly overridden method It is time to set the salary for a manager The following code is used to accomplish this:   Employee ken = new Manager(); int salary = 200; ken.setSalary(salary); Employee.setSalary():200.0   This snippet of code was expected to call the setSalary() method of the Manager class but the output does not show the expected result What went wrong in your code? The intention of defining the setSalary() method in the Manager class was to override the setSalary() method of the Employee class, not to overload it You made a mistake You used the type int as the parameter type in the setSalary() method, instead of the type double, in the Manager class You put comments indicating your intention to override the method in the Manager class However, comments not stop you from making logical mistakes You might spend, as every programmer does, hours and hours debugging errors resulting from this kind of logical mistake Who can help you in such situations? Annotations might help you in a few situations like this Let’s rewrite your Manager class using an annotation You not need to know anything about annotations at this point All you are going to is add one word to your program The following code is the modified version of the Manager class:   public class Manager extends Employee { @Override public void setSalary(int salary) { System.out.println("Manager.setSalary():" + salary); } }   All you have added is a @Override annotation to the Manager class and removed the “dumb” comments Trying to compile the revised Manager class results in a compile-time error that points to the use of the @Override annotation for the setSalary() method of the Manager class:   Manager.java:2: error: method does not override or implement a method from a supertype @Override ^ error   The use of the @Override annotation did the trick The @Override annotation is used with a non-static method to indicate the programmer’s intention to override the method in the superclass At source code level, it serves the purpose of documentation When the compiler comes across the @Override annotation, it makes sure that the method really overrides the method in the superclass If the method annotated does not override a method in the superclass, the compiler generates an error In your case, the setSalary(int salary) method in the Manager class does not override any method in the superclass Employee This is the reason that you got the error You may realize that using an annotation is as simple as documenting the source code However, they have compiler support You can use them to instruct the compiler to enforce some rules Annotations provide benefits much more than you have seen in this example Chapter ■ Annotations Let’s go back to the compile-time error You can fix the error by doing one of the following two things: • You can remove the @Override annotation from the setSalary(int salary) method in the Manager class It will make the method an overloaded method, not a method that overrides its superclass method • You can change the method signature from setSalary(int salary) to setSalary(double salary) Since you want to override the setSalary() method in the Manager class, use the second option and modify the Manager class as follows:   public class Manager extends Employee { @Override public void setSalary(double salary) { System.out.println("Manager.setSalary():" + salary); } }   Now the following code will work as expected:   Employee ken = new Manager(); int salary = 200; ken.setSalary(salary); Manager.setSalary():200.0   Note that the @Override annotation in the setSalary() method of the Manager class saves you debugging time Suppose you change the method signature in the Employee class If the changes in the Employee class make this method no longer overridden in the Manager class, you will get the same error when you compile the Manager class again Are you starting to understand the power of annotations? With this background in mind, let’s start digging deep into annotations According to the Merriam Webster dictionary, the meaning of annotation is “A note added by way of comment or explanation” This is exactly what an annotation is in Java It lets you associate (or annotate) metadata (or notes) to the program elements in a Java program The program elements may be a package, a class, an interface, a field of a class, a local variable, a method, a parameter of a method, an enum, an annotation, a type parameter in a generic type/method declaration, a type use, etc In other words, you can annotate any declaration or type use in a Java program An annotation is used as a modifier in a declaration of a program element like any other modifiers (public, private, final, static, etc.) Unlike a modifier, an annotation does not modify the meaning of the program elements It acts like a decoration or a note for the program element that it annotates An annotation differs from regular documentation in many ways A regular documentation is only for humans to read and it is “dumb.” It has no intelligence associated with it If you misspell a word, or state something in the documentation and just the opposite in the code, you are on your own It is very difficult and impractical to read the elements of documentation programmatically at runtime Java lets you generate Javadocs from your documentation and that’s it for regular documentation This does not mean that you not need to document your programs You need regular documentation At the same time, you need a way to enforce your intent using a documentation-like mechanism Your documentation should be available to the compiler and the runtime An annotation serves this purpose It is human readable, which serves as documentation It is compiler readable, which lets the compiler verify the intention of the programmer; for example, the compiler makes sure that the programmer Chapter ■ Annotations has really overridden the method if it comes across a @Override annotation for a method Annotations are also available at runtime so that a program can read and use it for any purpose it wants For example, a tool can read annotations and generate boilerplate code If you have worked with Enterprise JavaBeans (EJB), you know the pain of keeping all the interfaces and classes in sync and adding entries to XML configuration files EJB 3.0 uses annotations to generate the boilerplate code, which makes EJB development painless for programmers Another example of an annotation being used in a framework/tool is JUnit version 4.0 JUnit is a unit test framework for Java programs It uses annotations to mark methods that are test cases Before that, you had to follow a naming convention for the test case methods Annotations have a variety of uses, which are documentation, verification, and enforcement by the compiler, the runtime validation, code generation by frameworks/tools, etc To make an annotation available to the compiler and the runtime, an annotation has to follow rules In fact, an annotation is another type like a class and an interface As you have to declare a class type or an interface type before you can use it, you must also declare an annotation type An annotation does not change the semantics (or meaning) of the program element that it annotates In that sense, an annotation is like a comment, which does not affect the way the annotated program element works For example, the @Override annotation for the setSalary() method did not change the way the method works You (or a tool/framework) can change the behavior of a program based on an annotation In such cases, you make use of the annotation rather than the annotation doing anything on its own The point is that an annotation by itself is always passive Declaring an Annotation Type Declaring an annotation type is similar to declaring an interface type, except for some restrictions According to Java specification, an annotation type declaration is a special kind of interface type declaration You use the interface keyword, which is preceded by the @ sign (at sign) to declare an annotation type The following is the general syntax for declaring an annotation type:   @ interface { // Annotation type body goes here }   The for an annotation declaration is the same as for an interface declaration For example, you can declare an annotation type as public or package level The @ sign and the interface keyword may be separated by whitespaces or they can be placed together By convention, they are placed together as @interface The interface keyword is followed by an annotation type name It should be a valid Java identifier The annotation type body is placed within braces Suppose you want to annotate your program elements with the version information, so you can prepare a report about new program elements added in a specific release of your product To use a custom annotation type (as opposed to built-in annotation, such as @Override), you must declare it first You want to include the major and the minor versions of the release in the version information Listing 1-1 has the complete code for your first annotation declaration Listing 1-1.  The Declaration of an Annotation Type Named Version // Version.java package com.jdojo.annotation;   public @interface Version { int major(); int minor(); }   ■ Contents ■■Chapter 4: Generics�������������������������������������������������������������������������������������������������������103 What Are Generics?�������������������������������������������������������������������������������������������������������������������103 Supertype-Subtype Relationship�����������������������������������������������������������������������������������������������106 Raw Type�����������������������������������������������������������������������������������������������������������������������������������107 Unbounded Wildcards���������������������������������������������������������������������������������������������������������������108 Upper-Bounded Wildcards���������������������������������������������������������������������������������������������������������110 Lower-Bounded Wildcards��������������������������������������������������������������������������������������������������������112 Generic Methods and Constructors�������������������������������������������������������������������������������������������113 Type Inference in Generic Object Creation��������������������������������������������������������������������������������114 No Generic Exception Classes���������������������������������������������������������������������������������������������������117 No Generic Anonymous Classes������������������������������������������������������������������������������������������������117 Generics and Arrays������������������������������������������������������������������������������������������������������������������117 Runtime Class Type of Generic Objects�������������������������������������������������������������������������������������118 Heap Pollution���������������������������������������������������������������������������������������������������������������������������119 Varargs Methods and Heap Pollution Warnings������������������������������������������������������������������������120 Summary�����������������������������������������������������������������������������������������������������������������������������������121 ■■Chapter 5: Lambda Expressions������������������������������������������������������������������������������������123 What Is a Lambda Expression?�������������������������������������������������������������������������������������������������123 Why Do We Need Lambda Expressions?�����������������������������������������������������������������������������������125 Syntax for Lambda Expressions������������������������������������������������������������������������������������������������126 Omitting Parameter Types��������������������������������������������������������������������������������������������������������������������������������� 128 Declaring a Single Parameter���������������������������������������������������������������������������������������������������������������������������� 128 Declaring No Parameters����������������������������������������������������������������������������������������������������������������������������������� 129 Parameters with Modifiers�������������������������������������������������������������������������������������������������������������������������������� 129 Declaring Body of Lambda Expressions������������������������������������������������������������������������������������������������������������ 129 Target Typing�����������������������������������������������������������������������������������������������������������������������������130 Functional Interfaces�����������������������������������������������������������������������������������������������������������������137 Using the @FunctionalInterface Annotation������������������������������������������������������������������������������������������������������ 137 Generic Functional Interface����������������������������������������������������������������������������������������������������������������������������� 138 x ■ Contents Intersection Type and Lambda Expressions������������������������������������������������������������������������������������������������������� 140 Commonly Used Functional Interfaces�������������������������������������������������������������������������������������������������������������� 141 Using the Function Interface�������������������������������������������������������������������������������������������������������������������� 142 Using the Predicate Interface��������������������������������������������������������������������������������������������������������������������� 144 Using Functional Interfaces������������������������������������������������������������������������������������������������������������������������������� 145 Method References�������������������������������������������������������������������������������������������������������������������149 Static Method References��������������������������������������������������������������������������������������������������������������������������������� 150 Instance Method References����������������������������������������������������������������������������������������������������������������������������� 153 Supertype Instance Method References������������������������������������������������������������������������������������������������������������ 156 Constructor References������������������������������������������������������������������������������������������������������������������������������������� 158 Generic Method References������������������������������������������������������������������������������������������������������������������������������ 160 Lexical Scoping�������������������������������������������������������������������������������������������������������������������������161 Variable Capture������������������������������������������������������������������������������������������������������������������������164 Jumps and Exits������������������������������������������������������������������������������������������������������������������������167 Recursive Lambda Expressions������������������������������������������������������������������������������������������������168 Comparing Objects��������������������������������������������������������������������������������������������������������������������169 Summary�����������������������������������������������������������������������������������������������������������������������������������171 ■■Chapter 6: Threads��������������������������������������������������������������������������������������������������������173 What Is a Thread?����������������������������������������������������������������������������������������������������������������������173 Creating a Thread in Java����������������������������������������������������������������������������������������������������������176 Specifying Your Code for a Thread �������������������������������������������������������������������������������������������178 Inheriting Your Class from the Thread Class������������������������������������������������������������������������������������������������������ 179 Implementing the Runnable Interface��������������������������������������������������������������������������������������������������������������� 179 Using a Method Reference�������������������������������������������������������������������������������������������������������������������������������� 180 A Quick Example������������������������������������������������������������������������������������������������������������������������������������������������ 180 Using Multiple Threads in a Program����������������������������������������������������������������������������������������181 Issues in Using Multiple Threads�����������������������������������������������������������������������������������������������182 xi ■ Contents Java Memory Model (JMM)�������������������������������������������������������������������������������������������������������185 Atomicity������������������������������������������������������������������������������������������������������������������������������������������������������������ 185 Visibility������������������������������������������������������������������������������������������������������������������������������������������������������������� 186 Ordering������������������������������������������������������������������������������������������������������������������������������������������������������������� 186 Object’s Monitor and Threads Synchronization�������������������������������������������������������������������������186 The Producer/Consumer Synchronization Problem�������������������������������������������������������������������199 Which Thread Is Executing?������������������������������������������������������������������������������������������������������203 Letting a Thread Sleep��������������������������������������������������������������������������������������������������������������204 I will Join You in Heaven������������������������������������������������������������������������������������������������������������205 Be Considerate to Others and Yield�������������������������������������������������������������������������������������������207 Life Cycle of a Thread����������������������������������������������������������������������������������������������������������������208 Priority of a Thread��������������������������������������������������������������������������������������������������������������������211 Is It a Demon or a Daemon?������������������������������������������������������������������������������������������������������212 Am I Interrupted?����������������������������������������������������������������������������������������������������������������������214 Threads Work in a Group ����������������������������������������������������������������������������������������������������������218 Volatile Variables�����������������������������������������������������������������������������������������������������������������������219 Stopping, Suspending, and Resuming a Thread �����������������������������������������������������������������������221 Handling an Uncaught Exception in a Thread����������������������������������������������������������������������������225 New Thread Concurrency Packages������������������������������������������������������������������������������������������226 Atomic Variables������������������������������������������������������������������������������������������������������������������������227 Scalar Atomic Variable Classes������������������������������������������������������������������������������������������������������������������������� 228 Atomic Arrays Classes��������������������������������������������������������������������������������������������������������������������������������������� 228 Atomic Field Updater Classes���������������������������������������������������������������������������������������������������������������������������� 228 Atomic Compound Variable Classes������������������������������������������������������������������������������������������������������������������ 228 Explicit Locks����������������������������������������������������������������������������������������������������������������������������230 Synchronizers����������������������������������������������������������������������������������������������������������������������������235 Semaphores������������������������������������������������������������������������������������������������������������������������������������������������������ 235 Barriers�������������������������������������������������������������������������������������������������������������������������������������������������������������� 238 xii ■ Contents Phasers�������������������������������������������������������������������������������������������������������������������������������������������������������������� 241 Latches�������������������������������������������������������������������������������������������������������������������������������������������������������������� 250 Exchangers�������������������������������������������������������������������������������������������������������������������������������������������������������� 252 The Executor Framework����������������������������������������������������������������������������������������������������������256 Result-Bearing Tasks����������������������������������������������������������������������������������������������������������������������������������������� 261 Scheduling a Task���������������������������������������������������������������������������������������������������������������������������������������������� 264 Handling Uncaught Exceptions in a Task Execution������������������������������������������������������������������������������������������ 266 Executor’s Completion Service�������������������������������������������������������������������������������������������������������������������������� 268 The Fork/Join Framework���������������������������������������������������������������������������������������������������������271 Steps in Using the Fork/Join Framework���������������������������������������������������������������������������������������������������������� 272 A Fork/Join Example������������������������������������������������������������������������������������������������������������������������������������������ 273 Thread-Local Variables��������������������������������������������������������������������������������������������������������������276 Setting Stack Size of a Thread��������������������������������������������������������������������������������������������������278 Summary�����������������������������������������������������������������������������������������������������������������������������������279 ■■Chapter 7: Input/Output�������������������������������������������������������������������������������������������������281 What Is Input/Output?���������������������������������������������������������������������������������������������������������������281 Working with Files���������������������������������������������������������������������������������������������������������������������282 Creating a File Object���������������������������������������������������������������������������������������������������������������������������������������� 282 Knowing the Current Working Directory������������������������������������������������������������������������������������������������������������ 283 Checking for a File’s Existence�������������������������������������������������������������������������������������������������������������������������� 284 Which Path Do You Want to Go?������������������������������������������������������������������������������������������������������������������������� 284 Creating, Deleting, and Renaming Files������������������������������������������������������������������������������������������������������������� 286 Working with File Attributes������������������������������������������������������������������������������������������������������������������������������ 290 Copying a File���������������������������������������������������������������������������������������������������������������������������������������������������� 290 Knowing the Size of a File��������������������������������������������������������������������������������������������������������������������������������� 290 Listing All Files and Directories������������������������������������������������������������������������������������������������������������������������� 290 The Decorator Pattern���������������������������������������������������������������������������������������������������������������293 Input/Output Streams����������������������������������������������������������������������������������������������������������������301 Reading from File Using an Input Stream���������������������������������������������������������������������������������������������������������� 302 Writing Data to a File Using an Output Stream�������������������������������������������������������������������������������������������������� 306 xiii ■ Contents Input Stream Meets the Decorator Pattern�������������������������������������������������������������������������������309 BufferedInputStream����������������������������������������������������������������������������������������������������������������������������������������� 311 PushbackInputStream��������������������������������������������������������������������������������������������������������������������������������������� 313 Output Stream Meets the Decorator Pattern�����������������������������������������������������������������������������314 PrintStream������������������������������������������������������������������������������������������������������������������������������������������������������� 316 Using Pipes��������������������������������������������������������������������������������������������������������������������������������318 Reading and Writing Primitive Data Types���������������������������������������������������������������������������������320 Object Serialization�������������������������������������������������������������������������������������������������������������������322 Serializing Objects��������������������������������������������������������������������������������������������������������������������������������������������� 323 Deserializing Objects����������������������������������������������������������������������������������������������������������������������������������������� 326 Externalizable Object Serialization�������������������������������������������������������������������������������������������������������������������� 327 Serialization of transient Fields�������������������������������������������������������������������������������������������������331 Advanced Object Serialization���������������������������������������������������������������������������������������������������331 Writing an Object More Than Once to a Stream������������������������������������������������������������������������������������������������ 332 Class Evolution and Object Serialization����������������������������������������������������������������������������������������������������������� 335 Stopping Serialization���������������������������������������������������������������������������������������������������������������������������������������� 336 Readers and Writers������������������������������������������������������������������������������������������������������������������337 Custom Input/Output Streams���������������������������������������������������������������������������������������������������342 Random Access Files����������������������������������������������������������������������������������������������������������������344 Copying the Contents of a File��������������������������������������������������������������������������������������������������347 Standard Input/Output/Error Streams���������������������������������������������������������������������������������������347 Console and Scanner Classes���������������������������������������������������������������������������������������������������352 StringTokenizer and StreamTokenizer���������������������������������������������������������������������������������������354 Summary�����������������������������������������������������������������������������������������������������������������������������������357 ■■Chapter 8: Working with Archive Files��������������������������������������������������������������������������359 What Is an Archive File?������������������������������������������������������������������������������������������������������������359 Data Compression���������������������������������������������������������������������������������������������������������������������359 Checksum���������������������������������������������������������������������������������������������������������������������������������360 Compressing Byte Arrays����������������������������������������������������������������������������������������������������������362 xiv ■ Contents Working with ZIP File Format����������������������������������������������������������������������������������������������������366 Working with GZIP File Format��������������������������������������������������������������������������������������������������374 Working with JAR File Format���������������������������������������������������������������������������������������������������374 Creating a JAR File�������������������������������������������������������������������������������������������������������������������������������������������� 376 Updating a JAR File������������������������������������������������������������������������������������������������������������������������������������������� 377 Indexing a JAR File�������������������������������������������������������������������������������������������������������������������������������������������� 377 Extracting an Entry from a JAR File������������������������������������������������������������������������������������������������������������������� 378 Listing the Contents of a JAR File���������������������������������������������������������������������������������������������������������������������� 378 The Manifest File����������������������������������������������������������������������������������������������������������������������������������������������� 378 Sealing a Package in a JAR File������������������������������������������������������������������������������������������������������������������������ 381 Using the JAR API����������������������������������������������������������������������������������������������������������������������381 Accessing Resources from a JAR File���������������������������������������������������������������������������������������386 Summary�����������������������������������������������������������������������������������������������������������������������������������387 ■■Chapter 9: New Input/Output�����������������������������������������������������������������������������������������389 What Is NIO?������������������������������������������������������������������������������������������������������������������������������389 Buffers���������������������������������������������������������������������������������������������������������������������������������������390 Reading from and Writing to a Buffer����������������������������������������������������������������������������������������393 Read-Only Buffers���������������������������������������������������������������������������������������������������������������������399 Different Views of a Buffer��������������������������������������������������������������������������������������������������������400 Character Set����������������������������������������������������������������������������������������������������������������������������401 Channels�����������������������������������������������������������������������������������������������������������������������������������409 Reading/Writing Files ���������������������������������������������������������������������������������������������������������������411 Memory-Mapped File I/O�����������������������������������������������������������������������������������������������������������415 File Locking�������������������������������������������������������������������������������������������������������������������������������416 Copying Contents of a File ��������������������������������������������������������������������������������������������������������418 Knowing the Byte Order of a Machine���������������������������������������������������������������������������������������419 Byte Buffer and Its Byte Order���������������������������������������������������������������������������������������������������420 Summary�����������������������������������������������������������������������������������������������������������������������������������422 xv ■ Contents ■■Chapter 10: New Input/Output 2������������������������������������������������������������������������������������423 What Is New Input/Output 2?����������������������������������������������������������������������������������������������������423 Working with a File System�������������������������������������������������������������������������������������������������������424 Working with Paths�������������������������������������������������������������������������������������������������������������������426 Creating a Path Object��������������������������������������������������������������������������������������������������������������������������������������� 427 Accessing Components of a Path���������������������������������������������������������������������������������������������������������������������� 427 Comparing Paths����������������������������������������������������������������������������������������������������������������������������������������������� 429 Normalizing, Resolving, and Relativizing Paths������������������������������������������������������������������������������������������������� 431 Symbolic Links��������������������������������������������������������������������������������������������������������������������������432 Different Forms of a Path����������������������������������������������������������������������������������������������������������433 Performing File Operations on a Path���������������������������������������������������������������������������������������435 Creating New Files�������������������������������������������������������������������������������������������������������������������������������������������� 435 Deleting Files����������������������������������������������������������������������������������������������������������������������������������������������������� 436 Checking for Existence of a File������������������������������������������������������������������������������������������������������������������������ 437 Copying and Moving Files���������������������������������������������������������������������������������������������������������������������������������� 437 Commonly Used File Attributes�������������������������������������������������������������������������������������������������������������������������� 439 Probing the Content Type of a File��������������������������������������������������������������������������������������������������������������������� 440 Reading the Contents of a File��������������������������������������������������������������������������������������������������������������������������� 441 Writing to a File������������������������������������������������������������������������������������������������������������������������������������������������� 443 Random Access to a File����������������������������������������������������������������������������������������������������������������������������������� 445 Traversing a File Tree����������������������������������������������������������������������������������������������������������������447 Matching Paths�������������������������������������������������������������������������������������������������������������������������453 Managing File Attributes�����������������������������������������������������������������������������������������������������������454 Checking for a File Attribute View Support�������������������������������������������������������������������������������������������������������� 455 Reading and Updating File Attributes���������������������������������������������������������������������������������������������������������������� 456 Managing the Owner of a File��������������������������������������������������������������������������������������������������������������������������� 460 Managing ACL File Permissions������������������������������������������������������������������������������������������������������������������������ 462 Managing POSIX File Permissions��������������������������������������������������������������������������������������������������������������������� 466 xvi ■ Contents Watching a Directory for Modifications�������������������������������������������������������������������������������������468 Create a Watch Service������������������������������������������������������������������������������������������������������������������������������������� 469 Register the Directory with the Watch Service�������������������������������������������������������������������������������������������������� 470 Retrieve a WatchKey from the Watch Service Queue���������������������������������������������������������������������������������������� 470 Process the Events�������������������������������������������������������������������������������������������������������������������������������������������� 470 Reset the WatchKey after Processing Events���������������������������������������������������������������������������������������������������� 471 Close the Watch Service������������������������������������������������������������������������������������������������������������������������������������ 471 Asynchronous File I/O����������������������������������������������������������������������������������������������������������������473 Summary�����������������������������������������������������������������������������������������������������������������������������������483 ■■Chapter 11: Garbage Collection�������������������������������������������������������������������������������������485 What Is Garbage Collection?�����������������������������������������������������������������������������������������������������485 Memory Allocation in Java��������������������������������������������������������������������������������������������������������486 Garbage Collection in Java��������������������������������������������������������������������������������������������������������488 Invoking the Garbage Collector�������������������������������������������������������������������������������������������������489 Object Finalization���������������������������������������������������������������������������������������������������������������������491 Finally or Finalize?��������������������������������������������������������������������������������������������������������������������493 Object Resurrection�������������������������������������������������������������������������������������������������������������������494 State of an Object����������������������������������������������������������������������������������������������������������������������496 Weak References����������������������������������������������������������������������������������������������������������������������497 Accessing and Clearing a Referent’s Reference�����������������������������������������������������������������������502 Using the SoftReference Class��������������������������������������������������������������������������������������������������504 Using the ReferenceQueue Class����������������������������������������������������������������������������������������������508 Using the WeakReference Class������������������������������������������������������������������������������������������������509 Using the PhantomReference Class������������������������������������������������������������������������������������������513 Summary�����������������������������������������������������������������������������������������������������������������������������������516 ■■Chapter 12: Collections�������������������������������������������������������������������������������������������������519 What Is a Collection?�����������������������������������������������������������������������������������������������������������������519 Need for a Collection Framework����������������������������������������������������������������������������������������������520 Architecture of the Collection Framework���������������������������������������������������������������������������������521 xvii ■ Contents The Collection Interface������������������������������������������������������������������������������������������������������������522 Methods for Basic Operations��������������������������������������������������������������������������������������������������������������������������� 523 Methods for Bulk (or Group) Operations������������������������������������������������������������������������������������������������������������ 523 Methods for Aggregate Operations�������������������������������������������������������������������������������������������������������������������� 524 Methods for Array Operations���������������������������������������������������������������������������������������������������������������������������� 524 Methods for Comparison Operations����������������������������������������������������������������������������������������������������������������� 524 A Quick Example�����������������������������������������������������������������������������������������������������������������������524 Traversing Collections���������������������������������������������������������������������������������������������������������������526 Using an Iterator������������������������������������������������������������������������������������������������������������������������������������������������ 526 Using a for-each Loop���������������������������������������������������������������������������������������������������������������������������������������� 529 Using the forEach( ) Method������������������������������������������������������������������������������������������������������������������������������� 531 Using Different Types of Collections������������������������������������������������������������������������������������������532 Working with Sets��������������������������������������������������������������������������������������������������������������������������������������������� 532 Working with Lists��������������������������������������������������������������������������������������������������������������������������������������������� 544 Working with Queues���������������������������������������������������������������������������������������������������������������������������������������� 549 Working with Maps�������������������������������������������������������������������������������������������������������������������������������������������� 571 Applying Algorithms to Collections��������������������������������������������������������������������������������������������582 Sorting a List����������������������������������������������������������������������������������������������������������������������������������������������������� 582 Searching a List������������������������������������������������������������������������������������������������������������������������������������������������� 584 Shuffling, Reversing, Swapping, and Rotating a List����������������������������������������������������������������������������������������� 585 Creating Different Views of a Collection������������������������������������������������������������������������������������586 Read-Only Views of Collections������������������������������������������������������������������������������������������������������������������������� 587 Synchronized View of a Collection��������������������������������������������������������������������������������������������������������������������� 587 Checked Collections������������������������������������������������������������������������������������������������������������������������������������������ 588 Creating Empty Collections�������������������������������������������������������������������������������������������������������589 Creating Singleton Collections��������������������������������������������������������������������������������������������������590 Understanding Hash-based Collections������������������������������������������������������������������������������������590 Summary�����������������������������������������������������������������������������������������������������������������������������������595 xviii ■ Contents ■■Chapter 13: Streams������������������������������������������������������������������������������������������������������597 What Is a Stream?���������������������������������������������������������������������������������������������������������������������597 Streams Have No Storage���������������������������������������������������������������������������������������������������������������������������������� 598 Infinite Streams������������������������������������������������������������������������������������������������������������������������������������������������� 598 Internal Iteration vs External Iteration�������������������������������������������������������������������������������������������������������������� 598 Imperative vs Functional���������������������������������������������������������������������������������������������������������������������������������� 599 Stream Operations��������������������������������������������������������������������������������������������������������������������������������������������� 600 Ordered Streams����������������������������������������������������������������������������������������������������������������������������������������������� 601 Streams Are Not Reusable��������������������������������������������������������������������������������������������������������������������������������� 602 Architecture of the Streams API������������������������������������������������������������������������������������������������������������������������ 602 A Quick Example ����������������������������������������������������������������������������������������������������������������������603 Creating Streams����������������������������������������������������������������������������������������������������������������������607 Streams from Values����������������������������������������������������������������������������������������������������������������������������������������� 607 Empty Streams�������������������������������������������������������������������������������������������������������������������������������������������������� 610 Streams from Functions������������������������������������������������������������������������������������������������������������������������������������ 610 Streams from Arrays������������������������������������������������������������������������������������������������������������������������������������������ 615 Streams from Collections���������������������������������������������������������������������������������������������������������������������������������� 615 Streams from Files�������������������������������������������������������������������������������������������������������������������������������������������� 615 Streams from Other Sources����������������������������������������������������������������������������������������������������������������������������� 617 Representing an Optional Value������������������������������������������������������������������������������������������������618 Applying Operations on Streams�����������������������������������������������������������������������������������������������621 Debugging a Stream Pipeline���������������������������������������������������������������������������������������������������������������������������� 622 Applying the ForEach Operation������������������������������������������������������������������������������������������������������������������������ 623 Applying the Map Operation������������������������������������������������������������������������������������������������������������������������������ 624 Flattening Streams�������������������������������������������������������������������������������������������������������������������������������������������� 626 Applying the Filter Operation����������������������������������������������������������������������������������������������������������������������������� 628 Applying the Reduce Operation������������������������������������������������������������������������������������������������������������������������� 630 Collecting Data Using Collectors�����������������������������������������������������������������������������������������������638 Collecting Summary Statistics��������������������������������������������������������������������������������������������������642 xix ■ Contents Collecting Data in Maps������������������������������������������������������������������������������������������������������������644 Joining Strings Using Collectors�����������������������������������������������������������������������������������������������646 Grouping Data���������������������������������������������������������������������������������������������������������������������������647 Partitioning Data������������������������������������������������������������������������������������������������������������������������650 Adapting the Collector Results��������������������������������������������������������������������������������������������������651 Finding and Matching in Streams���������������������������������������������������������������������������������������������653 Parallel Streams������������������������������������������������������������������������������������������������������������������������655 Summary�����������������������������������������������������������������������������������������������������������������������������������657 Index���������������������������������������������������������������������������������������������������������������������������������659 xx About the Author Kishori Sharan is a senior software consultant at Doozer, Inc He holds a Master of Science in Computer Information Systems from Troy State University in Montgomery, Alabama He is a Sun Certified Java Programmer and Sybase Certified PowerBuilder Developer Professional He specializes in developing enterprise application using Java SE, Java EE, PowerBuilder, and Oracle database He has been working in the software industry for over 16 years He has helped several clients to migrate legacy applications to the Web He loves writing technical books in his free time He maintains his web site at www.jdojo.com where he posts blogs on Java and JavaFX xxi About the Technical Reviewers Jeff Friesen is a freelance tutor, author, and software developer with an emphasis on Java, Android, and HTML5 In addition to writing several books for Apress and serving as a technical reviewer for other Apress books, Jeff has written numerous articles on Java and other technologies for JavaWorld (www.javaworld.com), informIT (www.informit.com), java.net, SitePoint (www.sitepoint.com), and others Jeff can be contacted via his website at tutortutor.ca John Zukowski is currently a software engineer with TripAdvisor, the world’s largest travel site (www.tripadvisor.com) He has been playing with Java technologies for 20 years now and is the author of 10 Java-related books His books cover Java 6, Java Swing, Java Collections, and JBuilder from Apress, Java AWT from O’Reilly, and introductory Java from Sybex He lives outside Boston, Massachusetts and has a Master’s degree in Software Engineering from The Johns Hopkins University You can follow him on Twitter at http://twitter.com/javajohnz xxiii Acknowledgments My heartfelt thanks are due to my father-in-law, Mr Jim Baker, for displaying extraordinary patience in reading the initial draft of the book I am very grateful to him for spending so much of his valuable time teaching me quite a bit of English grammar that helped me produce better material I would like to thank my friend Richard Castillo for his hard work in reading my initial draft of the book and weeding out several mistakes Richard was instrumental in running all examples and pointing out errors My wife, Ellen, was always patient when I spent long hours at my computer desk working on this book She would happily bring me snacks, fruit, and a glass of water every 30 minutes or so to sustain me during that period I want to thank her for all of her support in writing this book She also deserves my sincere thanks for letting me sometimes seclude myself on weekends so I could focus on this book I would like to thank my family members and friends for their encouragement and support for writing this book: my elder brothers, Janki Sharan and Dr Sita Sharan; my sister and brother-in-law, Ratna and Abhay; my nephews Babalu, Dabalu, Gaurav, Saurav, and Chitranjan; my friends Shivashankar Ravindranath, Kannan Somasekar, Mahbub Choudhury, Biju Nair, Srinivas Kakkera, Anil Kumar Singh, Chris Coley, Willie Baptiste, Rahul Jain, Larry Brewster, Greg Langham, Ram Atmakuri, LaTondra Okeke, Rahul Nagpal, Ravi Datla, Prakash Chandra, and many more friends not mentioned here My sincere thanks are due to the wonderful team at Apress for their support during the publication of this book Thanks to Anamika Panchoo, the Senior Coordinating Editor, for providing excellent support and for being exceptionally patient with me when I asked her so many questions in the beginning, Thanks to Matthew Moodie, Jeff Friesen, and John Zukowski for their technical insights and feedback during the editing process My special thanks to Kevin Shea, the coordinating editor who filled in for Anamika for a few months and brought in Jeff as an additional technical reviewer to expedite the technical reviews Last but not least, my sincere thanks to Steve Anglin, the Lead Editor at Apress, for taking the initiative for the publication of this book xxv Foreword The evolving Java language has much to offer, and its wealth of features can overwhelm even advanced Java developers Oracle’s recent Java release has increased this wealth by offering exciting new features such as lambdas and the Streams API Perhaps you already know the basics of this language (e.g., types, operators, statements, and a few assorted APIs) and want to learn more about Java without becoming too overwhelmed If so, I heartily recommend that you check out this book by author Kishori Sharan Kishori provides a solid introduction to annotations, inner classes, reflection, generics, lambdas, threads, I/O, archive files, New I/O, New I/O 2, garbage collection, the Collections Framework, and the Streams API You’ll discover many aspects of the Java language that may be new to you (e.g., intersection types and how the compiler implements inner classes), and you will definitely want to augment your basic Java knowledge with these more advanced language/API topics to increase your desirability as a Java developer Beginning Java Language Features is one book that definitely deserves a place on your bookshelf —Jeff Friesen June, 2014 xxvii

Ngày đăng: 12/05/2017, 10:33

Từ khóa liên quan

Mục lục

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewers

  • Acknowledgments

  • Foreword

  • Introduction

  • Chapter 1: Annotations

    • What Are Annotations?

    • Declaring an Annotation Type

    • Restrictions on Annotation Types

      • Restriction #1

      • Restriction #2

      • Restriction #3

      • Restriction #4

      • Restriction #5

      • Restriction #6

      • Default Value of an Annotation Element

      • Annotation Type and Its Instances

      • Using Annotations

        • Primitive Types

        • String Types

        • Class Types

Tài liệu cùng người dùng

Tài liệu liên quan