diff --git a/.travis.yml b/.travisXX.yml similarity index 91% rename from .travis.yml rename to .travisXX.yml index a9e2a082d..54fee6592 100644 --- a/.travis.yml +++ b/.travisXX.yml @@ -1,6 +1,6 @@ language: java jdk: - - oraclejdk8 + - oraclejdk11 install: true script: - ./gradlew --no-daemon --stacktrace run diff --git a/Copyright.txt b/Copyright.txt index 8cc3bb56a..8eb3289e0 100644 --- a/Copyright.txt +++ b/Copyright.txt @@ -1,5 +1,5 @@ // Copyright.txt -This computer source code is Copyright ©2017 MindView LLC. +This computer source code is Copyright ©2021 MindView LLC. All Rights Reserved. Permission to use, copy, modify, and distribute this diff --git a/NOTES.md b/NOTES.md new file mode 100644 index 000000000..5401db816 --- /dev/null +++ b/NOTES.md @@ -0,0 +1,3 @@ +For generating table of contents in README.md +https://ecotrust-canada.github.io/markdown-toc/ +(Replace double hyphens with single hyphens after generation) diff --git a/README.md b/README.md index 84b3e7642..ad462ebc0 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,316 @@ -[![](https://travis-ci.org/BruceEckel/OnJava8-Examples.svg?branch=master)](https://travis-ci.org/BruceEckel/OnJava8-Examples) +# Examples for *On Java 8* by Bruce Eckel -[![](https://ci.appveyor.com/api/projects/status/github/BruceEckel/OnJava8-Examples)](https://ci.appveyor.com/project/BruceEckel/onjava-examples) +If you want to experiment with the code examples from the book [On Java +8](https://www.onjava8.com/), you're in the right place. -To compile and run these programs, you only need JDK 8 installed. -Invoking `gradlew` will automatically download and install Gradle. -Gradle will also install all additional libraries necessary to compile -and run the Java examples in the book. +These examples are automatically extracted directly from the book. This repository +includes tests to verify that the code in the book is correct. + +> NOTE: Do not attempt to use JDK 16 or greater with gradle. +> This produces a `BUG!` message from Gradle, which is broken for those versions. + +## Contents + +- [Building From the Command Line: Quick Version](#building-from-the-command-line-quick-version) +- [Building From the Command Line: Detailed Instructions](#building-from-the-command-line-detailed-instructions) + * [Install Java](#install-java) + + [Windows](#windows) + + [Macintosh](#macintosh) + + [Linux](#linux) + * [Verify Your Installation](#verify-your-installation) + * [Installing and Running the Book Examples](#installing-and-running-the-book-examples) +- [Appendix A: Command-Line Basics](#appendix-a-command-line-basics) + * [Editors](#editors) + * [The Shell](#the-shell) + + [Starting a Shell](#starting-a-shell) + + [Directories](#directories) + + [Basic Shell Operations](#basic-shell-operations) + + [Unpacking a Zip Archive](#unpacking-a-zip-archive) +- [Appendix B: Testing](#appendix-b-testing) +- [Appendix C: Troubleshooting](#appendix-c-troubleshooting) + +# Building From the Command Line: Quick Version + +Before you can run the examples from this repository, you must install +[JDK8](http://www.oracle.com/technetwork/java/javase/downloads/index.html), the +*Java Development Kit* for version 8 of the language. + +If you just want to download and check the code, [Download +Here](https://github.com/BruceEckel/OnJava8-Examples/archive/refs/heads/master.zip) +and [unzip it](#unpacking-a-zip-archive) into your destination directory. Open +a [shell/command window](#appendix-a-command-line-basics) and move into the +root of that directory. You'll know you are in the right directory if you see +the files `gradlew` and `gradlew.bat`. + +You'll need an Internet connection the first time you compile the code, +because Gradle needs to first install itself, then all the support libraries. +Once these are installed you can perform additional compiling and running +offline. + +On Mac/Linux, enter: + +``` +./gradlew test +``` + +(If you get a *Permission denied* error, run `chmod +x ./gradlew`) + +On Windows, enter + +``` +gradlew test +``` + +If all goes well, the tests will run. Everything should complete without errors. + +All the book examples are in the subdirectory `Examples` in subdirectories +corresponding to the atom names. + +# Building From the Command Line: Detailed Instructions + +If you are not familiar with the command line, first read [Command-Line +Basics](#appendix-a-command-line-basics). + +## Install Java + +You must first install the *Java Development Kit* (JDK). + +### Windows + +1. Follow the instructions to [install Chocolatey](https://chocolatey.org/). + +2. At a [shell prompt](#appendix-a-command-line-basics), type: `choco install +jdk8` (you may also select a more recent version, like `jdk11`). The +installation process takes some time, but when it's finished Java is installed +and the necessary environment variables are set. + +### Macintosh + +The Mac comes with a much older version of Java that won't work for the +examples in this book, so you'll need to update it to (at least) Java 8. + + 1. Follow the instructions at this link to [Install HomeBrew](http://brew.sh/) + + 2. At a [shell prompt](#appendix-a-command-line-basics), first type + `brew update`. When that completes, enter `brew cask install java`. + +**NOTE:** Sometimes the default version of Java that you get with the above +installation will be too recent and not validated by the Mac's security +system. If this happens you'll either need to turn off the security by hand +or install an earlier version of Java. For either choice, you'll need to Google +for answers on how to solve the problem (often the easiest approach is to just +search for the error message produced by the Mac). + +### Linux + +Use the standard package installer with the following [shell commands](#appendix-a-command-line-basics): + +*Ubuntu/Debian*: + + 1. `sudo apt-get update` + + 2. `sudo apt-get install default-jdk` + +*Fedora/Redhat*: + +``` +su -c "yum install java-1.8.0-openjdk" +``` + +## Verify Your Installation + +[Open a new shell](#appendix-a-command-line-basics) and type: + +``` +java -version +``` + +You should see something like the following (Version numbers and actual text +will vary): + +``` +openjdk version "11" 2018-09-25 +OpenJDK Runtime Environment 18.9 (build 11+28) +OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode) +``` + +If you see a message that the command is not found or not recognized, review +the installation instructions. If you still can't get it to work, check +[StackOverflow](http://stackoverflow.com/search?q=installing+java). + +## Installing and Running the Book Examples + +Once you have Java installed, the process to install and run the book examples +is the same for all platforms: + +1. Download the book examples from the +[GitHub Repository](https://github.com/BruceEckel/OnJava8-Examples/archive/refs/heads/master.zip). + +2. [Unzip](#unpacking-a-zip-archive) the downloaded file into the directory of your choice. + +3. Use the Windows Explorer, the Mac Finder, or Nautilus or equivalent on Linux +to browse to the directory where you uzipped `OnJava8-Examples`, and +[open a shell](#appendix-a-command-line-basics) there. + +4. If you're in the right directory, you should see files named `gradlew` and +`gradlew.bat` in that directory, along with numerous other files and +directories. The directories correspond to the chapters in the book. + +5. At the shell prompt, type `gradlew test` (Windows) or `./gradlew test` +(Mac/Linux). + +The first time you do this, Gradle will install itself and numerous other +packages, so it will take some time. After everything is installed, subsequent +builds and runs will be much faster. + +Note that you must be connected to the Internet the first time you run `gradlew` +so that Gradle can download the necessary packages. + +# Appendix A: Command-Line Basics + +Because it is possible for a "dedicated beginner" to learn programming from +this book, you may not have previously used your computer's command-line shell. +If you have, you can go directly to the +[installation instructions](#building-from-the-command-line-detailed-instructions). + +## Editors + +To create and modify Java program files—the code listings shown in this +book—you need a program called an *editor*. You'll also need the editor to +make changes to your system configuration files, which is sometimes required +during installation. + +Programming editors vary from heavyweight *Integrated Development Environments* +(IDEs, like Eclipse, NetBeans and IntelliJ IDEA) to more basic text +manipulation applications. If you already have an IDE and are comfortable with +it, feel free to use that for this book. + +Numerous explanations in this book are specific to IntelliJ IDEA so if you +don't already have an IDE you might as well start with IDEA. There are many +other editors; these are a subculture unto themselves and people sometimes get +into heated arguments about their merits. If you find one you like better, it's +not too hard to change. The important thing is to choose one and get +comfortable with it. + +## The Shell + +If you haven't programmed before, you might be unfamiliar with your operating +system *shell* (also called the *command prompt* in Windows). The shell harkens +back to the early days of computing when everything happened by typing commands +and the computer responded by displaying responses—everything was text-based. + +Although it can seem primitive in the age of graphical user interfaces, a shell +provides a surprising number of valuable features. + +To learn more about your shell than we cover here, see +[Bash Shell](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) for Mac/Linux +or [Windows Shell](https://en.wikipedia.org/wiki/Windows_shell). + +### Starting a Shell + +**Mac**: Click on the *Spotlight* (the magnifying-glass icon in the upper-right +corner of the screen) and type "terminal." Click on the application that looks +like a little TV screen (you might also be able to hit "Return"). This starts a +shell in your home directory. + +**Windows**: First, start the Windows Explorer to navigate through your +directories: + +- *Windows 7*: click the "Start" button in the lower left corner of the screen. +In the Start Menu search box area type "explorer" and then press the "Enter" +key. + +- *Windows 8*: click Windows+Q, type "explorer" and then press the "Enter" key. + +- *Windows 10*: click Windows+E. + +Once the Windows Explorer is running, move through the folders on your computer +by double-clicking on them with the mouse. Navigate to the desired folder. Now +click the file tab at the top left of the Explorer window and select "Open +Windows Powershell." This opens a shell in the destination directory. + +**Linux**: To open a shell in your home directory: + +- *Debian*: Press Alt+F2. In the dialog that pops up, type 'gnome-terminal' + +- *Ubuntu*: Either right-click on the desktop and select 'Open Terminal', or + press Ctrl+Alt+T + +- *Redhat*: Right-click on the desktop and select 'Open Terminal' + +- *Fedora*: Press Alt+F2. In the dialog that pops up, type 'gnome-terminal' + + +### Directories + +*Directories* are one of the fundamental elements of a shell. Directories hold +files, as well as other directories. Think of a directory as a tree with +branches. If `books` is a directory on your system and it has two other +directories as branches, for example `math` and `art`, we say that you have a +directory `books` with two *subdirectories* `math` and `art`. We refer to them +as `books/math` and `books/art` since `books` is their *parent* directory. +Note that Windows uses backslashes rather than forward slashes to separate the +parts of a directory. + +### Basic Shell Operations + +The shell operations shown here are approximately identical across operating +systems. For the purposes of this book, here are the essential operations in a +shell: + +- **Change directory**: Use `cd` followed by the name of the + directory where you want to move, or `cd ..` if you want to move + up a directory. If you want to move to a different directory while + remembering where you came from, use `pushd` followed by the different + directory name. Then, to return to the previous directory, just say + `popd`. + +- **Directory listing**: `ls` (`dir` in Windows) displays all the files and + subdirectory names in the current directory. Use the wildcard `*` (asterisk) to + narrow your search. For example, if you want to list all the files ending in + ".kt," you say `ls *.kt` (Windows: `dir *.kt`). If you want to list the + files starting with "F" and ending in ".kt," you say `ls F*.kt` (Windows: + `dir F*.kt`). + +- **Create a directory**: use the `mkdir` ("make directory") command + (Windows: `md`), followed by the name of the directory you want to create. + For example, `mkdir books` (Windows: `md books`). + +- **Remove a file**: Use `rm` ("remove") followed by the name of the file + you wish to remove (Windows: `del`). For example, `rm somefile.kt` (Windows: + `del somefile.kt`). + +- **Remove a directory**: use the `rm -r` command to remove the files in + the directory and the directory itself (Windows: `deltree`). For example, + `rm -r books` (Windows: `deltree books`). + +- **Repeat a command**: The "up arrow" on all three operating + systems moves through previous commands so you can edit and + repeat them. On Mac/Linux, `!!` repeats the last command and + `!n` repeats the nth command. + +- **Command history**: Use `history` in Mac/Linux or press the F7 key in Windows. + This gives you a list of all the commands you've entered. Mac/Linux provides + numbers to refer to when you want to repeat a command. + +### Unpacking a Zip Archive + +A file name ending with `.zip` is an archive containing other files in a +compressed format. Both Linux and Mac have command-line `unzip` utilities, and +it's possible to install a command-line `unzip` for Windows via the Internet. + +However, in all three systems the graphical file browser (Windows Explorer, the +Mac Finder, or Nautilus or equivalent on Linux) will browse to the directory +containing your zip file. Then right-mouse-click on the file and select "Open" +on the Mac, "Extract Here" on Linux, or "Extract all ..." on Windows. + +# Appendix B: Testing + +The test system is built in so that we (the authors) can verify the correctness +of what goes into the book. + +You don't need to run the tests, but if you want to, you can just run `gradlew +test` (on Windows) or `./gradlew test` (Mac/Linux). To compile and run everything, the command is: @@ -32,12 +337,39 @@ program in the **strings** chapter subdirectory: `gradlew :strings:ReplacingStringTokenizer` -However, if the file name is unique throughout the book (the majority are), you can just give the -program name, like this: +However, if the file name is unique throughout the book (the majority are), you +can just give the program name, like this: `gradlew ReplacingStringTokenizer` -Note that all commands are run from the base directory where the example code is installed, and where you find the -`gradlew` script. +Note that all commands are run from the base directory where the example code is +installed, and where you find the `gradlew` script. You can learn about other options by just typing `gradlew` with no arguments. + +# Appendix C: Troubleshooting + +If any terminology or processes described here remain unclear to you, you can +usually find explanations or answers through [Google](https://www.google.com/). +For more specific issues or problems, try +[StackOverflow](http://stackoverflow.com/). Sometimes you can find installation +instructions on [YouTube](https://www.youtube.com/). + +Sometimes a Gradle build will be unable to connect to the internet and download +the necessary components, producing an error message containing: + +``` +javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty +``` + +Normally this means you have multiple Java installations on your machine +(applications built with Java ordinarily install their own version of Java), and +somehow the `cacerts` security file is interfering with the `cacerts` file for +the Java you have installed. It can be difficult to know which `cacerts` file is +interfering with yours. The brute-force approach is to search for all the +`cacerts` files on your machine and begin uninstalling the associated +applications---or in some cases, simply removing the directory containing the +`cacerts` file---until the Gradle build begins to work. You might also need to +adjust some environment variables and/or your path. Once you get the Gradle +build working successfully, you should be able to reinstall any applications you +removed in the process. diff --git a/annotations/AUComposition.java b/annotations/AUComposition.java index 451af4cc6..94d51e607 100644 --- a/annotations/AUComposition.java +++ b/annotations/AUComposition.java @@ -1,10 +1,10 @@ // annotations/AUComposition.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating non-embedded tests // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AUComposition.class} +// build/classes/java/main/annotations/AUComposition.class} package annotations; import onjava.atunit.*; import onjava.*; @@ -23,8 +23,8 @@ boolean tMethodTwo() { } /* Output: annotations.AUComposition + . tMethodOne . tMethodTwo This is methodTwo - . tMethodOne OK (2 tests) */ diff --git a/annotations/AUExternalTest.java b/annotations/AUExternalTest.java index d2f4e5ca9..71c8f2f4b 100644 --- a/annotations/AUExternalTest.java +++ b/annotations/AUExternalTest.java @@ -1,10 +1,10 @@ // annotations/AUExternalTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating non-embedded tests // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AUExternalTest.class} +// build/classes/java/main/annotations/AUExternalTest.class} package annotations; import onjava.atunit.*; import onjava.*; diff --git a/annotations/AtUnitExample1.java b/annotations/AtUnitExample1.java index 2c42aad4f..de4cc6c64 100644 --- a/annotations/AtUnitExample1.java +++ b/annotations/AtUnitExample1.java @@ -1,9 +1,9 @@ // annotations/AtUnitExample1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitExample1.class} +// build/classes/java/main/annotations/AtUnitExample1.class} package annotations; import onjava.atunit.*; import onjava.*; @@ -34,15 +34,15 @@ boolean anotherDisappointment() { } /* Output: annotations.AtUnitExample1 - . m3 + . anotherDisappointment (failed) . methodOneTest + . failureTest (failed) . m2 This is methodTwo - . failureTest (failed) - . anotherDisappointment (failed) + . m3 (5 tests) >>> 2 FAILURES <<< - annotations.AtUnitExample1: failureTest annotations.AtUnitExample1: anotherDisappointment + annotations.AtUnitExample1: failureTest */ diff --git a/annotations/AtUnitExample2.java b/annotations/AtUnitExample2.java index 79c04bfd6..855c33133 100644 --- a/annotations/AtUnitExample2.java +++ b/annotations/AtUnitExample2.java @@ -1,10 +1,10 @@ // annotations/AtUnitExample2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Assertions and exceptions can be used in @Tests // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitExample2.class} +// build/classes/java/main/annotations/AtUnitExample2.class} package annotations; import java.io.*; import onjava.atunit.*; @@ -40,18 +40,18 @@ boolean assertAndReturn() { } /* Output: annotations.AtUnitExample2 + . assertFailureExample java.lang.AssertionError: What +a surprise! +(failed) + . assertExample . exceptionExample java.io.FileNotFoundException: nofile.txt (The system cannot find the file specified) (failed) - . assertExample . assertAndReturn This is methodTwo - . assertFailureExample java.lang.AssertionError: What -a surprise! -(failed) (4 tests) >>> 2 FAILURES <<< - annotations.AtUnitExample2: exceptionExample annotations.AtUnitExample2: assertFailureExample + annotations.AtUnitExample2: exceptionExample */ diff --git a/annotations/AtUnitExample3.java b/annotations/AtUnitExample3.java index b4d13d6ef..ed1a93911 100644 --- a/annotations/AtUnitExample3.java +++ b/annotations/AtUnitExample3.java @@ -1,9 +1,9 @@ // annotations/AtUnitExample3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitExample3.class} +// build/classes/java/main/annotations/AtUnitExample3.class} package annotations; import onjava.atunit.*; import onjava.*; @@ -35,8 +35,8 @@ boolean methodOneTest() { /* Output: annotations.AtUnitExample3 . initialization + . methodOneTest . m2 This is methodTwo - . methodOneTest OK (3 tests) */ diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java index f2114c441..23bc21efb 100644 --- a/annotations/AtUnitExample4.java +++ b/annotations/AtUnitExample4.java @@ -1,9 +1,9 @@ // annotations/AtUnitExample4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitExample4.class} +// build/classes/java/main/annotations/AtUnitExample4.class} // {VisuallyInspectOutput} package annotations; import java.util.*; diff --git a/annotations/AtUnitExample5.java b/annotations/AtUnitExample5.java index 20f608601..4e4ceb4f4 100644 --- a/annotations/AtUnitExample5.java +++ b/annotations/AtUnitExample5.java @@ -1,9 +1,9 @@ // annotations/AtUnitExample5.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitExample5.class} +// build/classes/java/main/annotations/AtUnitExample5.class} package annotations; import java.io.*; import onjava.atunit.*; @@ -14,8 +14,7 @@ public class AtUnitExample5 { public AtUnitExample5(String text) { this.text = text; } - @Override - public String toString() { return text; } + @Override public String toString() { return text; } @TestProperty static PrintWriter output; @TestProperty diff --git a/annotations/DemoProcessFiles.java b/annotations/DemoProcessFiles.java index 8462c59e7..13f12bbf5 100644 --- a/annotations/DemoProcessFiles.java +++ b/annotations/DemoProcessFiles.java @@ -1,5 +1,5 @@ // annotations/DemoProcessFiles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.ProcessFiles; diff --git a/annotations/HashSetTest.java b/annotations/HashSetTest.java index 62fc7a162..5b6e7541a 100644 --- a/annotations/HashSetTest.java +++ b/annotations/HashSetTest.java @@ -1,9 +1,9 @@ // annotations/HashSetTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.atunit.AtUnit -// build/classes/main/annotations/HashSetTest.class} +// build/classes/java/main/annotations/HashSetTest.class} package annotations; import java.util.*; import onjava.atunit.*; @@ -29,8 +29,8 @@ void tRemove() { } /* Output: annotations.HashSetTest + . tContains . initialization . tRemove - . tContains OK (3 tests) */ diff --git a/annotations/PasswordUtils.java b/annotations/PasswordUtils.java index 20c83cf74..549412696 100644 --- a/annotations/PasswordUtils.java +++ b/annotations/PasswordUtils.java @@ -1,5 +1,5 @@ // annotations/PasswordUtils.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/annotations/SimulatingNull.java b/annotations/SimulatingNull.java index d9fc66484..af1282f88 100644 --- a/annotations/SimulatingNull.java +++ b/annotations/SimulatingNull.java @@ -1,5 +1,5 @@ // annotations/SimulatingNull.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.annotation.*; diff --git a/annotations/StackL.java b/annotations/StackL.java index 02050132b..246454c25 100644 --- a/annotations/StackL.java +++ b/annotations/StackL.java @@ -1,5 +1,5 @@ // annotations/StackL.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A stack built on a LinkedList diff --git a/annotations/StackLStringTst.java b/annotations/StackLStringTst.java index 98531711f..b7d8250f7 100644 --- a/annotations/StackLStringTst.java +++ b/annotations/StackLStringTst.java @@ -1,10 +1,10 @@ // annotations/StackLStringTst.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Applying @Unit to generics // {java onjava.atunit.AtUnit -// build/classes/main/annotations/StackLStringTst.class} +// build/classes/java/main/annotations/StackLStringTst.class} package annotations; import onjava.atunit.*; import onjava.*; @@ -35,8 +35,8 @@ void tTop() { } /* Output: annotations.StackLStringTst + . tPop . tTop . tPush - . tPop OK (3 tests) */ diff --git a/annotations/Testable.java b/annotations/Testable.java index b0dd168d8..b23d0e620 100644 --- a/annotations/Testable.java +++ b/annotations/Testable.java @@ -1,5 +1,5 @@ // annotations/Testable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package annotations; diff --git a/annotations/UseCase.java b/annotations/UseCase.java index 21220d6a2..c65735185 100644 --- a/annotations/UseCase.java +++ b/annotations/UseCase.java @@ -1,5 +1,5 @@ // annotations/UseCase.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.annotation.*; diff --git a/annotations/UseCaseTracker.java b/annotations/UseCaseTracker.java index 2376d695a..53cc92795 100644 --- a/annotations/UseCaseTracker.java +++ b/annotations/UseCaseTracker.java @@ -1,5 +1,5 @@ // annotations/UseCaseTracker.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -27,11 +27,11 @@ public static void main(String[] args) { } } /* Output: +Found Use Case 49 + New passwords can't equal previously used ones Found Use Case 48 no description Found Use Case 47 Passwords must contain at least one numeric -Found Use Case 49 - New passwords can't equal previously used ones Missing use case 50 */ diff --git a/annotations/database/Constraints.java b/annotations/database/Constraints.java index 48c270c51..5631f52e9 100644 --- a/annotations/database/Constraints.java +++ b/annotations/database/Constraints.java @@ -1,5 +1,5 @@ // annotations/database/Constraints.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package annotations.database; diff --git a/annotations/database/DBTable.java b/annotations/database/DBTable.java index 0dc0ba500..3d345d990 100644 --- a/annotations/database/DBTable.java +++ b/annotations/database/DBTable.java @@ -1,5 +1,5 @@ // annotations/database/DBTable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package annotations.database; diff --git a/annotations/database/Member.java b/annotations/database/Member.java index be415758a..ae5723ac8 100644 --- a/annotations/database/Member.java +++ b/annotations/database/Member.java @@ -1,5 +1,5 @@ // annotations/database/Member.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package annotations.database; @@ -16,7 +16,8 @@ public class Member { public String getReference() { return reference; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } - @Override - public String toString() { return reference; } + @Override public String toString() { + return reference; + } public Integer getAge() { return age; } } diff --git a/annotations/database/SQLInteger.java b/annotations/database/SQLInteger.java index 645adbc58..4df1e7dd6 100644 --- a/annotations/database/SQLInteger.java +++ b/annotations/database/SQLInteger.java @@ -1,5 +1,5 @@ // annotations/database/SQLInteger.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package annotations.database; diff --git a/annotations/database/SQLString.java b/annotations/database/SQLString.java index 627aa3c12..c452d1e95 100644 --- a/annotations/database/SQLString.java +++ b/annotations/database/SQLString.java @@ -1,5 +1,5 @@ // annotations/database/SQLString.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package annotations.database; diff --git a/annotations/database/TableCreator.java b/annotations/database/TableCreator.java index a9b12066f..d2be7c5e1 100644 --- a/annotations/database/TableCreator.java +++ b/annotations/database/TableCreator.java @@ -1,5 +1,5 @@ // annotations/database/TableCreator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Reflection-based annotation processor diff --git a/annotations/database/Uniqueness.java b/annotations/database/Uniqueness.java index d0ab204c7..7959fe700 100644 --- a/annotations/database/Uniqueness.java +++ b/annotations/database/Uniqueness.java @@ -1,5 +1,5 @@ // annotations/database/Uniqueness.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Sample of nested annotations diff --git a/annotations/ifx/ExtractInterface.java b/annotations/ifx/ExtractInterface.java index ed61be171..c823fe9ca 100644 --- a/annotations/ifx/ExtractInterface.java +++ b/annotations/ifx/ExtractInterface.java @@ -1,5 +1,5 @@ // annotations/ifx/ExtractInterface.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // javac-based annotation processing diff --git a/annotations/ifx/IfaceExtractorProcessor.java b/annotations/ifx/IfaceExtractorProcessor.java index 4869d4945..fae22607c 100644 --- a/annotations/ifx/IfaceExtractorProcessor.java +++ b/annotations/ifx/IfaceExtractorProcessor.java @@ -1,5 +1,5 @@ // annotations/ifx/IfaceExtractorProcessor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // javac-based annotation processing @@ -21,14 +21,12 @@ public class IfaceExtractorProcessor interfaceMethods = new ArrayList<>(); Elements elementUtils; private ProcessingEnvironment processingEnv; - @Override - public void init( + @Override public void init( ProcessingEnvironment processingEnv) { this.processingEnv = processingEnv; elementUtils = processingEnv.getElementUtils(); } - @Override - public boolean process( + @Override public boolean process( Set annotations, RoundEnvironment env) { for(Element elem:env.getElementsAnnotatedWith( diff --git a/annotations/ifx/Multiplier.java b/annotations/ifx/Multiplier.java index ad0847976..25678fd5a 100644 --- a/annotations/ifx/Multiplier.java +++ b/annotations/ifx/Multiplier.java @@ -1,5 +1,5 @@ // annotations/ifx/Multiplier.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // javac-based annotation processing diff --git a/annotations/simplest/Simple.java b/annotations/simplest/Simple.java index 6e3a13ab2..101b7900a 100644 --- a/annotations/simplest/Simple.java +++ b/annotations/simplest/Simple.java @@ -1,5 +1,5 @@ // annotations/simplest/Simple.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A bare-bones annotation diff --git a/annotations/simplest/SimpleProcessor.java b/annotations/simplest/SimpleProcessor.java index c62bcc767..1dda51955 100644 --- a/annotations/simplest/SimpleProcessor.java +++ b/annotations/simplest/SimpleProcessor.java @@ -1,5 +1,5 @@ // annotations/simplest/SimpleProcessor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A bare-bones annotation processor @@ -14,8 +14,7 @@ @SupportedSourceVersion(SourceVersion.RELEASE_8) public class SimpleProcessor extends AbstractProcessor { - @Override - public boolean process( + @Override public boolean process( Set annotations, RoundEnvironment env) { for(TypeElement t : annotations) diff --git a/annotations/simplest/SimpleTest.java b/annotations/simplest/SimpleTest.java index e281e42b7..e97d5871e 100644 --- a/annotations/simplest/SimpleTest.java +++ b/annotations/simplest/SimpleTest.java @@ -1,5 +1,5 @@ // annotations/simplest/SimpleTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Test the "Simple" annotation diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 0d99cee33..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,6 +0,0 @@ -build_script: - - gradlew.bat --no-daemon --stacktrace run -# - gradlew.bat --parallel --stacktrace run -# - gradlew.bat --parallel --stacktrace :validating:jmh - -test: off diff --git a/appveyorXX.yml b/appveyorXX.yml new file mode 100644 index 000000000..5e586b07e --- /dev/null +++ b/appveyorXX.yml @@ -0,0 +1,4 @@ +build_script: + - gradlew.bat --no-daemon --stacktrace run + +test: off diff --git a/arrays/AlphabeticSearch.java b/arrays/AlphabeticSearch.java index 305b07db7..a6dea2c2e 100644 --- a/arrays/AlphabeticSearch.java +++ b/arrays/AlphabeticSearch.java @@ -1,5 +1,5 @@ // arrays/AlphabeticSearch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Searching with a Comparator import diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java index 5669bf1d4..b5dc136f8 100644 --- a/arrays/ArrayCopying.java +++ b/arrays/ArrayCopying.java @@ -1,5 +1,5 @@ // arrays/ArrayCopying.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrate Arrays.copy() and Arrays.copyOf() @@ -10,8 +10,7 @@ class Sup { // Superclass private int id; Sup(int n) { id = n; } - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName() + id; } } @@ -26,21 +25,21 @@ public static void main(String[] args) { int[] a1 = new int[SZ]; Arrays.setAll(a1, new Count.Integer()::get); show("a1", a1); - int[] a2 = Arrays.copyOf(a1, a1.length); // [1] + int[] a2 = Arrays.copyOf(a1, a1.length); // [1] // Prove they are distinct arrays: Arrays.fill(a1, 1); show("a1", a1); show("a2", a2); // Create a shorter result: - a2 = Arrays.copyOf(a2, a2.length/2); // [2] + a2 = Arrays.copyOf(a2, a2.length/2); // [2] show("a2", a2); // Allocate more space: a2 = Arrays.copyOf(a2, a2.length + 5); show("a2", a2); // Also copies wrapped arrays: - Integer[] a3 = new Integer[SZ]; // [3] + Integer[] a3 = new Integer[SZ]; // [3] Arrays.setAll(a3, new Count.Integer()::get); Integer[] a4 = Arrays.copyOfRange(a3, 4, 12); show("a4", a4); @@ -62,7 +61,7 @@ public static void main(String[] args) { Arrays.setAll(b2, Sup::new); try { Sub[] d3 = Arrays.copyOf( - b2, b2.length, Sub[].class); // [6] + b2, b2.length, Sub[].class); // [6] } catch(Exception e) { System.out.println(e); } diff --git a/arrays/ArrayOfGenericType.java b/arrays/ArrayOfGenericType.java index 6466df1fd..6c2df8468 100644 --- a/arrays/ArrayOfGenericType.java +++ b/arrays/ArrayOfGenericType.java @@ -1,5 +1,5 @@ // arrays/ArrayOfGenericType.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/arrays/ArrayOfGenerics.java b/arrays/ArrayOfGenerics.java index d41ce8658..8040dfa1f 100644 --- a/arrays/ArrayOfGenerics.java +++ b/arrays/ArrayOfGenerics.java @@ -1,5 +1,5 @@ // arrays/ArrayOfGenerics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/ArrayOptions.java b/arrays/ArrayOptions.java index 0aaa85d53..c313d9a29 100644 --- a/arrays/ArrayOptions.java +++ b/arrays/ArrayOptions.java @@ -1,5 +1,5 @@ // arrays/ArrayOptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Initialization & re-assignment of arrays diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java index e08a694a7..deae72faf 100644 --- a/arrays/ArraySearching.java +++ b/arrays/ArraySearching.java @@ -1,5 +1,5 @@ // arrays/ArraySearching.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using Arrays.binarySearch() diff --git a/arrays/AssemblingMultidimensionalArrays.java b/arrays/AssemblingMultidimensionalArrays.java index 2a4c4b99e..945c338e4 100644 --- a/arrays/AssemblingMultidimensionalArrays.java +++ b/arrays/AssemblingMultidimensionalArrays.java @@ -1,5 +1,5 @@ // arrays/AssemblingMultidimensionalArrays.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating multidimensional arrays diff --git a/arrays/AutoboxingArrays.java b/arrays/AutoboxingArrays.java index 30589cc43..d8601627c 100644 --- a/arrays/AutoboxingArrays.java +++ b/arrays/AutoboxingArrays.java @@ -1,5 +1,5 @@ // arrays/AutoboxingArrays.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/CollectionComparison.java b/arrays/CollectionComparison.java index 66958372f..b5f0b1132 100644 --- a/arrays/CollectionComparison.java +++ b/arrays/CollectionComparison.java @@ -1,5 +1,5 @@ // arrays/CollectionComparison.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -9,8 +9,7 @@ class BerylliumSphere { private static long counter; private final long id = counter++; - @Override - public String toString() { + @Override public String toString() { return "Sphere " + id; } } diff --git a/arrays/CompType.java b/arrays/CompType.java index a93b6aee4..8d7e82a33 100644 --- a/arrays/CompType.java +++ b/arrays/CompType.java @@ -1,5 +1,5 @@ // arrays/CompType.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Implementing Comparable in a class @@ -16,15 +16,13 @@ public CompType(int n1, int n2) { i = n1; j = n2; } - @Override - public String toString() { + @Override public String toString() { String result = "[i = " + i + ", j = " + j + "]"; if(count++ % 3 == 0) result += "\n"; return result; } - @Override - public int compareTo(CompType rv) { + @Override public int compareTo(CompType rv) { return (i < rv.i ? -1 : (i == rv.i ? 0 : 1)); } private static SplittableRandom r = diff --git a/arrays/ComparatorTest.java b/arrays/ComparatorTest.java index 79eb3c721..fbe385879 100644 --- a/arrays/ComparatorTest.java +++ b/arrays/ComparatorTest.java @@ -1,5 +1,5 @@ // arrays/ComparatorTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Implementing a Comparator for a class diff --git a/arrays/ComparingArrays.java b/arrays/ComparingArrays.java index 9a2851f67..c97c22d04 100644 --- a/arrays/ComparingArrays.java +++ b/arrays/ComparingArrays.java @@ -1,5 +1,5 @@ // arrays/ComparingArrays.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using Arrays.equals() diff --git a/arrays/CountUpward.java b/arrays/CountUpward.java index e512104f0..3ac361c86 100644 --- a/arrays/CountUpward.java +++ b/arrays/CountUpward.java @@ -1,5 +1,5 @@ // arrays/CountUpward.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/FillingArrays.java b/arrays/FillingArrays.java index 6c416a0ff..b7445dfdb 100644 --- a/arrays/FillingArrays.java +++ b/arrays/FillingArrays.java @@ -1,5 +1,5 @@ // arrays/FillingArrays.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using Arrays.fill() diff --git a/arrays/IceCreamFlavors.java b/arrays/IceCreamFlavors.java index 73c0813af..1be802edd 100644 --- a/arrays/IceCreamFlavors.java +++ b/arrays/IceCreamFlavors.java @@ -1,5 +1,5 @@ // arrays/IceCreamFlavors.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Returning arrays from methods diff --git a/arrays/ModifyExisting.java b/arrays/ModifyExisting.java index b5a0e8bc7..0c33b8d19 100644 --- a/arrays/ModifyExisting.java +++ b/arrays/ModifyExisting.java @@ -1,5 +1,5 @@ // arrays/ModifyExisting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -11,7 +11,7 @@ public static void main(String[] args) { double[] da = new double[7]; Arrays.setAll(da, new Rand.Double()::get); show(da); - Arrays.setAll(da, n -> da[n] / 100); // [1] + Arrays.setAll(da, n -> da[n] / 100); // [1] show(da); } } diff --git a/arrays/MultiDimWrapperArray.java b/arrays/MultiDimWrapperArray.java index 4f173ddd5..5055a1cbf 100644 --- a/arrays/MultiDimWrapperArray.java +++ b/arrays/MultiDimWrapperArray.java @@ -1,5 +1,5 @@ // arrays/MultiDimWrapperArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Multidimensional arrays of "wrapper" objects diff --git a/arrays/MultidimensionalObjectArrays.java b/arrays/MultidimensionalObjectArrays.java index ab147767b..8c91e7b5a 100644 --- a/arrays/MultidimensionalObjectArrays.java +++ b/arrays/MultidimensionalObjectArrays.java @@ -1,5 +1,5 @@ // arrays/MultidimensionalObjectArrays.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/MultidimensionalPrimitiveArray.java b/arrays/MultidimensionalPrimitiveArray.java index 0294c8b02..ffebf2b6f 100644 --- a/arrays/MultidimensionalPrimitiveArray.java +++ b/arrays/MultidimensionalPrimitiveArray.java @@ -1,5 +1,5 @@ // arrays/MultidimensionalPrimitiveArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/ParallelPrefix1.java b/arrays/ParallelPrefix1.java index 7a34d52ac..243753168 100644 --- a/arrays/ParallelPrefix1.java +++ b/arrays/ParallelPrefix1.java @@ -1,5 +1,5 @@ // arrays/ParallelPrefix1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/ParallelPrefix2.java b/arrays/ParallelPrefix2.java index 08dc8f448..c7963fe83 100644 --- a/arrays/ParallelPrefix2.java +++ b/arrays/ParallelPrefix2.java @@ -1,5 +1,5 @@ // arrays/ParallelPrefix2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/ParallelPrefix3.java b/arrays/ParallelPrefix3.java index cf7c1551d..88d32916e 100644 --- a/arrays/ParallelPrefix3.java +++ b/arrays/ParallelPrefix3.java @@ -1,5 +1,5 @@ // arrays/ParallelPrefix3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromTravisCI} diff --git a/arrays/ParallelSetAll.java b/arrays/ParallelSetAll.java index 6d8c0e974..787d2daf9 100644 --- a/arrays/ParallelSetAll.java +++ b/arrays/ParallelSetAll.java @@ -1,5 +1,5 @@ // arrays/ParallelSetAll.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/ParameterizedArrayType.java b/arrays/ParameterizedArrayType.java index cb84b1375..7213afde5 100644 --- a/arrays/ParameterizedArrayType.java +++ b/arrays/ParameterizedArrayType.java @@ -1,5 +1,5 @@ // arrays/ParameterizedArrayType.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/arrays/PythonLists.py b/arrays/PythonLists.py index d22df21cd..3ed60ee91 100644 --- a/arrays/PythonLists.py +++ b/arrays/PythonLists.py @@ -1,5 +1,5 @@ # arrays/PythonLists.py -# (c)2017 MindView LLC: see Copyright.txt +# (c)2021 MindView LLC: see Copyright.txt # We make no guarantees that this code is fit for any purpose. # Visit http://OnJava8.com for more book information. @@ -20,7 +20,7 @@ def getReversed(self): reversed.reverse() # Built-in list method return reversed -# No 'new' necessary for object creation: +# No 'new' necessary for object creation: {#24-no-new-necessary-for-object-creation} list2 = MyList(aList) print(type(list2)) # print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1] diff --git a/arrays/RaggedArray.java b/arrays/RaggedArray.java index 0877f954c..dfae93d64 100644 --- a/arrays/RaggedArray.java +++ b/arrays/RaggedArray.java @@ -1,5 +1,5 @@ // arrays/RaggedArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -14,7 +14,7 @@ public static void main(String[] args) { a[i] = new int[rand.nextInt(5)][]; for(int j = 0; j < a[i].length; j++) { a[i][j] = new int[rand.nextInt(5)]; - Arrays.setAll(a[i][j], n -> val++); // [1] + Arrays.setAll(a[i][j], n -> val++); // [1] } } System.out.println(Arrays.deepToString(a)); diff --git a/arrays/Reverse.java b/arrays/Reverse.java index a6553e7df..0f2719cec 100644 --- a/arrays/Reverse.java +++ b/arrays/Reverse.java @@ -1,5 +1,5 @@ // arrays/Reverse.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The Collections.reverseOrder() Comparator diff --git a/arrays/SimpleSetAll.java b/arrays/SimpleSetAll.java index 1234eb592..072975b00 100644 --- a/arrays/SimpleSetAll.java +++ b/arrays/SimpleSetAll.java @@ -1,5 +1,5 @@ // arrays/SimpleSetAll.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -8,8 +8,9 @@ class Bob { final int id; Bob(int n) { id = n; } - @Override - public String toString() { return "Bob" + id; } + @Override public String toString() { + return "Bob" + id; + } } public class SimpleSetAll { @@ -22,13 +23,13 @@ public static void main(String[] args) { int[] ia = new int[SZ]; long[] la = new long[SZ]; double[] da = new double[SZ]; - Arrays.setAll(ia, n -> n); // [1] + Arrays.setAll(ia, n -> n); // [1] Arrays.setAll(la, n -> n); Arrays.setAll(da, n -> n); show(ia); show(la); show(da); - Arrays.setAll(ia, n -> val++); // [2] + Arrays.setAll(ia, n -> val++); // [2] Arrays.setAll(la, n -> val++); Arrays.setAll(da, n -> val++); show(ia); @@ -36,11 +37,11 @@ public static void main(String[] args) { show(da); Bob[] ba = new Bob[SZ]; - Arrays.setAll(ba, Bob::new); // [3] + Arrays.setAll(ba, Bob::new); // [3] show(ba); Character[] ca = new Character[SZ]; - Arrays.setAll(ca, SimpleSetAll::getChar); // [4] + Arrays.setAll(ca, SimpleSetAll::getChar); // [4] show(ca); } } diff --git a/arrays/StreamFromArray.java b/arrays/StreamFromArray.java index b7022478b..b30ed6d44 100644 --- a/arrays/StreamFromArray.java +++ b/arrays/StreamFromArray.java @@ -1,5 +1,5 @@ // arrays/StreamFromArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/StringSorting.java b/arrays/StringSorting.java index 7972c7cce..aef57048d 100644 --- a/arrays/StringSorting.java +++ b/arrays/StringSorting.java @@ -1,5 +1,5 @@ // arrays/StringSorting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Sorting an array of Strings diff --git a/arrays/TestConvertTo.java b/arrays/TestConvertTo.java index c7d8fa1b2..8b8f849a5 100644 --- a/arrays/TestConvertTo.java +++ b/arrays/TestConvertTo.java @@ -1,5 +1,5 @@ // arrays/TestConvertTo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/TestCount.java b/arrays/TestCount.java index 9f1b137f2..b6b3e7b8d 100644 --- a/arrays/TestCount.java +++ b/arrays/TestCount.java @@ -1,5 +1,5 @@ // arrays/TestCount.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Test counting generators diff --git a/arrays/TestRand.java b/arrays/TestRand.java index 26da84b45..45d248ade 100644 --- a/arrays/TestRand.java +++ b/arrays/TestRand.java @@ -1,5 +1,5 @@ // arrays/TestRand.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Test random generators diff --git a/arrays/ThreeDWithNew.java b/arrays/ThreeDWithNew.java index 4d093f3ac..f1ab3393a 100644 --- a/arrays/ThreeDWithNew.java +++ b/arrays/ThreeDWithNew.java @@ -1,5 +1,5 @@ // arrays/ThreeDWithNew.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/arrays/jmh/ParallelSort.java b/arrays/jmh/ParallelSort.java index 0475ae142..64ff004d3 100644 --- a/arrays/jmh/ParallelSort.java +++ b/arrays/jmh/ParallelSort.java @@ -1,5 +1,5 @@ // arrays/jmh/ParallelSort.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package arrays.jmh; diff --git a/build.gradle b/build.gradle index afd39a4a6..b4feb13d5 100644 --- a/build.gradle +++ b/build.gradle @@ -5,8 +5,7 @@ buildscript { } } dependencies { - classpath 'me.champeau.gradle:jmh-gradle-plugin:0.3.1' - classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M2' + classpath 'me.champeau.gradle:jmh-gradle-plugin:0.5.2' } } @@ -16,9 +15,9 @@ subprojects { apply from: "$rootProject.projectDir/gradle/java.gradle" apply from: "$rootProject.projectDir/gradle/junit-jupiter.gradle" apply from: "$rootProject.projectDir/gradle/jmh.gradle" - apply from: "$rootProject.projectDir/gradle/checkstyle.gradle" + // apply from: "$rootProject.projectDir/gradle/checkstyle.gradle" apply from: "$rootProject.projectDir/gradle/findbugs.gradle" apply plugin: 'com.mindviewinc.tagging' } -apply from: 'gradle/subprojects.gradle' \ No newline at end of file +apply from: 'gradle/subprojects.gradle' diff --git a/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy b/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy index a72daddee..518a7d5f2 100644 --- a/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy +++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy @@ -26,6 +26,7 @@ class TaggingPlugin implements Plugin { // Exclude java sources that will not compile if (tags.willNotCompile + || tags.newFeature // Uses a feature introduced after Java 8 || (tags.lowLevelAppendix && runningInAppveyor) // Exclude entire lowlevel appendix || (tags.excludeFromAppveyorCI && runningInAppveyor) || (tags.excludeFromTravisCI && runningInTravis) diff --git a/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy b/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy index 9f343be93..f61ed4d79 100644 --- a/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy +++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy @@ -10,6 +10,7 @@ class Tags { Boolean throwsException = false Boolean errorOutputExpected = false Boolean excludeFromGradle = false + Boolean newFeature = false // For language feature introduced after Java 8 Boolean ignoreOutput = false // This tag isn't used in the build... String fileRoot String mainClass @@ -45,6 +46,7 @@ class Tags { throwsException = hasTag('ThrowsException') errorOutputExpected = hasTag('ErrorOutputExpected') excludeFromGradle = hasTag('ExcludeFromGradle') + newFeature = hasTag('NewFeature') ignoreOutput = hasTag('IgnoreOutput') javap = extract('javap') // Includes only arguments to command runFirst = extract('RunFirst:') @@ -83,6 +85,7 @@ class Tags { throwsException || errorOutputExpected || excludeFromGradle || + newFeature || ignoreOutput || javaCmd || args || @@ -105,6 +108,7 @@ class Tags { throwsException errorOutputExpected excludeFromGradle + newFeature ignoreOutput fileRoot mainClass diff --git a/collections/AdapterMethodIdiom.java b/collections/AdapterMethodIdiom.java index a7ebc6167..ffb8fbf5b 100644 --- a/collections/AdapterMethodIdiom.java +++ b/collections/AdapterMethodIdiom.java @@ -1,5 +1,5 @@ // collections/AdapterMethodIdiom.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The "Adapter Method" idiom uses for-in @@ -15,10 +15,12 @@ public Iterable reversed() { public Iterator iterator() { return new Iterator() { int current = size() - 1; - public boolean hasNext() { + @Override public boolean hasNext() { return current > -1; } + @Override public T next() { return get(current--); } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } @@ -31,7 +33,7 @@ public void remove() { // Not implemented public class AdapterMethodIdiom { public static void main(String[] args) { ReversibleArrayList ral = - new ReversibleArrayList( + new ReversibleArrayList<>( Arrays.asList("To be or not to be".split(" "))); // Grabs the ordinary iterator via iterator(): for(String s : ral) diff --git a/collections/AddingGroups.java b/collections/AddingGroups.java index 3561f459d..13fcdcaf1 100644 --- a/collections/AddingGroups.java +++ b/collections/AddingGroups.java @@ -1,5 +1,5 @@ // collections/AddingGroups.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Adding groups of elements to Collection objects diff --git a/collections/ApplesAndOrangesWithGenerics.java b/collections/ApplesAndOrangesWithGenerics.java index bd8cb646a..674ee7b47 100644 --- a/collections/ApplesAndOrangesWithGenerics.java +++ b/collections/ApplesAndOrangesWithGenerics.java @@ -1,5 +1,5 @@ // collections/ApplesAndOrangesWithGenerics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/ApplesAndOrangesWithoutGenerics.java b/collections/ApplesAndOrangesWithoutGenerics.java index 1832b85ac..4cbe23073 100644 --- a/collections/ApplesAndOrangesWithoutGenerics.java +++ b/collections/ApplesAndOrangesWithoutGenerics.java @@ -1,5 +1,5 @@ // collections/ApplesAndOrangesWithoutGenerics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple collection use (suppressing compiler warnings) @@ -24,7 +24,7 @@ public static void main(String[] args) { apples.add(new Orange()); for(Object apple : apples) { ((Apple) apple).id(); - // Orange is detected only at run time + // Orange is detected only at runtime } } } diff --git a/collections/ArrayIsNotIterable.java b/collections/ArrayIsNotIterable.java index 1f1e68140..a9660a67c 100644 --- a/collections/ArrayIsNotIterable.java +++ b/collections/ArrayIsNotIterable.java @@ -1,5 +1,5 @@ // collections/ArrayIsNotIterable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/AsListInference.java b/collections/AsListInference.java index 97f04a4e8..b25ac8e61 100644 --- a/collections/AsListInference.java +++ b/collections/AsListInference.java @@ -1,5 +1,5 @@ // collections/AsListInference.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -16,19 +16,23 @@ public static void main(String[] args) { List snow1 = Arrays.asList( new Crusty(), new Slush(), new Powder()); //- snow1.add(new Heavy()); // Exception + //- snow1.remove(0); // Exception List snow2 = Arrays.asList( new Light(), new Heavy()); //- snow2.add(new Slush()); // Exception + //- snow2.remove(0); // Exception List snow3 = new ArrayList<>(); Collections.addAll(snow3, new Light(), new Heavy(), new Powder()); snow3.add(new Crusty()); + snow3.remove(0); // Hint with explicit type argument specification: List snow4 = Arrays.asList( new Light(), new Heavy(), new Slush()); //- snow4.add(new Powder()); // Exception + //- snow4.remove(0); // Exception } } diff --git a/collections/BasicRecord.java b/collections/BasicRecord.java new file mode 100644 index 000000000..0fa0f2510 --- /dev/null +++ b/collections/BasicRecord.java @@ -0,0 +1,29 @@ +// collections/BasicRecord.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 +import java.util.*; + +record Employee(String name, int id) {} + +public class BasicRecord { + public static void main(String[] args) { + var bob = new Employee("Bob Dobbs", 11); + var dot = new Employee("Dorothy Gale", 9); + // bob.id = 12; // Error: + // id has private access in Employee + System.out.println(bob.name()); // Accessor + System.out.println(bob.id()); // Accessor + System.out.println(bob); // toString() + // Employee works as the key in a Map: + var map = Map.of(bob, "A", dot, "B"); + System.out.println(map); + } +} +/* Output: +Bob Dobbs +11 +Employee[name=Bob Dobbs, id=11] +{Employee[name=Dorothy Gale, id=9]=B, Employee[name=Bob Dobbs, id=11]=A} +*/ diff --git a/collections/CollectionDifferences.java b/collections/CollectionDifferences.java index f3100ad91..a8ea09d01 100644 --- a/collections/CollectionDifferences.java +++ b/collections/CollectionDifferences.java @@ -1,5 +1,5 @@ // collections/CollectionDifferences.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/collections/CollectionSequence.java b/collections/CollectionSequence.java index eafa63683..ea0e45740 100644 --- a/collections/CollectionSequence.java +++ b/collections/CollectionSequence.java @@ -1,21 +1,19 @@ // collections/CollectionSequence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class CollectionSequence extends AbstractCollection { - private Pet[] pets = Pets.array(8); + private Pet[] pets = new PetCreator().array(8); @Override public int size() { return pets.length; } - @Override - public Iterator iterator() { - return new Iterator() { // [1] + @Override public Iterator iterator() { + return new Iterator() { // [1] private int index = 0; - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return index < pets.length; } @Override diff --git a/collections/CompactConstructor.java b/collections/CompactConstructor.java new file mode 100644 index 000000000..017dcbf9b --- /dev/null +++ b/collections/CompactConstructor.java @@ -0,0 +1,16 @@ +// collections/CompactConstructor.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +record Point(int x, int y) { + void assertPositive(int val) { + if(val < 0) + throw new IllegalArgumentException("negative"); + } + Point { // Compact: No parameter list + assertPositive(x); + assertPositive(y); + } +} diff --git a/collections/ComposedRecord.java b/collections/ComposedRecord.java new file mode 100644 index 000000000..1e234b257 --- /dev/null +++ b/collections/ComposedRecord.java @@ -0,0 +1,10 @@ +// collections/ComposedRecord.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +record Company(Employee[] e) {} + +// class Conglomerate extends Company {} +// error: cannot inherit from final Company diff --git a/collections/CopyRecord.java b/collections/CopyRecord.java new file mode 100644 index 000000000..7e2d9dd1b --- /dev/null +++ b/collections/CopyRecord.java @@ -0,0 +1,18 @@ +// collections/CopyRecord.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +record R(int a, double b, char c) {} + +public class CopyRecord { + public static void main(String[] args) { + var r1 = new R(11, 2.2, 'z'); + var r2 = new R(r1.a(), r1.b(), r1.c()); + System.out.println(r1.equals(r2)); + } +} +/* Output: +true +*/ diff --git a/collections/CrossCollectionIteration.java b/collections/CrossCollectionIteration.java index 572fba6bb..2aaf7e95a 100644 --- a/collections/CrossCollectionIteration.java +++ b/collections/CrossCollectionIteration.java @@ -1,8 +1,8 @@ // collections/CrossCollectionIteration.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class CrossCollectionIteration { @@ -14,7 +14,7 @@ public static void display(Iterator it) { System.out.println(); } public static void main(String[] args) { - List pets = Pets.list(8); + List pets = new PetCreator().list(8); LinkedList petsLL = new LinkedList<>(pets); HashSet petsHS = new HashSet<>(pets); TreeSet petsTS = new TreeSet<>(pets); diff --git a/collections/CrossCollectionIteration2.java b/collections/CrossCollectionIteration2.java index 1e51ed3ac..e8aa755d0 100644 --- a/collections/CrossCollectionIteration2.java +++ b/collections/CrossCollectionIteration2.java @@ -1,8 +1,8 @@ // collections/CrossCollectionIteration2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class CrossCollectionIteration2 { @@ -15,7 +15,7 @@ public static void display(Iterable ip) { System.out.println(); } public static void main(String[] args) { - List pets = Pets.list(8); + List pets = new PetCreator().list(8); LinkedList petsLL = new LinkedList<>(pets); HashSet petsHS = new HashSet<>(pets); TreeSet petsTS = new TreeSet<>(pets); diff --git a/collections/EnvironmentVariables.java b/collections/EnvironmentVariables.java index 2ee865f2c..6098e4cfc 100644 --- a/collections/EnvironmentVariables.java +++ b/collections/EnvironmentVariables.java @@ -1,5 +1,5 @@ // collections/EnvironmentVariables.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/collections/FinalFields.java b/collections/FinalFields.java new file mode 100644 index 000000000..1cf0f4f4e --- /dev/null +++ b/collections/FinalFields.java @@ -0,0 +1,12 @@ +// collections/FinalFields.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 +import java.util.*; + +record FinalFields(int i) { + int timesTen() { return i * 10; } + // void tryToChange() { i++; } // Error: + // cannot assign a value to final variable i +} diff --git a/collections/ForInCollections.java b/collections/ForInCollections.java index 2dfbe1b6f..15ea9bb3a 100644 --- a/collections/ForInCollections.java +++ b/collections/ForInCollections.java @@ -1,5 +1,5 @@ // collections/ForInCollections.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // All collections work with for-in diff --git a/collections/GenericTypeInference.java b/collections/GenericTypeInference.java new file mode 100644 index 000000000..83264de2c --- /dev/null +++ b/collections/GenericTypeInference.java @@ -0,0 +1,20 @@ +// collections/GenericTypeInference.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 11 +import java.util.*; + +public class GenericTypeInference { + void old() { + ArrayList apples = new ArrayList<>(); + } + void modern() { + var apples = new ArrayList(); + } + void pitFall() { + var apples = new ArrayList<>(); + apples.add(new Apple()); + apples.get(0); // Comes back as plain Object + } +} diff --git a/collections/GenericsAndUpcasting.java b/collections/GenericsAndUpcasting.java index 0ba792c67..3462e0b76 100644 --- a/collections/GenericsAndUpcasting.java +++ b/collections/GenericsAndUpcasting.java @@ -1,5 +1,5 @@ // collections/GenericsAndUpcasting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -21,8 +21,8 @@ public static void main(String[] args) { } } /* Output: -GrannySmith@15db9742 -Gala@6d06d69c -Fuji@7852e922 -Braeburn@4e25154f +GrannySmith@19e0bfd +Gala@139a55 +Fuji@1db9742 +Braeburn@106d69c */ diff --git a/collections/ImplementingRecord.java b/collections/ImplementingRecord.java new file mode 100644 index 000000000..4a453f775 --- /dev/null +++ b/collections/ImplementingRecord.java @@ -0,0 +1,14 @@ +// collections/ImplementingRecord.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +interface Star { + double brightness(); + double density(); +} + +record RedDwarf(double brightness) implements Star { + @Override public double density() { return 100.0; } +} diff --git a/collections/InterfaceVsIterator.java b/collections/InterfaceVsIterator.java index 8404bfa43..fdb50a588 100644 --- a/collections/InterfaceVsIterator.java +++ b/collections/InterfaceVsIterator.java @@ -1,8 +1,8 @@ // collections/InterfaceVsIterator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class InterfaceVsIterator { @@ -19,7 +19,7 @@ public static void display(Collection pets) { System.out.println(); } public static void main(String[] args) { - List petList = Pets.list(8); + List petList = new PetCreator().list(8); Set petSet = new HashSet<>(petList); Map petMap = new LinkedHashMap<>(); String[] names = ("Ralph, Eric, Robin, Lacey, " + diff --git a/collections/IterableClass.java b/collections/IterableClass.java index 8ef2b65ad..1e64d783a 100644 --- a/collections/IterableClass.java +++ b/collections/IterableClass.java @@ -1,5 +1,5 @@ // collections/IterableClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Anything Iterable works with for-in @@ -9,12 +9,10 @@ public class IterableClass implements Iterable { protected String[] words = ("And that is how " + "we know the Earth to be banana-shaped." ).split(" "); - @Override - public Iterator iterator() { + @Override public Iterator iterator() { return new Iterator() { private int index = 0; - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return index < words.length; } @Override diff --git a/collections/LinkedListFeatures.java b/collections/LinkedListFeatures.java index 8a7b1b79f..489c699f2 100644 --- a/collections/LinkedListFeatures.java +++ b/collections/LinkedListFeatures.java @@ -1,14 +1,14 @@ // collections/LinkedListFeatures.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class LinkedListFeatures { public static void main(String[] args) { LinkedList pets = - new LinkedList<>(Pets.list(5)); + new LinkedList<>(new PetCreator().list(5)); System.out.println(pets); // Identical: System.out.println( @@ -27,9 +27,9 @@ public static void main(String[] args) { System.out.println(pets); pets.addFirst(new Rat()); System.out.println("After addFirst(): " + pets); - pets.offer(Pets.get()); + pets.offer(new PetCreator().get()); System.out.println("After offer(): " + pets); - pets.add(Pets.get()); + pets.add(new PetCreator().get()); System.out.println("After add(): " + pets); pets.addLast(new Hamster()); System.out.println("After addLast(): " + pets); @@ -47,8 +47,8 @@ public static void main(String[] args) { pets.poll(): Cymric [Mutt, Pug] After addFirst(): [Rat, Mutt, Pug] -After offer(): [Rat, Mutt, Pug, Cymric] -After add(): [Rat, Mutt, Pug, Cymric, Pug] -After addLast(): [Rat, Mutt, Pug, Cymric, Pug, Hamster] +After offer(): [Rat, Mutt, Pug, Rat] +After add(): [Rat, Mutt, Pug, Rat, Rat] +After addLast(): [Rat, Mutt, Pug, Rat, Rat, Hamster] pets.removeLast(): Hamster */ diff --git a/collections/ListFeatures.java b/collections/ListFeatures.java index b002d9a8f..12fb6b4f1 100644 --- a/collections/ListFeatures.java +++ b/collections/ListFeatures.java @@ -1,14 +1,14 @@ // collections/ListFeatures.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class ListFeatures { public static void main(String[] args) { Random rand = new Random(47); - List pets = Pets.list(7); + List pets = new PetCreator().list(7); System.out.println("1: " + pets); Hamster h = new Hamster(); pets.add(h); // Automatically resizes @@ -54,7 +54,7 @@ public static void main(String[] args) { pets.clear(); // Remove all elements System.out.println("19: " + pets); System.out.println("20: " + pets.isEmpty()); - pets.addAll(Pets.list(4)); + pets.addAll(new PetCreator().list(4)); System.out.println("21: " + pets); Object[] o = pets.toArray(); System.out.println("22: " + o[3]); @@ -87,7 +87,7 @@ public static void main(String[] args) { 18: false 19: [] 20: true -21: [Manx, Cymric, Rat, EgyptianMau] -22: EgyptianMau +21: [Rat, Manx, Cymric, Mutt] +22: Mutt 23: 14 */ diff --git a/collections/ListIteration.java b/collections/ListIteration.java index 4daa54fd9..4967f5260 100644 --- a/collections/ListIteration.java +++ b/collections/ListIteration.java @@ -1,13 +1,13 @@ // collections/ListIteration.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class ListIteration { public static void main(String[] args) { - List pets = Pets.list(8); + List pets = new PetCreator().list(8); ListIterator it = pets.listIterator(); while(it.hasNext()) System.out.print(it.next() + @@ -22,7 +22,7 @@ public static void main(String[] args) { it = pets.listIterator(3); while(it.hasNext()) { it.next(); - it.set(Pets.get()); + it.set(new PetCreator().get()); } System.out.println(pets); } @@ -32,6 +32,5 @@ public static void main(String[] args) { 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7; 7 6 5 4 3 2 1 0 [Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx] -[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, -EgyptianMau] +[Rat, Manx, Cymric, Rat, Rat, Rat, Rat, Rat] */ diff --git a/collections/MapOfList.java b/collections/MapOfList.java index 224017f86..d7357a6ed 100644 --- a/collections/MapOfList.java +++ b/collections/MapOfList.java @@ -1,10 +1,10 @@ // collections/MapOfList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java collections.MapOfList} package collections; -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class MapOfList { diff --git a/collections/ModifyingArraysAsList.java b/collections/ModifyingArraysAsList.java index 15104eaaa..ef50e40ab 100644 --- a/collections/ModifyingArraysAsList.java +++ b/collections/ModifyingArraysAsList.java @@ -1,5 +1,5 @@ // collections/ModifyingArraysAsList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/MultiIterableClass.java b/collections/MultiIterableClass.java index f90e543d4..3c5e7ae26 100644 --- a/collections/MultiIterableClass.java +++ b/collections/MultiIterableClass.java @@ -1,5 +1,5 @@ // collections/MultiIterableClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Adding several Adapter Methods @@ -11,12 +11,13 @@ public Iterable reversed() { public Iterator iterator() { return new Iterator() { int current = words.length - 1; - public boolean hasNext() { + @Override public boolean hasNext() { return current > -1; } - public String next() { + @Override public String next() { return words[current--]; } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } @@ -28,7 +29,7 @@ public Iterable randomized() { return new Iterable() { public Iterator iterator() { List shuffled = - new ArrayList(Arrays.asList(words)); + new ArrayList<>(Arrays.asList(words)); Collections.shuffle(shuffled, new Random(47)); return shuffled.iterator(); } diff --git a/collections/NestedLocalRecords.java b/collections/NestedLocalRecords.java new file mode 100644 index 000000000..5ae375668 --- /dev/null +++ b/collections/NestedLocalRecords.java @@ -0,0 +1,12 @@ +// collections/NestedLocalRecords.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +public class NestedLocalRecords { + record Nested(String s) {} + void method() { + record Local(String s) {} + } +} diff --git a/collections/NonCollectionSequence.java b/collections/NonCollectionSequence.java index 8ed7a2de5..dc8678274 100644 --- a/collections/NonCollectionSequence.java +++ b/collections/NonCollectionSequence.java @@ -1,20 +1,19 @@ // collections/NonCollectionSequence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; class PetSequence { - protected Pet[] pets = Pets.array(8); + protected Pet[] pets = new PetCreator().array(8); } public class NonCollectionSequence extends PetSequence { public Iterator iterator() { return new Iterator() { private int index = 0; - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return index < pets.length; } @Override diff --git a/collections/NormalConstructor.java b/collections/NormalConstructor.java new file mode 100644 index 000000000..da926b643 --- /dev/null +++ b/collections/NormalConstructor.java @@ -0,0 +1,11 @@ +// collections/NormalConstructor.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +record Value(int x) { + Value(int x) { // With the parameter list + this.x = x; // Must explicitly initialize + } +} diff --git a/collections/PetMap.java b/collections/PetMap.java index 8a9a90962..dc64bf574 100644 --- a/collections/PetMap.java +++ b/collections/PetMap.java @@ -1,8 +1,8 @@ // collections/PetMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class PetMap { diff --git a/collections/PlusTen.java b/collections/PlusTen.java new file mode 100644 index 000000000..a52bfed5b --- /dev/null +++ b/collections/PlusTen.java @@ -0,0 +1,20 @@ +// collections/PlusTen.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +record PlusTen(int x) { + PlusTen { + x += 10; + } + // Adjustment to field can only happen in + // the constructor. Still not legal: + // void mutate() { x += 10; } + public static void main(String[] args) { + System.out.println(new PlusTen(10)); + } +} +/* Output: +PlusTen[x=20] +*/ diff --git a/collections/PrintingCollections.java b/collections/PrintingCollections.java index 72e39b6df..c324722a9 100644 --- a/collections/PrintingCollections.java +++ b/collections/PrintingCollections.java @@ -1,5 +1,5 @@ // collections/PrintingCollections.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Collections print themselves automatically diff --git a/collections/PriorityQueueDemo.java b/collections/PriorityQueueDemo.java index 024ec51f6..0e0f553ef 100644 --- a/collections/PriorityQueueDemo.java +++ b/collections/PriorityQueueDemo.java @@ -1,5 +1,5 @@ // collections/PriorityQueueDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/QueueDemo.java b/collections/QueueDemo.java index 31a5a5e2a..a7d30c1c4 100644 --- a/collections/QueueDemo.java +++ b/collections/QueueDemo.java @@ -1,5 +1,5 @@ // collections/QueueDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Upcasting to a Queue from a LinkedList diff --git a/collections/SetOfInteger.java b/collections/SetOfInteger.java index 68553c65b..92a403e6c 100644 --- a/collections/SetOfInteger.java +++ b/collections/SetOfInteger.java @@ -1,5 +1,5 @@ // collections/SetOfInteger.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/SetOfString.java b/collections/SetOfString.java index d6f980e06..50a06bc20 100644 --- a/collections/SetOfString.java +++ b/collections/SetOfString.java @@ -1,5 +1,5 @@ // collections/SetOfString.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/SetOperations.java b/collections/SetOperations.java index 492658773..485588b6c 100644 --- a/collections/SetOperations.java +++ b/collections/SetOperations.java @@ -1,5 +1,5 @@ // collections/SetOperations.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/SimpleCollection.java b/collections/SimpleCollection.java index e0187dc86..6dcf73b24 100644 --- a/collections/SimpleCollection.java +++ b/collections/SimpleCollection.java @@ -1,5 +1,5 @@ // collections/SimpleCollection.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/SimpleIteration.java b/collections/SimpleIteration.java index d47e4711f..089774963 100644 --- a/collections/SimpleIteration.java +++ b/collections/SimpleIteration.java @@ -1,13 +1,13 @@ // collections/SimpleIteration.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class SimpleIteration { public static void main(String[] args) { - List pets = Pets.list(12); + List pets = new PetCreator().list(12); Iterator it = pets.iterator(); while(it.hasNext()) { Pet p = it.next(); diff --git a/collections/SortedSetOfString.java b/collections/SortedSetOfString.java index b2a0603bd..af6222aac 100644 --- a/collections/SortedSetOfString.java +++ b/collections/SortedSetOfString.java @@ -1,5 +1,5 @@ // collections/SortedSetOfString.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/StackCollision.java b/collections/StackCollision.java index 11fd340e8..7914e3496 100644 --- a/collections/StackCollision.java +++ b/collections/StackCollision.java @@ -1,5 +1,5 @@ // collections/StackCollision.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/collections/StackTest.java b/collections/StackTest.java index bc9e9305c..54005700a 100644 --- a/collections/StackTest.java +++ b/collections/StackTest.java @@ -1,5 +1,5 @@ // collections/StackTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/StackTest2.java b/collections/StackTest2.java index 303f856d6..148a834a8 100644 --- a/collections/StackTest2.java +++ b/collections/StackTest2.java @@ -1,5 +1,5 @@ // collections/StackTest2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/collections/Statistics.java b/collections/Statistics.java index 38a42ef3c..a3ece359e 100644 --- a/collections/Statistics.java +++ b/collections/Statistics.java @@ -1,5 +1,5 @@ // collections/Statistics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple demonstration of HashMap @@ -12,7 +12,7 @@ public static void main(String[] args) { for(int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: int r = rand.nextInt(20); - Integer freq = m.get(r); // [1] + Integer freq = m.get(r); // [1] m.put(r, freq == null ? 1 : freq + 1); } System.out.println(m); diff --git a/collections/UniqueWords.java b/collections/UniqueWords.java index 355accc75..e39a9b882 100644 --- a/collections/UniqueWords.java +++ b/collections/UniqueWords.java @@ -1,5 +1,5 @@ // collections/UniqueWords.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collections/UniqueWordsAlphabetic.java b/collections/UniqueWordsAlphabetic.java index e0db4a163..780ddb3f1 100644 --- a/collections/UniqueWordsAlphabetic.java +++ b/collections/UniqueWordsAlphabetic.java @@ -1,5 +1,5 @@ // collections/UniqueWordsAlphabetic.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Producing an alphabetic listing diff --git a/collectiontopics/AssociativeArray.java b/collectiontopics/AssociativeArray.java index 772f36d3e..37c09da89 100644 --- a/collectiontopics/AssociativeArray.java +++ b/collectiontopics/AssociativeArray.java @@ -1,5 +1,5 @@ // collectiontopics/AssociativeArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Associates keys with values @@ -22,8 +22,7 @@ public V get(K key) { return (V)pairs[i][1]; return null; // Did not find key } - @Override - public String toString() { + @Override public String toString() { StringBuilder result = new StringBuilder(); for(int i = 0; i < index; i++) { result.append(pairs[i][0].toString()); diff --git a/collectiontopics/Bits.java b/collectiontopics/Bits.java index f3c4d3904..f4f6d506a 100644 --- a/collectiontopics/Bits.java +++ b/collectiontopics/Bits.java @@ -1,5 +1,5 @@ // collectiontopics/Bits.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstration of BitSet diff --git a/collectiontopics/CanonicalMapping.java b/collectiontopics/CanonicalMapping.java index fecd6d3cb..f464599b5 100644 --- a/collectiontopics/CanonicalMapping.java +++ b/collectiontopics/CanonicalMapping.java @@ -1,55 +1,32 @@ // collectiontopics/CanonicalMapping.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates WeakHashMap import java.util.*; - -class Element { - private String ident; - Element(String id) { ident = id; } - @Override - public String toString() { return ident; } - @Override - public int hashCode() { - return Objects.hashCode(ident); - } - @Override - public boolean equals(Object r) { - return r instanceof Element && - Objects.equals(ident, ((Element)r).ident); - } - @Override - protected void finalize() { - System.out.println("Finalizing " + - getClass().getSimpleName() + " " + ident); - } -} - -class Key extends Element { - Key(String id) { super(id); } -} - -class Value extends Element { - Value(String id) { super(id); } -} +import java.util.stream.*; public class CanonicalMapping { + static void showKeys(Map m) { + // Display sorted keys + List keys = new ArrayList<>(m.keySet()); + Collections.sort(keys); + System.out.println(keys); + } public static void main(String[] args) { - int size = 1000; - // Or, choose size via the command line: - if(args.length > 0) - size = Integer.valueOf(args[0]); - Key[] keys = new Key[size]; - WeakHashMap map = + int size = 100; + String[] savedKeys = new String[size]; + WeakHashMap map = new WeakHashMap<>(); for(int i = 0; i < size; i++) { - Key k = new Key(Integer.toString(i)); - Value v = new Value(Integer.toString(i)); + String key = String.format("%03d", i); + String value = Integer.toString(i); if(i % 3 == 0) - keys[i] = k; // Save as "real" references - map.put(k, v); + savedKeys[i] = key; // Save as "real" references + map.put(key, value); } + showKeys(map); System.gc(); + showKeys(map); } } diff --git a/collectiontopics/CollectionMethods.java b/collectiontopics/CollectionMethods.java index 1bf8691ea..08660e62e 100644 --- a/collectiontopics/CollectionMethods.java +++ b/collectiontopics/CollectionMethods.java @@ -1,5 +1,5 @@ // collectiontopics/CollectionMethods.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Things you can do with all Collections @@ -56,8 +56,7 @@ public static void main(String[] args) { // c2 and c3 (an intersection of sets): c2.retainAll(c3); show(c2); - // Throw away all the elements - // in c2 that also appear in c3: + // Discard all c2 elements that also appear in c3: c2.removeAll(c3); System.out.println( "c2.isEmpty() = " + c2.isEmpty()); diff --git a/collectiontopics/Enumerations.java b/collectiontopics/Enumerations.java index e66385932..63d740590 100644 --- a/collectiontopics/Enumerations.java +++ b/collectiontopics/Enumerations.java @@ -1,5 +1,5 @@ // collectiontopics/Enumerations.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Java 1.0/1.1 Vector and Enumeration diff --git a/collectiontopics/FailFast.java b/collectiontopics/FailFast.java index 8a93867c9..9425de28d 100644 --- a/collectiontopics/FailFast.java +++ b/collectiontopics/FailFast.java @@ -1,5 +1,5 @@ // collectiontopics/FailFast.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates the "fail-fast" behavior diff --git a/collectiontopics/FillMapTest.java b/collectiontopics/FillMapTest.java index 0259a2738..e96d0263b 100644 --- a/collectiontopics/FillMapTest.java +++ b/collectiontopics/FillMapTest.java @@ -1,5 +1,5 @@ // collectiontopics/FillMapTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collectiontopics/FillingLists.java b/collectiontopics/FillingLists.java index af158de1f..29123d01f 100644 --- a/collectiontopics/FillingLists.java +++ b/collectiontopics/FillingLists.java @@ -1,5 +1,5 @@ // collectiontopics/FillingLists.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Collections.fill() & Collections.nCopies() @@ -8,8 +8,7 @@ class StringAddress { private String s; StringAddress(String s) { this.s = s; } - @Override - public String toString() { + @Override public String toString() { return super.toString() + " " + s; } } @@ -26,10 +25,10 @@ public static void main(String[] args) { } } /* Output: -[StringAddress@15db9742 Hello, StringAddress@15db9742 -Hello, StringAddress@15db9742 Hello, -StringAddress@15db9742 Hello] -[StringAddress@6d06d69c World!, StringAddress@6d06d69c -World!, StringAddress@6d06d69c World!, -StringAddress@6d06d69c World!] +[StringAddress@19e0bfd Hello, StringAddress@19e0bfd +Hello, StringAddress@19e0bfd Hello, +StringAddress@19e0bfd Hello] +[StringAddress@139a55 World!, StringAddress@139a55 +World!, StringAddress@139a55 World!, +StringAddress@139a55 World!] */ diff --git a/collectiontopics/FunctionalMap.java b/collectiontopics/FunctionalMap.java index 16abb45b0..ef9b48086 100644 --- a/collectiontopics/FunctionalMap.java +++ b/collectiontopics/FunctionalMap.java @@ -1,5 +1,5 @@ // collectiontopics/FunctionalMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Functional operations on a Map diff --git a/collectiontopics/HTMLColorTest.java b/collectiontopics/HTMLColorTest.java index 517ee575c..cdfeb5bed 100644 --- a/collectiontopics/HTMLColorTest.java +++ b/collectiontopics/HTMLColorTest.java @@ -1,5 +1,5 @@ // collectiontopics/HTMLColorTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import static onjava.HTMLColors.*; diff --git a/collectiontopics/LinkedHashMapDemo.java b/collectiontopics/LinkedHashMapDemo.java index 70e1db15c..7e9bc16a5 100644 --- a/collectiontopics/LinkedHashMapDemo.java +++ b/collectiontopics/LinkedHashMapDemo.java @@ -1,5 +1,5 @@ // collectiontopics/LinkedHashMapDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // What you can do with a LinkedHashMap diff --git a/collectiontopics/ListOps.java b/collectiontopics/ListOps.java index 760652b57..dee92d5e5 100644 --- a/collectiontopics/ListOps.java +++ b/collectiontopics/ListOps.java @@ -1,5 +1,5 @@ // collectiontopics/ListOps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Things you can do with Lists diff --git a/collectiontopics/ListSortSearch.java b/collectiontopics/ListSortSearch.java index d59bc6439..2f2ca2d7e 100644 --- a/collectiontopics/ListSortSearch.java +++ b/collectiontopics/ListSortSearch.java @@ -1,5 +1,5 @@ // collectiontopics/ListSortSearch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Sorting/searching Lists with Collections utilities @@ -13,9 +13,9 @@ public static void main(String[] args) { System.out.println(list); Collections.shuffle(list, new Random(47)); System.out.println("Shuffled: " + list); - // Use ListIterator to trim off last elements: - ListIterator it = list.listIterator(10); - while(it.hasNext()) { + ListIterator it = + list.listIterator(10); // [1] + while(it.hasNext()) { // [2] it.next(); it.remove(); } diff --git a/collectiontopics/MapOps.java b/collectiontopics/MapOps.java index c49cb84a2..6b6458bb2 100644 --- a/collectiontopics/MapOps.java +++ b/collectiontopics/MapOps.java @@ -1,5 +1,5 @@ // collectiontopics/MapOps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Things you can do with Maps diff --git a/collectiontopics/NavMap.java b/collectiontopics/NavMap.java index 0f682b8a3..2d898268b 100644 --- a/collectiontopics/NavMap.java +++ b/collectiontopics/NavMap.java @@ -1,5 +1,5 @@ // collectiontopics/NavMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // NavigableMap produces pieces of a Map diff --git a/collectiontopics/QueueBehavior.java b/collectiontopics/QueueBehavior.java index 923eab610..16f7582e2 100644 --- a/collectiontopics/QueueBehavior.java +++ b/collectiontopics/QueueBehavior.java @@ -1,5 +1,5 @@ // collectiontopics/QueueBehavior.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Compares basic behavior @@ -15,7 +15,7 @@ static Stream strings() { } static void test(int id, Queue queue) { System.out.print(id + ": "); - strings().map(queue::offer).count(); + strings().forEach(queue::offer); while(queue.peek() != null) System.out.print(queue.remove() + " "); System.out.println(); diff --git a/collectiontopics/ReadOnly.java b/collectiontopics/ReadOnly.java index 925cb8198..547c32a5f 100644 --- a/collectiontopics/ReadOnly.java +++ b/collectiontopics/ReadOnly.java @@ -1,5 +1,5 @@ // collectiontopics/ReadOnly.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using the Collections.unmodifiable methods diff --git a/collectiontopics/References.java b/collectiontopics/References.java index e95cce2d5..798e8f31e 100644 --- a/collectiontopics/References.java +++ b/collectiontopics/References.java @@ -1,5 +1,5 @@ // collectiontopics/References.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates Reference objects @@ -11,10 +11,9 @@ class VeryBig { private long[] la = new long[SIZE]; private String ident; VeryBig(String id) { ident = id; } - @Override - public String toString() { return ident; } - @Override - protected void finalize() { + @Override public String toString() { return ident; } + @SuppressWarnings("deprecation") + @Override protected void finalize() { System.out.println("Finalizing " + ident); } } @@ -67,25 +66,25 @@ public static void main(String[] args) { } } /* Output: (First and Last 10 Lines) -Just created: java.lang.ref.SoftReference@15db9742 -Just created: java.lang.ref.SoftReference@6d06d69c -Just created: java.lang.ref.SoftReference@7852e922 -Just created: java.lang.ref.SoftReference@4e25154f -Just created: java.lang.ref.SoftReference@70dea4e -Just created: java.lang.ref.SoftReference@5c647e05 -Just created: java.lang.ref.SoftReference@33909752 -Just created: java.lang.ref.SoftReference@55f96302 -Just created: java.lang.ref.SoftReference@3d4eac69 -Just created: java.lang.ref.SoftReference@42a57993 +Just created: java.lang.ref.SoftReference@19e0bfd +Just created: java.lang.ref.SoftReference@139a55 +Just created: java.lang.ref.SoftReference@1db9742 +Just created: java.lang.ref.SoftReference@106d69c +Just created: java.lang.ref.SoftReference@52e922 +Just created: java.lang.ref.SoftReference@25154f +Just created: java.lang.ref.SoftReference@10dea4e +Just created: java.lang.ref.SoftReference@647e05 +Just created: java.lang.ref.SoftReference@1909752 +Just created: java.lang.ref.SoftReference@1f96302 ...________...________...________...________... -Just created: java.lang.ref.PhantomReference@45ee12a7 +Just created: java.lang.ref.PhantomReference@16f6e28 In queue: null -Just created: java.lang.ref.PhantomReference@330bedb4 +Just created: java.lang.ref.PhantomReference@15fbaa4 In queue: null -Just created: java.lang.ref.PhantomReference@2503dbd3 +Just created: java.lang.ref.PhantomReference@1ee12a7 In queue: null -Just created: java.lang.ref.PhantomReference@4b67cf4d +Just created: java.lang.ref.PhantomReference@10bedb4 In queue: null -Just created: java.lang.ref.PhantomReference@7ea987ac +Just created: java.lang.ref.PhantomReference@103dbd3 In queue: null */ diff --git a/collectiontopics/SetOrder.java b/collectiontopics/SetOrder.java index fb4fcf4de..b167a7c72 100644 --- a/collectiontopics/SetOrder.java +++ b/collectiontopics/SetOrder.java @@ -1,5 +1,5 @@ // collectiontopics/SetOrder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -25,7 +25,7 @@ public class SetOrder { type.substring(type.lastIndexOf('.') + 1)); @SuppressWarnings("unchecked") Set set = (Set) - Class.forName(type).newInstance(); + Class.forName(type).getConstructor().newInstance(); set.addAll(RLIST); set.stream() .limit(10) diff --git a/collectiontopics/SimpleDeques.java b/collectiontopics/SimpleDeques.java index 119ecc5b7..811c43daa 100644 --- a/collectiontopics/SimpleDeques.java +++ b/collectiontopics/SimpleDeques.java @@ -1,5 +1,5 @@ // collectiontopics/SimpleDeques.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Very basic test of Deques @@ -11,8 +11,7 @@ class CountString implements Supplier { private int n = 0; CountString() {} CountString(int start) { n = start; } - @Override - public String get() { + @Override public String get() { return Integer.toString(n++); } } diff --git a/collectiontopics/SortedMapDemo.java b/collectiontopics/SortedMapDemo.java index 90e1e297e..5601aca04 100644 --- a/collectiontopics/SortedMapDemo.java +++ b/collectiontopics/SortedMapDemo.java @@ -1,5 +1,5 @@ // collectiontopics/SortedMapDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // What you can do with a TreeMap diff --git a/collectiontopics/SortedSetDemo.java b/collectiontopics/SortedSetDemo.java index 837978d46..91a9b3a54 100644 --- a/collectiontopics/SortedSetDemo.java +++ b/collectiontopics/SortedSetDemo.java @@ -1,5 +1,5 @@ // collectiontopics/SortedSetDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/collectiontopics/Stacks.java b/collectiontopics/Stacks.java index da56e8b7f..a9d306ed3 100644 --- a/collectiontopics/Stacks.java +++ b/collectiontopics/Stacks.java @@ -1,5 +1,5 @@ // collectiontopics/Stacks.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstration of Stack Class diff --git a/collectiontopics/StreamFillMaps.java b/collectiontopics/StreamFillMaps.java index 6e568e9fb..6df827332 100644 --- a/collectiontopics/StreamFillMaps.java +++ b/collectiontopics/StreamFillMaps.java @@ -1,5 +1,5 @@ // collectiontopics/StreamFillMaps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -11,8 +11,7 @@ class Letters implements Supplier> { private int number = 1; private char letter = 'A'; - @Override - public Pair get() { + @Override public Pair get() { return new Pair<>(number++, "" + letter++); } } diff --git a/collectiontopics/SuppliersCollectionTest.java b/collectiontopics/SuppliersCollectionTest.java index f8b42a874..58f810bff 100644 --- a/collectiontopics/SuppliersCollectionTest.java +++ b/collectiontopics/SuppliersCollectionTest.java @@ -1,5 +1,5 @@ // collectiontopics/SuppliersCollectionTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -13,8 +13,7 @@ class Government implements Supplier { "distributing swords is no basis " + "for a system of government").split(" "); private int index; - @Override - public String get() { + @Override public String get() { return foundation[index++]; } } diff --git a/collectiontopics/Synchronization.java b/collectiontopics/Synchronization.java index 768f013df..86389da1c 100644 --- a/collectiontopics/Synchronization.java +++ b/collectiontopics/Synchronization.java @@ -1,5 +1,5 @@ // collectiontopics/Synchronization.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using the Collections.synchronized methods diff --git a/collectiontopics/ToDoList.java b/collectiontopics/ToDoList.java index 1da979ba2..2be266eeb 100644 --- a/collectiontopics/ToDoList.java +++ b/collectiontopics/ToDoList.java @@ -1,5 +1,5 @@ // collectiontopics/ToDoList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A more complex use of PriorityQueue @@ -14,8 +14,7 @@ class ToDoItem implements Comparable { secondary = sec; item = td; } - @Override - public int compareTo(ToDoItem arg) { + @Override public int compareTo(ToDoItem arg) { if(primary > arg.primary) return +1; if(primary == arg.primary) @@ -25,8 +24,7 @@ else if(secondary == arg.secondary) return 0; return -1; } - @Override - public String toString() { + @Override public String toString() { return Character.toString(primary) + secondary + ": " + item; } diff --git a/collectiontopics/TypesForSets.java b/collectiontopics/TypesForSets.java index b7840f64c..e4c745879 100644 --- a/collectiontopics/TypesForSets.java +++ b/collectiontopics/TypesForSets.java @@ -1,5 +1,5 @@ // collectiontopics/TypesForSets.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Methods necessary to put your own type in a Set @@ -10,21 +10,18 @@ class SetType { protected int i; SetType(int n) { i = n; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof SetType && Objects.equals(i, ((SetType)o).i); } - @Override - public String toString() { + @Override public String toString() { return Integer.toString(i); } } class HashType extends SetType { HashType(int n) { super(n); } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hashCode(i); } } @@ -32,8 +29,7 @@ public int hashCode() { class TreeType extends SetType implements Comparable { TreeType(int n) { super(n); } - @Override - public int compareTo(TreeType arg) { + @Override public int compareTo(TreeType arg) { return Integer.compare(arg.i, i); // Equivalent to: // return arg.i < i ? -1 : (arg.i == i ? 0 : 1); @@ -80,10 +76,10 @@ public static void main(String[] args) { [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [10, 9, 8, 7, 6, 5, 0, 1, 2, 3, 4] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] -[1, 6, 8, 6, 2, 7, 8, 9, 4, 10, 7, 5, 1, 3, 4, 9, 9, -10, 5, 3, 2, 0, 4, 1, 2, 0, 8, 3, 0, 10, 6, 5, 7] -[3, 1, 4, 8, 7, 6, 9, 5, 3, 0, 10, 5, 5, 10, 7, 8, 8, -9, 1, 4, 10, 2, 6, 9, 1, 6, 0, 3, 2, 0, 7, 2, 4] +[4, 1, 5, 1, 0, 5, 6, 8, 7, 0, 2, 8, 4, 9, 6, 10, 6, 7, +2, 9, 10, 3, 8, 4, 10, 3, 9, 5, 3, 7, 1, 2, 0] +[9, 8, 4, 8, 5, 0, 1, 6, 2, 9, 3, 7, 2, 2, 7, 0, 9, 5, +5, 6, 4, 7, 10, 1, 6, 4, 1, 10, 3, 3, 0, 10, 8] [10, 9, 8, 7, 6, 5, 0, 1, 2, 3, 4, 10, 9, 8, 7, 6, 5, 0, 1, 2, 3, 4, 10, 9, 8, 7, 6, 5, 0, 1, 2, 3, 4] [10, 9, 8, 7, 6, 5, 0, 1, 2, 3, 4, 10, 9, 8, 7, 6, 5, diff --git a/collectiontopics/Unsupported.java b/collectiontopics/Unsupported.java index fba5dafd1..132b760c4 100644 --- a/collectiontopics/Unsupported.java +++ b/collectiontopics/Unsupported.java @@ -1,5 +1,5 @@ // collectiontopics/Unsupported.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Unsupported operations in Java collections diff --git a/collectiontopics/Utilities.java b/collectiontopics/Utilities.java index c2b94bac9..0b7b0f9a0 100644 --- a/collectiontopics/Utilities.java +++ b/collectiontopics/Utilities.java @@ -1,5 +1,5 @@ // collectiontopics/Utilities.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple demonstrations of the Collections utilities diff --git a/com/mindviewinc/simple/List.java b/com/mindviewinc/simple/List.java index 065ff8437..2b1131a03 100644 --- a/com/mindviewinc/simple/List.java +++ b/com/mindviewinc/simple/List.java @@ -1,5 +1,5 @@ // com/mindviewinc/simple/List.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating a package diff --git a/com/mindviewinc/simple/Vector.java b/com/mindviewinc/simple/Vector.java index db50ba121..af63e03c7 100644 --- a/com/mindviewinc/simple/Vector.java +++ b/com/mindviewinc/simple/Vector.java @@ -1,5 +1,5 @@ // com/mindviewinc/simple/Vector.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating a package diff --git a/compression/GZIPcompress.java b/compression/GZIPcompress.java index 0a669a913..1b847c57b 100644 --- a/compression/GZIPcompress.java +++ b/compression/GZIPcompress.java @@ -1,5 +1,5 @@ // compression/GZIPcompress.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java GZIPcompress GZIPcompress.java} diff --git a/compression/ZipCompress.java b/compression/ZipCompress.java index a8168e7c4..532316029 100644 --- a/compression/ZipCompress.java +++ b/compression/ZipCompress.java @@ -1,5 +1,5 @@ // compression/ZipCompress.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Uses Zip compression to compress any diff --git a/concurrent/Baked.java b/concurrent/Baked.java index c4b1ed0da..105a887d5 100644 --- a/concurrent/Baked.java +++ b/concurrent/Baked.java @@ -1,5 +1,5 @@ // concurrent/Baked.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/Batter.java b/concurrent/Batter.java index 8a814ae75..80a9022a3 100644 --- a/concurrent/Batter.java +++ b/concurrent/Batter.java @@ -1,5 +1,5 @@ // concurrent/Batter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/Breakable.java b/concurrent/Breakable.java index a3b632d7f..0fcacb383 100644 --- a/concurrent/Breakable.java +++ b/concurrent/Breakable.java @@ -1,5 +1,5 @@ // concurrent/Breakable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -11,8 +11,7 @@ public Breakable(String id, int failcount) { this.id = id; this.failcount = failcount; } - @Override - public String toString() { + @Override public String toString() { return "Breakable_" + id + " [" + failcount + "]"; } diff --git a/concurrent/CachedThreadPool.java b/concurrent/CachedThreadPool.java index 15dac382f..11b6bad3a 100644 --- a/concurrent/CachedThreadPool.java +++ b/concurrent/CachedThreadPool.java @@ -1,5 +1,5 @@ // concurrent/CachedThreadPool.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -16,14 +16,14 @@ public static void main(String[] args) { } } /* Output: -NapTask[7] pool-1-thread-8 -NapTask[4] pool-1-thread-5 NapTask[1] pool-1-thread-2 -NapTask[3] pool-1-thread-4 -NapTask[0] pool-1-thread-1 +NapTask[5] pool-1-thread-6 +NapTask[4] pool-1-thread-5 NapTask[8] pool-1-thread-9 -NapTask[2] pool-1-thread-3 +NapTask[0] pool-1-thread-1 NapTask[9] pool-1-thread-10 +NapTask[2] pool-1-thread-3 +NapTask[3] pool-1-thread-4 NapTask[6] pool-1-thread-7 -NapTask[5] pool-1-thread-6 +NapTask[7] pool-1-thread-8 */ diff --git a/concurrent/CachedThreadPool2.java b/concurrent/CachedThreadPool2.java index a5b29a52a..091241e57 100644 --- a/concurrent/CachedThreadPool2.java +++ b/concurrent/CachedThreadPool2.java @@ -1,5 +1,5 @@ // concurrent/CachedThreadPool2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -16,14 +16,14 @@ public static void main(String[] args) { } } /* Output: -0 pool-1-thread-1 200 -1 pool-1-thread-2 200 -4 pool-1-thread-5 300 -5 pool-1-thread-6 400 -8 pool-1-thread-9 500 -9 pool-1-thread-10 600 -2 pool-1-thread-3 700 -7 pool-1-thread-8 800 -3 pool-1-thread-4 900 -6 pool-1-thread-7 1000 +3 pool-1-thread-4 100 +2 pool-1-thread-3 200 +6 pool-1-thread-7 300 +7 pool-1-thread-8 400 +0 pool-1-thread-1 514 +1 pool-1-thread-2 527 +4 pool-1-thread-5 627 +5 pool-1-thread-6 727 +9 pool-1-thread-10 827 +8 pool-1-thread-9 927 */ diff --git a/concurrent/CachedThreadPool3.java b/concurrent/CachedThreadPool3.java index 550914e1a..919c3c130 100644 --- a/concurrent/CachedThreadPool3.java +++ b/concurrent/CachedThreadPool3.java @@ -1,5 +1,5 @@ // concurrent/CachedThreadPool3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -33,15 +33,15 @@ public static void main(String[] args) } } /* Output: -1 pool-1-thread-2 100 0 pool-1-thread-1 100 -4 pool-1-thread-5 100 -5 pool-1-thread-6 100 -8 pool-1-thread-9 100 -9 pool-1-thread-10 100 +9 pool-1-thread-1 100 +1 pool-1-thread-2 100 2 pool-1-thread-3 100 3 pool-1-thread-4 100 6 pool-1-thread-7 100 7 pool-1-thread-8 100 +4 pool-1-thread-5 100 +5 pool-1-thread-6 100 +8 pool-1-thread-9 100 sum = 1000 */ diff --git a/concurrent/CatchCompletableExceptions.java b/concurrent/CatchCompletableExceptions.java index ed180ee8c..5c9bcd610 100644 --- a/concurrent/CatchCompletableExceptions.java +++ b/concurrent/CatchCompletableExceptions.java @@ -1,5 +1,5 @@ // concurrent/CatchCompletableExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/CollectionIntoStream.java b/concurrent/CollectionIntoStream.java index 2ddf4ed2d..4e2f5b3c8 100644 --- a/concurrent/CollectionIntoStream.java +++ b/concurrent/CollectionIntoStream.java @@ -1,5 +1,5 @@ // concurrent/CollectionIntoStream.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/concurrent/CompletableApply.java b/concurrent/CompletableApply.java index 3173d0260..aeac0e25e 100644 --- a/concurrent/CompletableApply.java +++ b/concurrent/CompletableApply.java @@ -1,5 +1,5 @@ // concurrent/CompletableApply.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/CompletableApplyAsync.java b/concurrent/CompletableApplyAsync.java index 2698595ad..974d99ffe 100644 --- a/concurrent/CompletableApplyAsync.java +++ b/concurrent/CompletableApplyAsync.java @@ -1,5 +1,5 @@ // concurrent/CompletableApplyAsync.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -21,11 +21,11 @@ public static void main(String[] args) { } } /* Output: -116 +103 Machina0: ONE Machina0: TWO Machina0: THREE Machina0: complete Machina0: complete -552 +545 */ diff --git a/concurrent/CompletableApplyChained.java b/concurrent/CompletableApplyChained.java index acb6f8a7c..6194bc5d8 100644 --- a/concurrent/CompletableApplyChained.java +++ b/concurrent/CompletableApplyChained.java @@ -1,5 +1,5 @@ // concurrent/CompletableApplyChained.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -23,5 +23,5 @@ public static void main(String[] args) { Machina0: TWO Machina0: THREE Machina0: complete -514 +521 */ diff --git a/concurrent/CompletableExceptions.java b/concurrent/CompletableExceptions.java index e7bac94bc..341a0afc6 100644 --- a/concurrent/CompletableExceptions.java +++ b/concurrent/CompletableExceptions.java @@ -1,5 +1,5 @@ // concurrent/CompletableExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/CompletableOperations.java b/concurrent/CompletableOperations.java index 745b2bb38..6def117f4 100644 --- a/concurrent/CompletableOperations.java +++ b/concurrent/CompletableOperations.java @@ -1,5 +1,5 @@ // concurrent/CompletableOperations.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -66,8 +66,8 @@ public static void main(String[] args) { cancelled: true completed exceptionally: true done: true -java.util.concurrent.CompletableFuture@6d311334[Complet -ed exceptionally] +java.util.concurrent.CompletableFuture@1629346[Complete +d exceptionally] 777 dependents: 1 dependents: 2 diff --git a/concurrent/CompletablePizza.java b/concurrent/CompletablePizza.java index f81391d2b..7003f7d29 100644 --- a/concurrent/CompletablePizza.java +++ b/concurrent/CompletablePizza.java @@ -1,5 +1,5 @@ // concurrent/CompletablePizza.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -42,46 +42,46 @@ public static void main(String[] args) { } } /* Output: -169 -Pizza 0: ROLLED +98 Pizza 1: ROLLED -Pizza 2: ROLLED -Pizza 4: ROLLED Pizza 3: ROLLED +Pizza 4: ROLLED +Pizza 2: ROLLED +Pizza 0: ROLLED Pizza 1: SAUCED -Pizza 0: SAUCED Pizza 2: SAUCED -Pizza 4: SAUCED Pizza 3: SAUCED -Pizza 0: CHEESED -Pizza 4: CHEESED -Pizza 1: CHEESED +Pizza 0: SAUCED +Pizza 4: SAUCED Pizza 2: CHEESED +Pizza 0: CHEESED Pizza 3: CHEESED -Pizza 0: TOPPED +Pizza 1: CHEESED +Pizza 4: CHEESED +Pizza 2: TOPPED Pizza 4: TOPPED Pizza 1: TOPPED -Pizza 2: TOPPED Pizza 3: TOPPED +Pizza 0: TOPPED Pizza 0: BAKED Pizza 4: BAKED Pizza 1: BAKED Pizza 3: BAKED Pizza 2: BAKED -Pizza 0: SLICED -Pizza 4: SLICED -Pizza 1: SLICED Pizza 3: SLICED +Pizza 1: SLICED Pizza 2: SLICED -Pizza 4: BOXED +Pizza 4: SLICED +Pizza 0: SLICED Pizza 0: BOXED -Pizza0: complete +Pizza 2: BOXED +Pizza 4: BOXED Pizza 1: BOXED +Pizza0: complete Pizza1: complete -Pizza 3: BOXED -Pizza 2: BOXED Pizza2: complete +Pizza 3: BOXED Pizza3: complete Pizza4: complete -1797 +1762 */ diff --git a/concurrent/CompletableUtilities.java b/concurrent/CompletableUtilities.java index 3ee2ab6dc..e1099d6b8 100644 --- a/concurrent/CompletableUtilities.java +++ b/concurrent/CompletableUtilities.java @@ -1,5 +1,5 @@ // concurrent/CompletableUtilities.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/concurrent/CompletedMachina.java b/concurrent/CompletedMachina.java index efba32c4e..d6684e962 100644 --- a/concurrent/CompletedMachina.java +++ b/concurrent/CompletedMachina.java @@ -1,5 +1,5 @@ // concurrent/CompletedMachina.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/CountingStream.java b/concurrent/CountingStream.java index 1d0adc665..47a1a77fb 100644 --- a/concurrent/CountingStream.java +++ b/concurrent/CountingStream.java @@ -1,5 +1,5 @@ // concurrent/CountingStream.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/concurrent/CountingTask.java b/concurrent/CountingTask.java index 1f3bbc2f1..140adfed9 100644 --- a/concurrent/CountingTask.java +++ b/concurrent/CountingTask.java @@ -1,5 +1,5 @@ // concurrent/CountingTask.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -7,8 +7,7 @@ public class CountingTask implements Callable { final int id; public CountingTask(int id) { this.id = id; } - @Override - public Integer call() { + @Override public Integer call() { Integer val = 0; for(int i = 0; i < 100; i++) val++; diff --git a/concurrent/DiningPhilosophers.java b/concurrent/DiningPhilosophers.java index 45801d831..8b54820a1 100644 --- a/concurrent/DiningPhilosophers.java +++ b/concurrent/DiningPhilosophers.java @@ -1,5 +1,5 @@ // concurrent/DiningPhilosophers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Hidden deadlock diff --git a/concurrent/DualCompletableOperations.java b/concurrent/DualCompletableOperations.java index 71eb4dab2..dd7048d91 100644 --- a/concurrent/DualCompletableOperations.java +++ b/concurrent/DualCompletableOperations.java @@ -1,5 +1,5 @@ // concurrent/DualCompletableOperations.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/FrostedCake.java b/concurrent/FrostedCake.java index 0d5a84b4d..77a15fcfe 100644 --- a/concurrent/FrostedCake.java +++ b/concurrent/FrostedCake.java @@ -1,5 +1,5 @@ // concurrent/FrostedCake.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -19,8 +19,9 @@ public class FrostedCake { public FrostedCake(Baked baked, Frosting frosting) { new Nap(0.1); } - @Override - public String toString() { return "FrostedCake"; } + @Override public String toString() { + return "FrostedCake"; + } public static void main(String[] args) { Baked.batch().forEach(baked -> baked .thenCombineAsync(Frosting.make(), diff --git a/concurrent/Futures.java b/concurrent/Futures.java index 138614a33..55bb483cb 100644 --- a/concurrent/Futures.java +++ b/concurrent/Futures.java @@ -1,5 +1,5 @@ // concurrent/Futures.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -13,7 +13,7 @@ public static void main(String[] args) Executors.newSingleThreadExecutor(); Future f = exec.submit(new CountingTask(99)); - System.out.println(f.get()); // [1] + System.out.println(f.get()); // [1] exec.shutdown(); } } diff --git a/concurrent/GuardedIDField.java b/concurrent/GuardedIDField.java index 88e5ad940..8dd2ddd29 100644 --- a/concurrent/GuardedIDField.java +++ b/concurrent/GuardedIDField.java @@ -1,5 +1,5 @@ // concurrent/GuardedIDField.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.*; @@ -8,7 +8,7 @@ public class GuardedIDField implements HasID { private static AtomicInteger counter = new AtomicInteger(); private int id = counter.getAndIncrement(); - public int getID() { return id; } + @Override public int getID() { return id; } public static void main(String[] args) { IDChecker.test(GuardedIDField::new); } diff --git a/concurrent/HasID.java b/concurrent/HasID.java index 4e679a59f..a9734e39f 100644 --- a/concurrent/HasID.java +++ b/concurrent/HasID.java @@ -1,5 +1,5 @@ // concurrent/HasID.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/concurrent/IDChecker.java b/concurrent/IDChecker.java index f21a63d3c..31c45ef66 100644 --- a/concurrent/IDChecker.java +++ b/concurrent/IDChecker.java @@ -1,5 +1,5 @@ // concurrent/IDChecker.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -16,8 +16,7 @@ static class MakeObjects MakeObjects(Supplier gen) { this.gen = gen; } - @Override - public List get() { + @Override public List get() { return Stream.generate(gen) .limit(SIZE) diff --git a/concurrent/InterferingTask.java b/concurrent/InterferingTask.java index 4c564acc7..8715741b8 100644 --- a/concurrent/InterferingTask.java +++ b/concurrent/InterferingTask.java @@ -1,5 +1,5 @@ // concurrent/InterferingTask.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -7,8 +7,7 @@ public class InterferingTask implements Runnable { final int id; private static Integer val = 0; public InterferingTask(int id) { this.id = id; } - @Override - public void run() { + @Override public void run() { for(int i = 0; i < 100; i++) val++; System.out.println(id + " " + diff --git a/concurrent/LambdasAndMethodReferences.java b/concurrent/LambdasAndMethodReferences.java index 08316a986..cb124b6b7 100644 --- a/concurrent/LambdasAndMethodReferences.java +++ b/concurrent/LambdasAndMethodReferences.java @@ -1,5 +1,5 @@ // concurrent/LambdasAndMethodReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -34,7 +34,7 @@ public static void main(String[] args) } /* Output: Lambda1 -NotCallable NotRunnable Lambda2 +NotCallable */ diff --git a/concurrent/Machina.java b/concurrent/Machina.java index 1275391fc..57175c267 100644 --- a/concurrent/Machina.java +++ b/concurrent/Machina.java @@ -1,5 +1,5 @@ // concurrent/Machina.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.Nap; @@ -23,8 +23,7 @@ public static Machina work(Machina m) { System.out.println(m); return m; } - @Override - public String toString() { + @Override public String toString() { return "Machina" + id + ": " + (state.equals(State.END)? "complete" : state); } diff --git a/concurrent/MoreTasksAfterShutdown.java b/concurrent/MoreTasksAfterShutdown.java index 56b925ea6..31a142e16 100644 --- a/concurrent/MoreTasksAfterShutdown.java +++ b/concurrent/MoreTasksAfterShutdown.java @@ -1,5 +1,5 @@ // concurrent/MoreTasksAfterShutdown.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -20,8 +20,7 @@ public static void main(String[] args) { /* Output: java.util.concurrent.RejectedExecutionException: Task NapTask[99] rejected from java.util.concurrent.ThreadPo -olExecutor@4e25154f[Shutting down, pool size = 1, -active threads = 1, queued tasks = 0, completed tasks = -0] +olExecutor@106d69c[Shutting down, pool size = 1, active +threads = 1, queued tasks = 0, completed tasks = 0] NapTask[1] pool-1-thread-1 */ diff --git a/concurrent/NapTask.java b/concurrent/NapTask.java index 26e17bf7a..9206eb4e8 100644 --- a/concurrent/NapTask.java +++ b/concurrent/NapTask.java @@ -1,5 +1,5 @@ // concurrent/NapTask.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.Nap; @@ -7,14 +7,12 @@ public class NapTask implements Runnable { final int id; public NapTask(int id) { this.id = id; } - @Override - public void run() { + @Override public void run() { new Nap(0.1); // Seconds System.out.println(this + " " + Thread.currentThread().getName()); } - @Override - public String toString() { + @Override public String toString() { return "NapTask[" + id + "]"; } } diff --git a/concurrent/OnePizza.java b/concurrent/OnePizza.java index 265b2b419..b8298ebbc 100644 --- a/concurrent/OnePizza.java +++ b/concurrent/OnePizza.java @@ -1,5 +1,5 @@ // concurrent/OnePizza.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.Timer; @@ -22,5 +22,5 @@ public static void main(String[] args) { Pizza 0: BAKED Pizza 0: SLICED Pizza 0: BOXED -1622 +1665 */ diff --git a/concurrent/ParallelPrime.java b/concurrent/ParallelPrime.java index 1359ebf58..84ed969db 100644 --- a/concurrent/ParallelPrime.java +++ b/concurrent/ParallelPrime.java @@ -1,5 +1,5 @@ // concurrent/ParallelPrime.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -20,7 +20,7 @@ public static void main(String[] args) Timer timer = new Timer(); List primes = iterate(2, i -> i + 1) - .parallel() // [1] + .parallel() // [1] .filter(ParallelPrime::isPrime) .limit(COUNT) .mapToObj(Long::toString) @@ -31,5 +31,5 @@ public static void main(String[] args) } } /* Output: -1224 +1635 */ diff --git a/concurrent/ParallelStreamPuzzle.java b/concurrent/ParallelStreamPuzzle.java index bf3a9dfa3..0993d7b91 100644 --- a/concurrent/ParallelStreamPuzzle.java +++ b/concurrent/ParallelStreamPuzzle.java @@ -1,5 +1,5 @@ // concurrent/ParallelStreamPuzzle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -10,7 +10,7 @@ public class ParallelStreamPuzzle { static class IntGenerator implements Supplier { private int current = 0; - public Integer get() { + @Override public Integer get() { return current++; } } @@ -18,7 +18,7 @@ public static void main(String[] args) { List x = Stream.generate(new IntGenerator()) .limit(10) - .parallel() // [1] + .parallel() // [1] .collect(Collectors.toList()); System.out.println(x); } diff --git a/concurrent/ParallelStreamPuzzle2.java b/concurrent/ParallelStreamPuzzle2.java index b02baafaf..ff8b5ed15 100644 --- a/concurrent/ParallelStreamPuzzle2.java +++ b/concurrent/ParallelStreamPuzzle2.java @@ -1,5 +1,5 @@ // concurrent/ParallelStreamPuzzle2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -16,7 +16,7 @@ public class ParallelStreamPuzzle2 { IntGenerator implements Supplier { private AtomicInteger current = new AtomicInteger(); - public Integer get() { + @Override public Integer get() { trace.add(current.get() + ": " + Thread.currentThread().getName()); return current.getAndIncrement(); @@ -34,5 +34,5 @@ public Integer get() { } } /* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +[1, 5, 7, 8, 9, 11, 13, 15, 18, 21] */ diff --git a/concurrent/ParallelStreamPuzzle3.java b/concurrent/ParallelStreamPuzzle3.java index 92d2c851d..69a35618f 100644 --- a/concurrent/ParallelStreamPuzzle3.java +++ b/concurrent/ParallelStreamPuzzle3.java @@ -1,5 +1,5 @@ // concurrent/ParallelStreamPuzzle3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/concurrent/Philosopher.java b/concurrent/Philosopher.java index 29552954b..7fa356846 100644 --- a/concurrent/Philosopher.java +++ b/concurrent/Philosopher.java @@ -1,5 +1,5 @@ // concurrent/Philosopher.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -12,12 +12,10 @@ public Philosopher(int seat, this.left = left; this.right = right; } - @Override - public String toString() { + @Override public String toString() { return "P" + seat; } - @Override - public void run() { + @Override public void run() { while(true) { // System.out.println("Thinking"); // [1] right.pickUp(); diff --git a/concurrent/Pizza.java b/concurrent/Pizza.java index a2dfad92e..6325b930f 100644 --- a/concurrent/Pizza.java +++ b/concurrent/Pizza.java @@ -1,5 +1,5 @@ // concurrent/Pizza.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; @@ -41,8 +41,7 @@ public Pizza next(Step previousStep) { public boolean complete() { return step.equals(Step.BOXED); } - @Override - public String toString() { + @Override public String toString() { return "Pizza" + id + ": " + (step.equals(Step.BOXED)? "complete" : step); } diff --git a/concurrent/PizzaParallelSteps.java b/concurrent/PizzaParallelSteps.java index a289da367..a6ccb3e23 100644 --- a/concurrent/PizzaParallelSteps.java +++ b/concurrent/PizzaParallelSteps.java @@ -1,5 +1,5 @@ // concurrent/PizzaParallelSteps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -25,45 +25,45 @@ public static void main(String[] args) { } } /* Output: +Pizza 1: ROLLED Pizza 2: ROLLED Pizza 0: ROLLED -Pizza 1: ROLLED -Pizza 4: ROLLED Pizza 3: ROLLED -Pizza 1: SAUCED -Pizza 0: SAUCED +Pizza 4: ROLLED +Pizza 4: SAUCED Pizza 2: SAUCED +Pizza 0: SAUCED +Pizza 1: SAUCED Pizza 3: SAUCED -Pizza 4: SAUCED Pizza 1: CHEESED -Pizza 0: CHEESED -Pizza 2: CHEESED Pizza 3: CHEESED Pizza 4: CHEESED +Pizza 2: CHEESED +Pizza 0: CHEESED +Pizza 3: TOPPED +Pizza 1: TOPPED Pizza 0: TOPPED Pizza 2: TOPPED -Pizza 1: TOPPED -Pizza 3: TOPPED Pizza 4: TOPPED -Pizza 1: BAKED Pizza 2: BAKED +Pizza 3: BAKED +Pizza 1: BAKED Pizza 0: BAKED Pizza 4: BAKED -Pizza 3: BAKED -Pizza 0: SLICED -Pizza 2: SLICED -Pizza 1: SLICED Pizza 3: SLICED +Pizza 1: SLICED +Pizza 2: SLICED +Pizza 0: SLICED Pizza 4: SLICED +Pizza 3: BOXED +Pizza3: complete Pizza 1: BOXED Pizza1: complete Pizza 2: BOXED Pizza 0: BOXED -Pizza2: complete Pizza0: complete -Pizza 3: BOXED +Pizza2: complete Pizza 4: BOXED Pizza4: complete -Pizza3: complete -1738 +1766 */ diff --git a/concurrent/PizzaStreams.java b/concurrent/PizzaStreams.java index 6d3e5f29e..8ec339bee 100644 --- a/concurrent/PizzaStreams.java +++ b/concurrent/PizzaStreams.java @@ -1,5 +1,5 @@ // concurrent/PizzaStreams.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -12,7 +12,7 @@ public static void main(String[] args) { Timer timer = new Timer(); IntStream.range(0, QUANTITY) .mapToObj(Pizza::new) - .parallel() // [1] + .parallel() // [1] .forEach(za -> { while(!za.complete()) za.next(); @@ -21,40 +21,40 @@ public static void main(String[] args) { } } /* Output: -Pizza 2: ROLLED Pizza 0: ROLLED Pizza 1: ROLLED -Pizza 4: ROLLED +Pizza 2: ROLLED Pizza 3: ROLLED -Pizza 2: SAUCED +Pizza 4: ROLLED Pizza 1: SAUCED Pizza 0: SAUCED Pizza 4: SAUCED +Pizza 2: SAUCED Pizza 3: SAUCED +Pizza 3: CHEESED Pizza 2: CHEESED -Pizza 1: CHEESED -Pizza 0: CHEESED Pizza 4: CHEESED -Pizza 3: CHEESED +Pizza 0: CHEESED +Pizza 1: CHEESED +Pizza 3: TOPPED Pizza 2: TOPPED +Pizza 4: TOPPED Pizza 1: TOPPED Pizza 0: TOPPED -Pizza 4: TOPPED -Pizza 3: TOPPED -Pizza 2: BAKED -Pizza 1: BAKED -Pizza 0: BAKED Pizza 4: BAKED +Pizza 2: BAKED Pizza 3: BAKED -Pizza 2: SLICED -Pizza 1: SLICED -Pizza 0: SLICED +Pizza 0: BAKED +Pizza 1: BAKED Pizza 4: SLICED Pizza 3: SLICED +Pizza 2: SLICED +Pizza 0: SLICED +Pizza 1: SLICED Pizza 2: BOXED -Pizza 1: BOXED -Pizza 0: BOXED Pizza 4: BOXED Pizza 3: BOXED -1739 +Pizza 1: BOXED +Pizza 0: BOXED +1797 */ diff --git a/concurrent/QuittableTask.java b/concurrent/QuittableTask.java index 2e473f4ea..e2a1bab23 100644 --- a/concurrent/QuittableTask.java +++ b/concurrent/QuittableTask.java @@ -1,5 +1,5 @@ // concurrent/QuittableTask.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.AtomicBoolean; @@ -11,10 +11,9 @@ public class QuittableTask implements Runnable { private AtomicBoolean running = new AtomicBoolean(true); public void quit() { running.set(false); } - @Override - public void run() { - while(running.get()) // [1] + @Override public void run() { + while(running.get()) // [1] new Nap(0.1); - System.out.print(id + " "); // [2] + System.out.print(id + " "); // [2] } } diff --git a/concurrent/QuittingCompletable.java b/concurrent/QuittingCompletable.java index e57ec0f31..7fb9c0fca 100644 --- a/concurrent/QuittingCompletable.java +++ b/concurrent/QuittingCompletable.java @@ -1,5 +1,5 @@ // concurrent/QuittingCompletable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -23,13 +23,13 @@ public static void main(String[] args) { } } /* Output: -7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 -26 27 28 29 30 31 32 33 34 6 35 4 38 39 40 41 42 43 44 -45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 -63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 -81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 -99 100 101 102 103 104 105 106 107 108 109 110 111 112 -1 113 114 116 117 118 119 120 121 122 123 124 125 126 -127 128 129 130 131 132 133 134 135 136 137 138 139 140 -141 142 143 144 145 146 147 148 149 5 115 37 36 2 3 +6 7 5 9 11 12 13 14 15 16 17 18 19 20 21 22 23 10 24 26 +27 28 29 30 31 32 25 33 8 36 37 38 39 40 41 42 43 44 45 +46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 +64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 +82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 +100 101 102 103 104 105 106 107 108 34 110 111 112 113 +114 115 116 117 118 119 120 121 109 123 124 125 126 127 +128 129 130 131 35 132 122 134 133 136 135 138 140 141 +142 143 144 145 146 147 148 149 137 139 3 1 2 4 */ diff --git a/concurrent/QuittingTasks.java b/concurrent/QuittingTasks.java index dc863f426..58618e531 100644 --- a/concurrent/QuittingTasks.java +++ b/concurrent/QuittingTasks.java @@ -1,5 +1,5 @@ // concurrent/QuittingTasks.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -23,13 +23,13 @@ public static void main(String[] args) { } } /* Output: -24 27 31 8 11 7 19 12 16 4 23 3 28 32 15 20 63 60 68 67 -64 39 47 52 51 55 40 43 48 59 44 56 36 35 71 72 83 103 -96 92 88 99 100 87 91 79 75 84 76 115 108 112 104 107 -111 95 80 147 120 127 119 123 144 143 116 132 124 128 -136 131 135 139 148 140 2 126 6 5 1 18 129 17 14 13 21 -22 9 10 30 33 58 37 125 26 34 133 145 78 137 141 138 62 -74 142 86 65 73 146 70 42 149 121 110 134 105 82 117 -106 113 122 45 114 118 38 50 29 90 101 89 57 53 94 41 -61 66 130 69 77 81 85 93 25 102 54 109 98 49 46 97 +11 23 20 12 24 16 19 15 35 147 32 27 7 4 28 31 8 83 3 1 +13 9 5 2 6 18 14 17 21 25 22 26 29 30 33 34 37 41 38 46 +45 49 50 53 57 58 54 69 104 112 40 73 74 115 116 70 119 +77 81 56 85 78 82 111 86 90 48 89 36 108 107 44 55 52 +43 60 63 59 64 71 68 67 75 76 72 79 80 84 87 88 66 91 +10 95 65 96 94 92 62 100 61 93 47 39 51 99 103 128 123 +127 124 140 120 139 136 135 143 148 144 105 102 131 101 +132 98 97 149 137 134 42 106 110 109 114 133 113 117 +118 130 129 126 121 125 122 138 141 145 142 146 */ diff --git a/concurrent/SharedConstructorArgument.java b/concurrent/SharedConstructorArgument.java index df8ec4574..9746ff761 100644 --- a/concurrent/SharedConstructorArgument.java +++ b/concurrent/SharedConstructorArgument.java @@ -1,5 +1,5 @@ // concurrent/SharedConstructorArgument.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.*; @@ -10,13 +10,13 @@ interface SharedArg { class Unsafe implements SharedArg { private int i = 0; - public int get() { return i++; } + @Override public int get() { return i++; } } class Safe implements SharedArg { private static AtomicInteger counter = new AtomicInteger(); - public int get() { + @Override public int get() { return counter.getAndIncrement(); } } @@ -26,8 +26,7 @@ class SharedUser implements HasID { SharedUser(SharedArg sa) { id = sa.get(); } - @Override - public int getID() { return id; } + @Override public int getID() { return id; } } public class SharedConstructorArgument { @@ -39,6 +38,6 @@ public static void main(String[] args) { } } /* Output: -24838 +16537 0 */ diff --git a/concurrent/SingleThreadExecutor.java b/concurrent/SingleThreadExecutor.java index 58047d26a..12629d433 100644 --- a/concurrent/SingleThreadExecutor.java +++ b/concurrent/SingleThreadExecutor.java @@ -1,5 +1,5 @@ // concurrent/SingleThreadExecutor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -30,17 +30,17 @@ public static void main(String[] args) { NapTask[0] pool-1-thread-1 main awaiting termination NapTask[1] pool-1-thread-1 -main awaiting termination NapTask[2] pool-1-thread-1 main awaiting termination NapTask[3] pool-1-thread-1 main awaiting termination -NapTask[4] pool-1-thread-1 main awaiting termination +NapTask[4] pool-1-thread-1 NapTask[5] pool-1-thread-1 main awaiting termination NapTask[6] pool-1-thread-1 main awaiting termination +main awaiting termination NapTask[7] pool-1-thread-1 main awaiting termination NapTask[8] pool-1-thread-1 diff --git a/concurrent/SingleThreadExecutor2.java b/concurrent/SingleThreadExecutor2.java index 113fb6393..81657338f 100644 --- a/concurrent/SingleThreadExecutor2.java +++ b/concurrent/SingleThreadExecutor2.java @@ -1,5 +1,5 @@ // concurrent/SingleThreadExecutor2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/SingleThreadExecutor3.java b/concurrent/SingleThreadExecutor3.java index 46e384280..d32c667f1 100644 --- a/concurrent/SingleThreadExecutor3.java +++ b/concurrent/SingleThreadExecutor3.java @@ -1,5 +1,5 @@ // concurrent/SingleThreadExecutor3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/StaticIDField.java b/concurrent/StaticIDField.java index 9e563dfdb..deefbb62e 100644 --- a/concurrent/StaticIDField.java +++ b/concurrent/StaticIDField.java @@ -1,10 +1,10 @@ // concurrent/StaticIDField.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class StaticIDField implements HasID { private static int counter = 0; private int id = counter++; - public int getID() { return id; } + @Override public int getID() { return id; } } diff --git a/concurrent/StickHolder.java b/concurrent/StickHolder.java index 413e69dc8..f4f9279ca 100644 --- a/concurrent/StickHolder.java +++ b/concurrent/StickHolder.java @@ -1,5 +1,5 @@ // concurrent/StickHolder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/StreamExceptions.java b/concurrent/StreamExceptions.java index facae761e..e02b42743 100644 --- a/concurrent/StreamExceptions.java +++ b/concurrent/StreamExceptions.java @@ -1,5 +1,5 @@ // concurrent/StreamExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/concurrent/Summing.java b/concurrent/Summing.java index 8f44563e1..ae97efca2 100644 --- a/concurrent/Summing.java +++ b/concurrent/Summing.java @@ -1,5 +1,5 @@ // concurrent/Summing.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; @@ -41,7 +41,7 @@ public static void main(String[] args) { } /* Output: 5000000050000000 -Sum Stream: 167ms -Sum Stream Parallel: 46ms -Sum Iterated: 284ms +Sum Stream: 841ms +Sum Stream Parallel: 179ms +Sum Iterated: 4051ms */ diff --git a/concurrent/Summing2.java b/concurrent/Summing2.java index f5d75be97..257a53138 100644 --- a/concurrent/Summing2.java +++ b/concurrent/Summing2.java @@ -1,5 +1,5 @@ // concurrent/Summing2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromTravisCI} @@ -37,8 +37,8 @@ public static void main(String[] args) { } /* Output: 200000010000000 -Array Stream Sum: 104ms -Parallel: 81ms -Basic Sum: 106ms -parallelPrefix: 265ms +Array Stream Sum: 166ms +Parallel: 30ms +Basic Sum: 45ms +parallelPrefix: 53ms */ diff --git a/concurrent/Summing3.java b/concurrent/Summing3.java index 5477dc617..3af34db21 100644 --- a/concurrent/Summing3.java +++ b/concurrent/Summing3.java @@ -1,5 +1,5 @@ // concurrent/Summing3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromTravisCI} @@ -36,7 +36,7 @@ public static void main(String[] args) { } /* Output: 50000005000000 -Long Array Stream Reduce: 1038ms -Long Basic Sum: 21ms -Long parallelPrefix: 3616ms +Long Array Stream Reduce: 1510ms +Long Basic Sum: 35ms +Long parallelPrefix: 4306ms */ diff --git a/concurrent/Summing4.java b/concurrent/Summing4.java index 4df903234..03dc04ba0 100644 --- a/concurrent/Summing4.java +++ b/concurrent/Summing4.java @@ -1,5 +1,5 @@ // concurrent/Summing4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromTravisCI} @@ -19,5 +19,5 @@ public static void main(String[] args) { } /* Output: 50000005000000 -Long Parallel: 1014ms +Long Parallel: 1147ms */ diff --git a/concurrent/SynchronizedConstructor.java b/concurrent/SynchronizedConstructor.java index 520829ee3..092c9733b 100644 --- a/concurrent/SynchronizedConstructor.java +++ b/concurrent/SynchronizedConstructor.java @@ -1,5 +1,5 @@ // concurrent/SynchronizedConstructor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.*; @@ -13,8 +13,7 @@ class SyncConstructor implements HasID { id = sa.get(); } } - @Override - public int getID() { return id; } + @Override public int getID() { return id; } } public class SynchronizedConstructor { diff --git a/concurrent/SynchronizedFactory.java b/concurrent/SynchronizedFactory.java index 4f682082b..11e5f184b 100644 --- a/concurrent/SynchronizedFactory.java +++ b/concurrent/SynchronizedFactory.java @@ -1,5 +1,5 @@ // concurrent/SynchronizedFactory.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.*; @@ -9,8 +9,7 @@ final class SyncFactory implements HasID { private SyncFactory(SharedArg sa) { id = sa.get(); } - @Override - public int getID() { return id; } + @Override public int getID() { return id; } public static synchronized SyncFactory factory(SharedArg sa) { return new SyncFactory(sa); diff --git a/concurrent/TestStaticIDField.java b/concurrent/TestStaticIDField.java index 772958aad..6f10da7cf 100644 --- a/concurrent/TestStaticIDField.java +++ b/concurrent/TestStaticIDField.java @@ -1,5 +1,5 @@ // concurrent/TestStaticIDField.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,5 +9,5 @@ public static void main(String[] args) { } } /* Output: -13287 +21397 */ diff --git a/concurrent/ThrowsChecked.java b/concurrent/ThrowsChecked.java index bbebadd18..f198cc6c0 100644 --- a/concurrent/ThrowsChecked.java +++ b/concurrent/ThrowsChecked.java @@ -1,5 +1,5 @@ // concurrent/ThrowsChecked.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; @@ -17,7 +17,7 @@ static ThrowsChecked nochecked(ThrowsChecked tc) { static void testStream() { Stream.of(new ThrowsChecked()) .map(ThrowsChecked::nochecked) - // .map(ThrowsChecked::withchecked); // [1] + // .map(ThrowsChecked::withchecked); // [1] .map(tc -> { try { return withchecked(tc); @@ -30,7 +30,7 @@ static void testCompletableFuture() { CompletableFuture .completedFuture(new ThrowsChecked()) .thenApply(ThrowsChecked::nochecked) - // .thenApply(ThrowsChecked::withchecked); // [2] + // .thenApply(ThrowsChecked::withchecked); // [2] .thenApply(tc -> { try { return withchecked(tc); diff --git a/concurrent/Workable.java b/concurrent/Workable.java index a04bc113c..ada83c2f6 100644 --- a/concurrent/Workable.java +++ b/concurrent/Workable.java @@ -1,5 +1,5 @@ // concurrent/Workable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -12,8 +12,7 @@ public Workable(String id, double duration) { this.id = id; this.duration = duration; } - @Override - public String toString() { + @Override public String toString() { return "Workable[" + id + "]"; } public static Workable work(Workable tt) { diff --git a/control/BreakAndContinue.java b/control/BreakAndContinue.java index 83ad25e06..d6c39738c 100644 --- a/control/BreakAndContinue.java +++ b/control/BreakAndContinue.java @@ -1,5 +1,5 @@ // control/BreakAndContinue.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Break and continue keywords @@ -7,14 +7,14 @@ public class BreakAndContinue { public static void main(String[] args) { - for(int i = 0; i < 100; i++) { // [1] + for(int i = 0; i < 100; i++) { // [1] if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration System.out.print(i + " "); } System.out.println(); // Using for-in: - for(int i : range(100)) { // [2] + for(int i : range(100)) { // [2] if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration System.out.print(i + " "); @@ -22,7 +22,7 @@ public static void main(String[] args) { System.out.println(); int i = 0; // An "infinite loop": - while(true) { // [3] + while(true) { // [3] i++; int j = i * 27; if(j == 1269) break; // Out of loop diff --git a/control/CommaOperator.java b/control/CommaOperator.java index d4337c036..995765188 100644 --- a/control/CommaOperator.java +++ b/control/CommaOperator.java @@ -1,5 +1,5 @@ // control/CommaOperator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/control/ForInFloat.java b/control/ForInFloat.java index 4027b2f79..c36236ef1 100644 --- a/control/ForInFloat.java +++ b/control/ForInFloat.java @@ -1,5 +1,5 @@ // control/ForInFloat.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/control/ForInInt.java b/control/ForInInt.java index 0abc762f6..7adf5550d 100644 --- a/control/ForInInt.java +++ b/control/ForInInt.java @@ -1,5 +1,5 @@ // control/ForInInt.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import static onjava.Range.*; diff --git a/control/ForInString.java b/control/ForInString.java index 320f17004..8b5ba601e 100644 --- a/control/ForInString.java +++ b/control/ForInString.java @@ -1,5 +1,5 @@ // control/ForInString.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/control/IfElse.java b/control/IfElse.java index 1347bcd1d..b2fd79de9 100644 --- a/control/IfElse.java +++ b/control/IfElse.java @@ -1,5 +1,5 @@ // control/IfElse.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -8,7 +8,7 @@ public class IfElse { static void test(int testval, int target) { if(testval > target) result = +1; - else if(testval < target) // [1] + else if(testval < target) // [1] result = -1; else result = 0; // Match diff --git a/control/LabeledFor.java b/control/LabeledFor.java index 7535b2163..0cfe7bd95 100644 --- a/control/LabeledFor.java +++ b/control/LabeledFor.java @@ -1,5 +1,5 @@ // control/LabeledFor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // For loops with "labeled break"/"labeled continue." diff --git a/control/LabeledWhile.java b/control/LabeledWhile.java index 8fded1940..6c884cb80 100644 --- a/control/LabeledWhile.java +++ b/control/LabeledWhile.java @@ -1,5 +1,5 @@ // control/LabeledWhile.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // "While" with "labeled break" and "labeled continue." diff --git a/control/ListCharacters.java b/control/ListCharacters.java index c846270d6..dc4b7d2ca 100644 --- a/control/ListCharacters.java +++ b/control/ListCharacters.java @@ -1,5 +1,5 @@ // control/ListCharacters.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // List all the lowercase ASCII letters diff --git a/control/RandomBounds.java b/control/RandomBounds.java index 81a0dc13b..e0903f372 100644 --- a/control/RandomBounds.java +++ b/control/RandomBounds.java @@ -1,5 +1,5 @@ // control/RandomBounds.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Does Math.random() produce 0.0 and 1.0? diff --git a/control/StringSwitch.java b/control/StringSwitch.java index 3ad7236d7..ac4694cf3 100644 --- a/control/StringSwitch.java +++ b/control/StringSwitch.java @@ -1,5 +1,5 @@ // control/StringSwitch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/control/TestWithReturn.java b/control/TestWithReturn.java index 6df7a5df1..9b32ee845 100644 --- a/control/TestWithReturn.java +++ b/control/TestWithReturn.java @@ -1,5 +1,5 @@ // control/TestWithReturn.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/control/TrueFalse.java b/control/TrueFalse.java index b4d25db06..ad2da1a79 100644 --- a/control/TrueFalse.java +++ b/control/TrueFalse.java @@ -1,5 +1,5 @@ // control/TrueFalse.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/control/VowelsAndConsonants.java b/control/VowelsAndConsonants.java index 79ea2bfc5..2b8b3e959 100644 --- a/control/VowelsAndConsonants.java +++ b/control/VowelsAndConsonants.java @@ -1,5 +1,5 @@ // control/VowelsAndConsonants.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates the switch statement diff --git a/control/WhileTest.java b/control/WhileTest.java index becb35682..a047c166c 100644 --- a/control/WhileTest.java +++ b/control/WhileTest.java @@ -1,5 +1,5 @@ // control/WhileTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates the while loop diff --git a/enumerations/ArrowInSwitch.java b/enumerations/ArrowInSwitch.java new file mode 100644 index 000000000..f583d7ee2 --- /dev/null +++ b/enumerations/ArrowInSwitch.java @@ -0,0 +1,42 @@ +// enumerations/ArrowInSwitch.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 14 +import static java.util.stream.IntStream.range; + +public class ArrowInSwitch { + static void colons(int i) { + switch(i) { + case 1: System.out.println("one"); + break; + case 2: System.out.println("two"); + break; + case 3: System.out.println("three"); + break; + default: System.out.println("default"); + } + } + static void arrows(int i) { + switch(i) { + case 1 -> System.out.println("one"); + case 2 -> System.out.println("two"); + case 3 -> System.out.println("three"); + default -> System.out.println("default"); + } + } + public static void main(String[] args) { + range(0, 4).forEach(i -> colons(i)); + range(0, 4).forEach(i -> arrows(i)); + } +} +/* Output: +default +one +two +three +default +one +two +three +*/ diff --git a/enumerations/CaseNull.java b/enumerations/CaseNull.java new file mode 100644 index 000000000..6b5004920 --- /dev/null +++ b/enumerations/CaseNull.java @@ -0,0 +1,92 @@ +// enumerations/CaseNull.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +// Run with java flag: --enable-preview +import java.util.*; +import java.util.function.*; + +public class CaseNull { + static void old(String s) { + if(s == null) { + System.out.println("null"); + return; + } + switch(s) { + case "XX" -> System.out.println("XX"); + default -> System.out.println("default"); + } + } + static void checkNull(String s) { + switch(s) { + case "XX" -> System.out.println("XX"); + case null -> System.out.println("null"); + default -> System.out.println("default"); + } + // Works with colon syntax, too: + switch(s) { + case "XX": System.out.println("XX"); + break; + case null: System.out.println("null"); + break; + default : System.out.println("default"); + } + } + static void defaultOnly(String s) { + switch(s) { + case "XX" -> System.out.println("XX"); + default -> System.out.println("default"); + } + } + static void combineNullAndCase(String s) { + switch(s) { + case "XX", null -> System.out.println("XX|null"); + default -> System.out.println("default"); + } + } + static void combineNullAndDefault(String s) { + switch(s) { + case "XX" -> System.out.println("XX"); + case null, default -> System.out.println("both"); + } + } + static void test(Consumer cs) { + cs.accept("XX"); + cs.accept("YY"); + try { + cs.accept(null); + } catch(NullPointerException e) { + System.out.println(e.getMessage()); + } + } + public static void main(String[] args) { + test(CaseNull::old); + test(CaseNull::checkNull); + test(CaseNull::defaultOnly); + test(CaseNull::combineNullAndCase); + test(CaseNull::combineNullAndDefault); + } +} +/* Output: +XX +default +null +XX +XX +default +default +null +null +XX +default +Cannot invoke "String.hashCode()" because "" is null +XX|null +default +XX|null +XX +both +both +*/ diff --git a/enumerations/Dominance.java b/enumerations/Dominance.java new file mode 100644 index 000000000..893e755e2 --- /dev/null +++ b/enumerations/Dominance.java @@ -0,0 +1,20 @@ +// enumerations/Dominance.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +import java.util.*; + +sealed interface Base {} +record Derived() implements Base {} + +public class Dominance { + static String test(Base base) { + return switch(base) { + case Derived d -> "Derived"; + case Base b -> "B"; // [1] + }; + } +} diff --git a/enumerations/EnumSwitch.java b/enumerations/EnumSwitch.java new file mode 100644 index 000000000..a17546eab --- /dev/null +++ b/enumerations/EnumSwitch.java @@ -0,0 +1,17 @@ +// enumerations/EnumSwitch.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 14 + +public class EnumSwitch { + enum Signal { GREEN, YELLOW, RED, } + Signal color = Signal.RED; + public void change() { + color = switch(color) { + case RED -> Signal.GREEN; + case GREEN -> Signal.YELLOW; + case YELLOW -> Signal.RED; + }; + } +} diff --git a/enumerations/NormalLiskov.java b/enumerations/NormalLiskov.java new file mode 100644 index 000000000..c121700ab --- /dev/null +++ b/enumerations/NormalLiskov.java @@ -0,0 +1,40 @@ +// enumerations/NormalLiskov.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.stream.*; + +interface LifeForm { + String move(); + String react(); +} + +class Worm implements LifeForm { + @Override public String move() { + return "Worm::move()"; + } + @Override public String react() { + return "Worm::react()"; + } +} + +class Giraffe implements LifeForm { + @Override public String move() { + return "Giraffe::move()"; + } + @Override public String react() { + return "Giraffe::react()"; + } +} + +public class NormalLiskov { + public static void main(String[] args) { + Stream.of(new Worm(), new Giraffe()) + .forEach(lf -> System.out.println( + lf.move() + " " + lf.react())); + } +} +/* Output: +Worm::move() Worm::react() +Giraffe::move() Giraffe::react() +*/ diff --git a/enumerations/ObjectMatch.java b/enumerations/ObjectMatch.java new file mode 100644 index 000000000..490b79a0b --- /dev/null +++ b/enumerations/ObjectMatch.java @@ -0,0 +1,46 @@ +// enumerations/ObjectMatch.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +// Run with java flag: --enable-preview +import java.util.*; + +record XX() {} + +public class ObjectMatch { + static String match(Object o) { + return switch(o) { + case Dog d -> "Walk the dog"; + case Fish f -> "Change the fish water"; + case Pet sp -> "Not dog or fish"; + case String s -> "String " + s; + case Integer i -> "Integer " + i; + case String[] sa -> String.join(", ", sa); + case null, XX xx -> "null or XX: " + xx; + default -> "Something else"; + }; + } + public static void main(String[] args) { + List.of(new Dog(), new Fish(), new Pet(), + "Oscar", Integer.valueOf(12), + Double.valueOf("47.74"), + new String[]{ "to", "the", "point" }, + new XX() + ).forEach( + p -> System.out.println(match(p)) + ); + } +} +/* Output: +Walk the dog +Change the fish water +Not dog or fish +String Oscar +Integer 12 +Something else +to, the, point +null or Object: XX[] +*/ diff --git a/enumerations/OddScoping.java b/enumerations/OddScoping.java new file mode 100644 index 000000000..fd938e98a --- /dev/null +++ b/enumerations/OddScoping.java @@ -0,0 +1,27 @@ +// enumerations/OddScoping.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +public class OddScoping { + static void f(Object o) { + if(!(o instanceof String s)) { + System.out.println("Not a String"); + throw new RuntimeException(); + } + // s is in scope here! + System.out.println(s.toUpperCase()); // [1] + } + public static void main(String[] args) { + f("Curiouser and Curiouser"); + f(null); + } +} +/* Output: +CURIOUSER AND CURIOUSER +Not a String +Exception in thread "main" java.lang.RuntimeException + at OddScoping.f(OddScoping.java:8) + at OddScoping.main(OddScoping.java:15) +*/ diff --git a/enumerations/People.java b/enumerations/People.java new file mode 100644 index 000000000..183d34c79 --- /dev/null +++ b/enumerations/People.java @@ -0,0 +1,46 @@ +// enumerations/People.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +// Run with java flag: --enable-preview +import java.util.*; + +record Person(String name, int age) {} + +public class People { + static String categorize(Person person) { + return switch(person) { + case Person p && p.age() > 40 // [1] + -> p + " is middle aged"; + case Person p && + (p.name().contains("D") || p.age() == 14) + -> p + " D or 14"; + case Person p && !(p.age() >= 100) // [2] + -> p + " is not a centenarian"; + case Person p -> p + " Everyone else"; + }; + } + public static void main(String[] args) { + List.of( + new Person("Dorothy", 15), + new Person("John Bigboote", 42), + new Person("Morty", 14), + new Person("Morty Jr.", 1), + new Person("Jose", 39), + new Person("Kane", 118) + ).forEach( + p -> System.out.println(categorize(p)) + ); + } +} +/* Output: +Person[name=Dorothy, age=15] D or 14 +Person[name=John Bigboote, age=42] is middle aged +Person[name=Morty, age=14] D or 14 +Person[name=Morty Jr., age=1] is not a centenarian +Person[name=Jose, age=39] is not a centenarian +Person[name=Kane, age=118] is middle aged +*/ diff --git a/enumerations/Pet.java b/enumerations/Pet.java new file mode 100644 index 000000000..0508905e3 --- /dev/null +++ b/enumerations/Pet.java @@ -0,0 +1,16 @@ +// enumerations/Pet.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class Pet { + void feed() {} +} + +class Dog extends Pet { + void walk() {} +} + +class Fish extends Pet { + void changeWater() {} +} diff --git a/enumerations/PetPatternMatch.java b/enumerations/PetPatternMatch.java new file mode 100644 index 000000000..d538ef2b8 --- /dev/null +++ b/enumerations/PetPatternMatch.java @@ -0,0 +1,22 @@ +// enumerations/PetPatternMatch.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +import java.util.*; + +public class PetPatternMatch { + static void careFor(Pet p) { + switch(p) { + case Dog d -> d.walk(); + case Fish f -> f.changeWater(); + case Pet sp -> sp.feed(); + }; + } + static void petCare() { + List.of(new Dog(), new Fish()) + .forEach(p -> careFor(p)); + } +} diff --git a/enumerations/PetPatternMatch2.java b/enumerations/PetPatternMatch2.java new file mode 100644 index 000000000..76b44f4ee --- /dev/null +++ b/enumerations/PetPatternMatch2.java @@ -0,0 +1,36 @@ +// enumerations/PetPatternMatch2.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +package sealedpet; +import java.util.*; + +sealed interface Pet { + void feed(); +} + +final class Dog implements Pet { + @Override public void feed() {} + void walk() {} +} + +final class Fish implements Pet { + @Override public void feed() {} + void changeWater() {} +} + +public class PetPatternMatch2 { + static void careFor(Pet p) { + switch(p) { + case Dog d -> d.walk(); + case Fish f -> f.changeWater(); + }; + } + static void petCare() { + List.of(new Dog(), new Fish()) + .forEach(p -> careFor(p)); + } +} diff --git a/enumerations/Planets.java b/enumerations/Planets.java new file mode 100644 index 000000000..9554c684f --- /dev/null +++ b/enumerations/Planets.java @@ -0,0 +1,36 @@ +// enumerations/Planets.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 14 + +enum CelestialBody { + MERCURY, VENUS, EARTH, MARS, JUPITER, + SATURN, URANUS, NEPTUNE, PLUTO +} + +public class Planets { + public static String classify(CelestialBody b) { + var result = switch(b) { + case MERCURY, VENUS, EARTH, + MARS, JUPITER, + SATURN, URANUS, NEPTUNE -> { + System.out.print("A planet: "); + yield b.toString(); + } + case PLUTO -> { + System.out.print("Not a planet: "); + yield b.toString(); + } + }; + return result; + } + public static void main(String[] args) { + System.out.println(classify(CelestialBody.MARS)); + System.out.println(classify(CelestialBody.PLUTO)); + } +} +/* Output: +A planet: MARS +Not a planet: PLUTO +*/ diff --git a/enumerations/SealedPatternMatch.java b/enumerations/SealedPatternMatch.java new file mode 100644 index 000000000..b5051303b --- /dev/null +++ b/enumerations/SealedPatternMatch.java @@ -0,0 +1,48 @@ +// enumerations/SealedPatternMatch.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +// Run with java flag: --enable-preview +import java.util.*; + +sealed interface Transport {}; +record Bicycle(String id) implements Transport {}; +record Glider(int size) implements Transport {}; +record Surfboard(double weight) implements Transport {}; +// If you uncomment this: +// record Skis(int length) implements Transport {}; +// You get an error: "the switch expression +// does not cover all possible input values" + +public class SealedPatternMatch { + static String exhaustive(Transport t) { + return switch(t) { + case Bicycle b -> "Bicycle " + b.id(); + case Glider g -> "Glider " + g.size(); + case Surfboard s -> "Surfboard " + s.weight(); + }; + } + public static void main(String[] args) { + List.of( + new Bicycle("Bob"), + new Glider(65), + new Surfboard(6.4) + ).forEach( + t -> System.out.println(exhaustive(t)) + ); + try { + exhaustive(null); // Always possible! // [1] + } catch(NullPointerException e) { + System.out.println("Not exhaustive: " + e); + } + } +} +/* Output: +Bicycle Bob +Glider 65 +Surfboard 6.4 +Not exhaustive: java.lang.NullPointerException +*/ diff --git a/enumerations/Shapes.java b/enumerations/Shapes.java new file mode 100644 index 000000000..031fc4851 --- /dev/null +++ b/enumerations/Shapes.java @@ -0,0 +1,53 @@ +// enumerations/Shapes.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +// Run with java flag: --enable-preview +import java.util.*; + +sealed interface Shape { + double area(); +} + +record Circle(double radius) implements Shape { + @Override public double area() { + return Math.PI * radius * radius; + } +} + +record Rectangle(double side1, double side2) + implements Shape { + @Override public double area() { + return side1 * side2; + } +} + +public class Shapes { + static void classify(Shape s) { + System.out.println(switch(s) { + case Circle c && c.area() < 100.0 + -> "Small Circle: " + c; + case Circle c -> "Large Circle: " + c; + case Rectangle r && r.side1() == r.side2() + -> "Square: " + r; + case Rectangle r -> "Rectangle: " + r; + }); + } + public static void main(String[] args) { + List.of( + new Circle(5.0), + new Circle(25.0), + new Rectangle(12.0, 12.0), + new Rectangle(12.0, 15.0) + ).forEach(t -> classify(t)); + } +} +/* Output: +Small Circle: Circle[radius=5.0] +Large Circle: Circle[radius=25.0] +Square: Rectangle[side1=12.0, side2=12.0] +Rectangle: Rectangle[side1=12.0, side2=15.0] +*/ diff --git a/enumerations/SmartCasting.java b/enumerations/SmartCasting.java new file mode 100644 index 000000000..848c0e9de --- /dev/null +++ b/enumerations/SmartCasting.java @@ -0,0 +1,36 @@ +// enumerations/SmartCasting.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 16 + +public class SmartCasting { + static void dumb(Object x) { + if(x instanceof String) { + String s = (String)x; + if(s.length() > 0) { + System.out.format( + "%d %s%n", s.length(), s.toUpperCase()); + } + } + } + static void smart(Object x) { + if(x instanceof String s && s.length() > 0) { + System.out.format( + "%d %s%n", s.length(), s.toUpperCase()); + } + } + static void wrong(Object x) { + // "Or" never works: + // if(x instanceof String s || s.length() > 0) {} + // error: cannot find symbol ^ + } + public static void main(String[] args) { + dumb("dumb"); + smart("smart"); + } +} +/* Output: +4 DUMB +5 SMART +*/ diff --git a/enumerations/SwitchExpression.java b/enumerations/SwitchExpression.java new file mode 100644 index 000000000..06a0fe49b --- /dev/null +++ b/enumerations/SwitchExpression.java @@ -0,0 +1,38 @@ +// enumerations/SwitchExpression.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 14 +import java.util.*; + +public class SwitchExpression { + static int colon(String s) { + var result = switch(s) { + case "i": yield 1; + case "j": yield 2; + case "k": yield 3; + default: yield 0; + }; + return result; + } + static int arrow(String s) { + var result = switch(s) { + case "i" -> 1; + case "j" -> 2; + case "k" -> 3; + default -> 0; + }; + return result; + } + public static void main(String[] args) { + for(var s: new String[]{"i", "j", "k", "z"}) + System.out.format( + "%s %d %d%n", s, colon(s), arrow(s)); + } +} +/* Output: +i 1 1 +j 2 2 +k 3 3 +z 0 0 +*/ diff --git a/enumerations/Tanks.java b/enumerations/Tanks.java new file mode 100644 index 000000000..0604693f5 --- /dev/null +++ b/enumerations/Tanks.java @@ -0,0 +1,47 @@ +// enumerations/Tanks.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Preview in JDK 17 +// Compile with javac flags: +// --enable-preview --source 17 +// Run with java flag: --enable-preview +import java.util.*; + +enum Type { TOXIC, FLAMMABLE, NEUTRAL } + +record Level(int percent) { + Level { + if(percent < 0 || percent > 100) + throw new IndexOutOfBoundsException( + percent + " percent"); + } +} + +record Tank(Type type, Level level) {} + +public class Tanks { + static String check(Tank tank) { + return switch(tank) { + case Tank t && t.type() == Type.TOXIC + -> "Toxic: " + t; + case Tank t && ( // [1] + t.type() == Type.TOXIC && + t.level().percent() < 50 + ) -> "Toxic, low: " + t; + case Tank t && t.type() == Type.FLAMMABLE + -> "Flammable: " + t; + // Equivalent to "default": + case Tank t -> "Other Tank: " + t; + }; + } + public static void main(String[] args) { + List.of( + new Tank(Type.TOXIC, new Level(49)), + new Tank(Type.FLAMMABLE, new Level(52)), + new Tank(Type.NEUTRAL, new Level(75)) + ).forEach( + t -> System.out.println(check(t)) + ); + } +} diff --git a/enums/AlarmPoints.java b/enums/AlarmPoints.java index ddca40188..484ee4f63 100644 --- a/enums/AlarmPoints.java +++ b/enums/AlarmPoints.java @@ -1,5 +1,5 @@ // enums/AlarmPoints.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package enums; diff --git a/enums/BigEnumSet.java b/enums/BigEnumSet.java index 1c0544640..8e2127b7a 100644 --- a/enums/BigEnumSet.java +++ b/enums/BigEnumSet.java @@ -1,5 +1,5 @@ // enums/BigEnumSet.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/enums/Burrito2.java b/enums/Burrito2.java index 5999ce0e4..5892eaf73 100644 --- a/enums/Burrito2.java +++ b/enums/Burrito2.java @@ -1,5 +1,5 @@ // enums/Burrito2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java enums.Burrito2} @@ -11,8 +11,7 @@ public class Burrito2 { public Burrito2(SpicinessEnum degree) { this.degree = degree; } - @Override - public String toString() { + @Override public String toString() { return "Burrito is "+ degree; } public static void main(String[] args) { diff --git a/enums/CarWash.java b/enums/CarWash.java index 8111cb305..1b6fc856f 100644 --- a/enums/CarWash.java +++ b/enums/CarWash.java @@ -1,5 +1,5 @@ // enums/CarWash.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -7,44 +7,37 @@ public class CarWash { public enum Cycle { UNDERBODY { - @Override - void action() { + @Override void action() { System.out.println("Spraying the underbody"); } }, WHEELWASH { - @Override - void action() { + @Override void action() { System.out.println("Washing the wheels"); } }, PREWASH { - @Override - void action() { + @Override void action() { System.out.println("Loosening the dirt"); } }, BASIC { - @Override - void action() { + @Override void action() { System.out.println("The basic wash"); } }, HOTWAX { - @Override - void action() { + @Override void action() { System.out.println("Applying hot wax"); } }, RINSE { - @Override - void action() { + @Override void action() { System.out.println("Rinsing"); } }, BLOWDRY { - @Override - void action() { + @Override void action() { System.out.println("Blowing dry"); } }; @@ -59,8 +52,7 @@ public void washCar() { for(Cycle c : cycles) c.action(); } - @Override - public String toString() { + @Override public String toString() { return cycles.toString(); } public static void main(String[] args) { diff --git a/enums/Competitor.java b/enums/Competitor.java index 2f1514681..5232d7d36 100644 --- a/enums/Competitor.java +++ b/enums/Competitor.java @@ -1,5 +1,5 @@ // enums/Competitor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Switching one enum on another diff --git a/enums/ConstantSpecificMethod.java b/enums/ConstantSpecificMethod.java index c8f6ef0ff..04ee956bb 100644 --- a/enums/ConstantSpecificMethod.java +++ b/enums/ConstantSpecificMethod.java @@ -1,5 +1,5 @@ // enums/ConstantSpecificMethod.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -7,22 +7,19 @@ public enum ConstantSpecificMethod { DATE_TIME { - @Override - String getInfo() { + @Override String getInfo() { return DateFormat.getDateInstance() .format(new Date()); } }, CLASSPATH { - @Override - String getInfo() { + @Override String getInfo() { return System.getenv("CLASSPATH"); } }, VERSION { - @Override - String getInfo() { + @Override String getInfo() { return System.getProperty("java.version"); } }; @@ -33,9 +30,8 @@ public static void main(String[] args) { } } /* Output: -May 9, 2017 -C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\\gradle\wrapper\gradle- -wrapper.jar -1.8.0_112 +Jan 24, 2021 +C:\Git\OnJava8\ExtractedExamples\\gradle\wrapper\gradle +-wrapper.jar +1.8.0_41 */ diff --git a/enums/EnumClass.java b/enums/EnumClass.java index 1999c6f43..a7ec9cea2 100644 --- a/enums/EnumClass.java +++ b/enums/EnumClass.java @@ -1,5 +1,5 @@ // enums/EnumClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Capabilities of the Enum class diff --git a/enums/EnumMaps.java b/enums/EnumMaps.java index 79b5e6c88..2adeffcc9 100644 --- a/enums/EnumMaps.java +++ b/enums/EnumMaps.java @@ -1,5 +1,5 @@ // enums/EnumMaps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Basics of EnumMaps diff --git a/enums/EnumSets.java b/enums/EnumSets.java index 838b26991..afb9fa7b1 100644 --- a/enums/EnumSets.java +++ b/enums/EnumSets.java @@ -1,5 +1,5 @@ // enums/EnumSets.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Operations on EnumSets diff --git a/enums/Input.java b/enums/Input.java index e9a178d82..c7be7babc 100644 --- a/enums/Input.java +++ b/enums/Input.java @@ -1,5 +1,5 @@ // enums/Input.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -8,14 +8,12 @@ public enum Input { NICKEL(5), DIME(10), QUARTER(25), DOLLAR(100), TOOTHPASTE(200), CHIPS(75), SODA(100), SOAP(50), ABORT_TRANSACTION { - @Override - public int amount() { // Disallow + @Override public int amount() { // Disallow throw new RuntimeException("ABORT.amount()"); } }, STOP { // This must be the last instance. - @Override - public int amount() { // Disallow + @Override public int amount() { // Disallow throw new RuntimeException("SHUT_DOWN.amount()"); } diff --git a/enums/Item.java b/enums/Item.java new file mode 100644 index 000000000..1fd45d2fe --- /dev/null +++ b/enums/Item.java @@ -0,0 +1,12 @@ +// enums/Item.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package enums; + +public interface Item { + Outcome compete(Item it); + Outcome eval(Paper p); + Outcome eval(Scissors s); + Outcome eval(Rock r); +} diff --git a/enums/NonEnum.java b/enums/NonEnum.java index a1ef0ac8b..cbd1e72b5 100644 --- a/enums/NonEnum.java +++ b/enums/NonEnum.java @@ -1,5 +1,5 @@ // enums/NonEnum.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/enums/NotClasses.java b/enums/NotClasses.java index c58a16c47..efd83c8fb 100644 --- a/enums/NotClasses.java +++ b/enums/NotClasses.java @@ -1,25 +1,23 @@ // enums/NotClasses.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// {javap -c LikeClasses} +// {ExcludeFromGradle} +// javap -c LikeClasses enum LikeClasses { WINKEN { - @Override - void behavior() { + @Override void behavior() { System.out.println("Behavior1"); } }, BLINKEN { - @Override - void behavior() { + @Override void behavior() { System.out.println("Behavior2"); } }, NOD { - @Override - void behavior() { + @Override void behavior() { System.out.println("Behavior3"); } }; diff --git a/enums/Outcome.java b/enums/Outcome.java index da1cf8401..75b343b5f 100644 --- a/enums/Outcome.java +++ b/enums/Outcome.java @@ -1,5 +1,5 @@ // enums/Outcome.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package enums; diff --git a/enums/OverrideConstantSpecific.java b/enums/OverrideConstantSpecific.java index 6ea818eea..a9ba41818 100644 --- a/enums/OverrideConstantSpecific.java +++ b/enums/OverrideConstantSpecific.java @@ -1,13 +1,12 @@ // enums/OverrideConstantSpecific.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public enum OverrideConstantSpecific { NUT, BOLT, WASHER { - @Override - void f() { + @Override void f() { System.out.println("Overridden method"); } }; diff --git a/enums/OzWitch.java b/enums/OzWitch.java index 67aea7f5e..275961a12 100644 --- a/enums/OzWitch.java +++ b/enums/OzWitch.java @@ -1,5 +1,5 @@ // enums/OzWitch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The witches in the land of Oz diff --git a/enums/Paper.java b/enums/Paper.java new file mode 100644 index 000000000..7273a5c18 --- /dev/null +++ b/enums/Paper.java @@ -0,0 +1,21 @@ +// enums/Paper.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package enums; +import static enums.Outcome.*; + +public class Paper implements Item { + @Override public Outcome compete(Item it) { + return it.eval(this); + } + @Override + public Outcome eval(Paper p) { return DRAW; } + @Override + public Outcome eval(Scissors s) { return WIN; } + @Override + public Outcome eval(Rock r) { return LOSE; } + @Override public String toString() { + return "Paper"; + } +} diff --git a/enums/PostOffice.java b/enums/PostOffice.java index 2209d9ac7..2aef48f95 100644 --- a/enums/PostOffice.java +++ b/enums/PostOffice.java @@ -1,5 +1,5 @@ // enums/PostOffice.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Modeling a post office @@ -20,12 +20,13 @@ enum ReturnAddress {MISSING,OK1,OK2,OK3,OK4,OK5} ReturnAddress returnAddress; static long counter = 0; long id = counter++; - @Override - public String toString() { return "Mail " + id; } + @Override public String toString() { + return "Mail " + id; + } public String details() { return toString() + ", General Delivery: " + generalDelivery + - ", Address Scanability: " + scannability + + ", Address Scannability: " + scannability + ", Address Readability: " + readability + ", Address Address: " + address + ", Return address: " + returnAddress; @@ -48,15 +49,12 @@ public static Mail randomMail() { Iterable generator(final int count) { return new Iterable() { int n = count; - @Override - public Iterator iterator() { + @Override public Iterator iterator() { return new Iterator() { - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return n-- > 0; } - @Override - public Mail next() { + @Override public Mail next() { return randomMail(); } @Override @@ -72,8 +70,7 @@ public void remove() { // Not implemented public class PostOffice { enum MailHandler { GENERAL_DELIVERY { - @Override - boolean handle(Mail m) { + @Override boolean handle(Mail m) { switch(m.generalDelivery) { case YES: System.out.println( @@ -84,8 +81,7 @@ boolean handle(Mail m) { } }, MACHINE_SCAN { - @Override - boolean handle(Mail m) { + @Override boolean handle(Mail m) { switch(m.scannability) { case UNSCANNABLE: return false; default: @@ -100,8 +96,7 @@ boolean handle(Mail m) { } }, VISUAL_INSPECTION { - @Override - boolean handle(Mail m) { + @Override boolean handle(Mail m) { switch(m.readability) { case ILLEGIBLE: return false; default: @@ -116,8 +111,7 @@ boolean handle(Mail m) { } }, RETURN_TO_SENDER { - @Override - boolean handle(Mail m) { + @Override boolean handle(Mail m) { switch(m.returnAddress) { case MISSING: return false; default: @@ -144,52 +138,52 @@ public static void main(String[] args) { } } /* Output: -Mail 0, General Delivery: NO2, Address Scanability: +Mail 0, General Delivery: NO2, Address Scannability: UNSCANNABLE, Address Readability: YES3, Address Address: OK1, Return address: OK1 Delivering Mail 0 normally ***** -Mail 1, General Delivery: NO5, Address Scanability: +Mail 1, General Delivery: NO5, Address Scannability: YES3, Address Readability: ILLEGIBLE, Address Address: OK5, Return address: OK1 Delivering Mail 1 automatically ***** -Mail 2, General Delivery: YES, Address Scanability: +Mail 2, General Delivery: YES, Address Scannability: YES3, Address Readability: YES1, Address Address: OK1, Return address: OK5 Using general delivery for Mail 2 ***** -Mail 3, General Delivery: NO4, Address Scanability: +Mail 3, General Delivery: NO4, Address Scannability: YES3, Address Readability: YES1, Address Address: INCORRECT, Return address: OK4 Returning Mail 3 to sender ***** -Mail 4, General Delivery: NO4, Address Scanability: +Mail 4, General Delivery: NO4, Address Scannability: UNSCANNABLE, Address Readability: YES1, Address Address: INCORRECT, Return address: OK2 Returning Mail 4 to sender ***** -Mail 5, General Delivery: NO3, Address Scanability: +Mail 5, General Delivery: NO3, Address Scannability: YES1, Address Readability: ILLEGIBLE, Address Address: OK4, Return address: OK2 Delivering Mail 5 automatically ***** -Mail 6, General Delivery: YES, Address Scanability: +Mail 6, General Delivery: YES, Address Scannability: YES4, Address Readability: ILLEGIBLE, Address Address: OK4, Return address: OK4 Using general delivery for Mail 6 ***** -Mail 7, General Delivery: YES, Address Scanability: +Mail 7, General Delivery: YES, Address Scannability: YES3, Address Readability: YES4, Address Address: OK2, Return address: MISSING Using general delivery for Mail 7 ***** -Mail 8, General Delivery: NO3, Address Scanability: +Mail 8, General Delivery: NO3, Address Scannability: YES1, Address Readability: YES3, Address Address: INCORRECT, Return address: MISSING Mail 8 is a dead letter ***** -Mail 9, General Delivery: NO1, Address Scanability: +Mail 9, General Delivery: NO1, Address Scannability: UNSCANNABLE, Address Readability: YES2, Address Address: OK1, Return address: OK4 Delivering Mail 9 normally diff --git a/enums/RandomTest.java b/enums/RandomTest.java index 9d74531fa..724009735 100644 --- a/enums/RandomTest.java +++ b/enums/RandomTest.java @@ -1,5 +1,5 @@ // enums/RandomTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/enums/Reflection.java b/enums/Reflection.java index 92799a941..d9ac05a7b 100644 --- a/enums/Reflection.java +++ b/enums/Reflection.java @@ -1,5 +1,5 @@ // enums/Reflection.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Analyzing enums using reflection @@ -38,7 +38,7 @@ public static void main(String[] args) { System.out.println(exploreMethods); // Decompile the code for the enum: OSExecute.command( - "javap -cp build/classes/main Explore"); + "javap -cp build/classes/java/main Explore"); } } /* Output: diff --git a/enums/RoShamBo.java b/enums/RoShamBo.java index 09ef7fc03..708584d98 100644 --- a/enums/RoShamBo.java +++ b/enums/RoShamBo.java @@ -1,5 +1,5 @@ // enums/RoShamBo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Common tools for RoShamBo examples diff --git a/enums/RoShamBo1.java b/enums/RoShamBo1.java index 7fba68962..d20f0bbcd 100644 --- a/enums/RoShamBo1.java +++ b/enums/RoShamBo1.java @@ -1,64 +1,11 @@ // enums/RoShamBo1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstration of multiple dispatching // {java enums.RoShamBo1} package enums; import java.util.*; -import static enums.Outcome.*; - -interface Item { - Outcome compete(Item it); - Outcome eval(Paper p); - Outcome eval(Scissors s); - Outcome eval(Rock r); -} - -class Paper implements Item { - @Override - public Outcome compete(Item it) { - return it.eval(this); - } - @Override - public Outcome eval(Paper p) { return DRAW; } - @Override - public Outcome eval(Scissors s) { return WIN; } - @Override - public Outcome eval(Rock r) { return LOSE; } - @Override - public String toString() { return "Paper"; } -} - -class Scissors implements Item { - @Override - public Outcome compete(Item it) { - return it.eval(this); - } - @Override - public Outcome eval(Paper p) { return LOSE; } - @Override - public Outcome eval(Scissors s) { return DRAW; } - @Override - public Outcome eval(Rock r) { return WIN; } - @Override - public String toString() { return "Scissors"; } -} - -class Rock implements Item { - @Override - public Outcome compete(Item it) { - return it.eval(this); - } - @Override - public Outcome eval(Paper p) { return WIN; } - @Override - public Outcome eval(Scissors s) { return LOSE; } - @Override - public Outcome eval(Rock r) { return DRAW; } - @Override - public String toString() { return "Rock"; } -} public class RoShamBo1 { static final int SIZE = 20; diff --git a/enums/RoShamBo2.java b/enums/RoShamBo2.java index db52d4589..16786562a 100644 --- a/enums/RoShamBo2.java +++ b/enums/RoShamBo2.java @@ -1,5 +1,5 @@ // enums/RoShamBo2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Switching one enum on another @@ -18,8 +18,7 @@ public enum RoShamBo2 implements Competitor { this.vSCISSORS = scissors; this.vROCK = rock; } - @Override - public Outcome compete(RoShamBo2 it) { + @Override public Outcome compete(RoShamBo2 it) { switch(it) { default: case PAPER: return vPAPER; diff --git a/enums/RoShamBo3.java b/enums/RoShamBo3.java index 046912dd4..91683dce7 100644 --- a/enums/RoShamBo3.java +++ b/enums/RoShamBo3.java @@ -1,5 +1,5 @@ // enums/RoShamBo3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using constant-specific methods @@ -9,8 +9,7 @@ public enum RoShamBo3 implements Competitor { PAPER { - @Override - public Outcome compete(RoShamBo3 it) { + @Override public Outcome compete(RoShamBo3 it) { switch(it) { default: // To placate the compiler case PAPER: return DRAW; @@ -20,8 +19,7 @@ public Outcome compete(RoShamBo3 it) { } }, SCISSORS { - @Override - public Outcome compete(RoShamBo3 it) { + @Override public Outcome compete(RoShamBo3 it) { switch(it) { default: case PAPER: return WIN; @@ -31,8 +29,7 @@ public Outcome compete(RoShamBo3 it) { } }, ROCK { - @Override - public Outcome compete(RoShamBo3 it) { + @Override public Outcome compete(RoShamBo3 it) { switch(it) { default: case PAPER: return LOSE; diff --git a/enums/RoShamBo4.java b/enums/RoShamBo4.java index b129e09da..2ad59aa96 100644 --- a/enums/RoShamBo4.java +++ b/enums/RoShamBo4.java @@ -1,5 +1,5 @@ // enums/RoShamBo4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java enums.RoShamBo4} diff --git a/enums/RoShamBo5.java b/enums/RoShamBo5.java index eabddd3de..8f6b996ec 100644 --- a/enums/RoShamBo5.java +++ b/enums/RoShamBo5.java @@ -1,5 +1,5 @@ // enums/RoShamBo5.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Multiple dispatching using an EnumMap of EnumMaps @@ -27,8 +27,7 @@ static void initRow(RoShamBo5 it, row.put(RoShamBo5.SCISSORS, vSCISSORS); row.put(RoShamBo5.ROCK, vROCK); } - @Override - public Outcome compete(RoShamBo5 it) { + @Override public Outcome compete(RoShamBo5 it) { return table.get(this).get(it); } public static void main(String[] args) { diff --git a/enums/RoShamBo6.java b/enums/RoShamBo6.java index d1e2e0268..3d66d894d 100644 --- a/enums/RoShamBo6.java +++ b/enums/RoShamBo6.java @@ -1,5 +1,5 @@ // enums/RoShamBo6.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Enums using "tables" instead of multiple dispatch @@ -14,8 +14,7 @@ enum RoShamBo6 implements Competitor { { WIN, DRAW, LOSE }, // SCISSORS { LOSE, WIN, DRAW }, // ROCK }; - @Override - public Outcome compete(RoShamBo6 other) { + @Override public Outcome compete(RoShamBo6 other) { return table[this.ordinal()][other.ordinal()]; } public static void main(String[] args) { diff --git a/enums/Rock.java b/enums/Rock.java new file mode 100644 index 000000000..f9e5f7046 --- /dev/null +++ b/enums/Rock.java @@ -0,0 +1,21 @@ +// enums/Rock.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package enums; +import static enums.Outcome.*; + +public class Rock implements Item { + @Override public Outcome compete(Item it) { + return it.eval(this); + } + @Override + public Outcome eval(Paper p) { return WIN; } + @Override + public Outcome eval(Scissors s) { return LOSE; } + @Override + public Outcome eval(Rock r) { return DRAW; } + @Override public String toString() { + return "Rock"; + } +} diff --git a/enums/Scissors.java b/enums/Scissors.java new file mode 100644 index 000000000..45bab4996 --- /dev/null +++ b/enums/Scissors.java @@ -0,0 +1,21 @@ +// enums/Scissors.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package enums; +import static enums.Outcome.*; + +public class Scissors implements Item { + @Override public Outcome compete(Item it) { + return it.eval(this); + } + @Override + public Outcome eval(Paper p) { return LOSE; } + @Override + public Outcome eval(Scissors s) { return DRAW; } + @Override + public Outcome eval(Rock r) { return WIN; } + @Override public String toString() { + return "Scissors"; + } +} diff --git a/enums/SecurityCategory.java b/enums/SecurityCategory.java index 908ebe9cb..18dd0f62a 100644 --- a/enums/SecurityCategory.java +++ b/enums/SecurityCategory.java @@ -1,5 +1,5 @@ // enums/SecurityCategory.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // More succinct subcategorization of enums diff --git a/enums/SpaceShip.java b/enums/SpaceShip.java index 95e23f4e5..45a5485fb 100644 --- a/enums/SpaceShip.java +++ b/enums/SpaceShip.java @@ -1,5 +1,5 @@ // enums/SpaceShip.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; @@ -7,8 +7,7 @@ public enum SpaceShip { SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP; - @Override - public String toString() { + @Override public String toString() { String id = name(); String lower = id.substring(1).toLowerCase(); return id.charAt(0) + lower; diff --git a/enums/SpicinessEnum.java b/enums/SpicinessEnum.java index 78f4518a7..02b54ee4d 100644 --- a/enums/SpicinessEnum.java +++ b/enums/SpicinessEnum.java @@ -1,5 +1,5 @@ // enums/SpicinessEnum.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package enums; diff --git a/enums/TrafficLight.java b/enums/TrafficLight.java index 9be9d3e8a..a42089a7a 100644 --- a/enums/TrafficLight.java +++ b/enums/TrafficLight.java @@ -1,5 +1,5 @@ // enums/TrafficLight.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Enums in switch statements @@ -21,8 +21,7 @@ public void change() { break; } } - @Override - public String toString() { + @Override public String toString() { return "The traffic light is " + color; } public static void main(String[] args) { diff --git a/enums/UpcastEnum.java b/enums/UpcastEnum.java index 31995bd64..5665e2e3d 100644 --- a/enums/UpcastEnum.java +++ b/enums/UpcastEnum.java @@ -1,5 +1,5 @@ // enums/UpcastEnum.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // No values() method if you upcast an enum diff --git a/enums/VendingMachine.java b/enums/VendingMachine.java index fbc976df6..269dd0131 100644 --- a/enums/VendingMachine.java +++ b/enums/VendingMachine.java @@ -1,5 +1,5 @@ // enums/VendingMachine.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java VendingMachine VendingMachineInput.txt} @@ -37,8 +37,7 @@ public class VendingMachine { enum StateDuration { TRANSIENT } // Tagging enum enum State { RESTING { - @Override - void next(Input input) { + @Override void next(Input input) { switch(Category.categorize(input)) { case MONEY: amount += input.amount(); @@ -51,8 +50,7 @@ void next(Input input) { } }, ADDING_MONEY { - @Override - void next(Input input) { + @Override void next(Input input) { switch(Category.categorize(input)) { case MONEY: amount += input.amount(); @@ -74,16 +72,14 @@ void next(Input input) { } }, DISPENSING(StateDuration.TRANSIENT) { - @Override - void next() { + @Override void next() { System.out.println("here is your " + selection); amount -= selection.amount(); state = GIVING_CHANGE; } }, GIVING_CHANGE(StateDuration.TRANSIENT) { - @Override - void next() { + @Override void next() { if(amount > 0) { System.out.println("Your change: " + amount); amount = 0; @@ -125,8 +121,7 @@ public static void main(String[] args) { // For a basic sanity check: class RandomInputSupplier implements Supplier { - @Override - public Input get() { + @Override public Input get() { return Input.randomSelection(); } } @@ -146,8 +141,7 @@ class FileInputSupplier implements Supplier { throw new RuntimeException(e); } } - @Override - public Input get() { + @Override public Input get() { if(!input.hasNext()) return null; return Enum.valueOf( diff --git a/enums/cartoons/EnumImplementation.java b/enums/cartoons/EnumImplementation.java index cb3abaa0f..5d1cb0d50 100644 --- a/enums/cartoons/EnumImplementation.java +++ b/enums/cartoons/EnumImplementation.java @@ -1,5 +1,5 @@ // enums/cartoons/EnumImplementation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // An enum can implement an interface @@ -14,8 +14,7 @@ enum CartoonCharacter SILLY, BOUNCY, NUTTY, BOB; private Random rand = new Random(47); - @Override - public CartoonCharacter get() { + @Override public CartoonCharacter get() { return values()[rand.nextInt(values().length)]; } } diff --git a/enums/menu/Course.java b/enums/menu/Course.java index a11fdace9..7cb54ef1a 100644 --- a/enums/menu/Course.java +++ b/enums/menu/Course.java @@ -1,5 +1,5 @@ // enums/menu/Course.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package enums.menu; diff --git a/enums/menu/Food.java b/enums/menu/Food.java index bfe8dd553..51f4a8a07 100644 --- a/enums/menu/Food.java +++ b/enums/menu/Food.java @@ -1,5 +1,5 @@ // enums/menu/Food.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Subcategorization of enums within interfaces @@ -11,7 +11,7 @@ enum Appetizer implements Food { } enum MainCourse implements Food { LASAGNE, BURRITO, PAD_THAI, - LENTILS, HUMMOUS, VINDALOO; + LENTILS, HUMMUS, VINDALOO; } enum Dessert implements Food { TIRAMISU, GELATO, BLACK_FOREST_CAKE, diff --git a/enums/menu/Meal.java b/enums/menu/Meal.java index 3bd12ed21..48b7f723b 100644 --- a/enums/menu/Meal.java +++ b/enums/menu/Meal.java @@ -1,5 +1,5 @@ // enums/menu/Meal.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java enums.menu.Meal} diff --git a/enums/menu/Meal2.java b/enums/menu/Meal2.java index 17bbdf6e9..0064926e0 100644 --- a/enums/menu/Meal2.java +++ b/enums/menu/Meal2.java @@ -1,5 +1,5 @@ // enums/menu/Meal2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java enums.menu.Meal2} @@ -21,7 +21,7 @@ enum Appetizer implements Food { } enum MainCourse implements Food { LASAGNE, BURRITO, PAD_THAI, - LENTILS, HUMMOUS, VINDALOO; + LENTILS, HUMMUS, VINDALOO; } enum Dessert implements Food { TIRAMISU, GELATO, BLACK_FOREST_CAKE, diff --git a/enums/menu/TypeOfFood.java b/enums/menu/TypeOfFood.java index 7909f1f4a..d11fce81c 100644 --- a/enums/menu/TypeOfFood.java +++ b/enums/menu/TypeOfFood.java @@ -1,5 +1,5 @@ // enums/menu/TypeOfFood.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java enums.menu.TypeOfFood} diff --git a/equalshashcode/ComposedEquality.java b/equalshashcode/ComposedEquality.java index 01fe792e3..58ad001de 100644 --- a/equalshashcode/ComposedEquality.java +++ b/equalshashcode/ComposedEquality.java @@ -1,5 +1,5 @@ // equalshashcode/ComposedEquality.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -11,8 +11,7 @@ class Part { this.ss = ss; this.dd = dd; } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof Part && Objects.equals(ss, ((Part)rval).ss) && Objects.equals(dd, ((Part)rval).dd); @@ -26,8 +25,7 @@ public ComposedEquality(int i, String s, double d) { part = new Part(s, d); System.out.println("made 'ComposedEquality'"); } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof ComposedEquality && super.equals(rval) && Objects.equals(part, diff --git a/equalshashcode/CountedString.java b/equalshashcode/CountedString.java index f3c5823ec..4b7c0aab7 100644 --- a/equalshashcode/CountedString.java +++ b/equalshashcode/CountedString.java @@ -1,5 +1,5 @@ // equalshashcode/CountedString.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating a good hashCode() @@ -19,13 +19,11 @@ public CountedString(String str) { if(s2.equals(s)) id++; } - @Override - public String toString() { + @Override public String toString() { return "String: " + s + " id: " + id + " hashCode(): " + hashCode(); } - @Override - public int hashCode() { + @Override public int hashCode() { // The very simple approach: // return s.hashCode() * id; // Using Joshua Bloch's recipe: @@ -34,8 +32,7 @@ public int hashCode() { result = 37 * result + id; return result; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof CountedString && Objects.equals(s, ((CountedString)o).s) && Objects.equals(id, ((CountedString)o).id); diff --git a/equalshashcode/DefaultComparison.java b/equalshashcode/DefaultComparison.java index 541e918ea..1c5c03ab9 100644 --- a/equalshashcode/DefaultComparison.java +++ b/equalshashcode/DefaultComparison.java @@ -1,5 +1,5 @@ // equalshashcode/DefaultComparison.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/equalshashcode/Equality.java b/equalshashcode/Equality.java index 1565b33f8..46661bc8a 100644 --- a/equalshashcode/Equality.java +++ b/equalshashcode/Equality.java @@ -1,5 +1,5 @@ // equalshashcode/Equality.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -14,8 +14,7 @@ public Equality(int i, String s, double d) { this.d = d; System.out.println("made 'Equality'"); } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { if(rval == null) return false; if(rval == this) diff --git a/equalshashcode/EqualityFactory.java b/equalshashcode/EqualityFactory.java index 0f391cbd8..1718cdba2 100644 --- a/equalshashcode/EqualityFactory.java +++ b/equalshashcode/EqualityFactory.java @@ -1,5 +1,5 @@ // equalshashcode/EqualityFactory.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/equalshashcode/Groundhog.java b/equalshashcode/Groundhog.java index 2f0513f43..bdc941114 100644 --- a/equalshashcode/Groundhog.java +++ b/equalshashcode/Groundhog.java @@ -1,5 +1,5 @@ // equalshashcode/Groundhog.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Looks plausible, but doesn't work as a HashMap key @@ -7,8 +7,7 @@ public class Groundhog { protected int number; public Groundhog(int n) { number = n; } - @Override - public String toString() { + @Override public String toString() { return "Groundhog #" + number; } } diff --git a/equalshashcode/Groundhog2.java b/equalshashcode/Groundhog2.java index 70f253d81..124eaa9e8 100644 --- a/equalshashcode/Groundhog2.java +++ b/equalshashcode/Groundhog2.java @@ -1,5 +1,5 @@ // equalshashcode/Groundhog2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A class that's used as a key in a HashMap @@ -10,8 +10,7 @@ public class Groundhog2 extends Groundhog { public Groundhog2(int n) { super(n); } @Override public int hashCode() { return number; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof Groundhog2 && Objects.equals( number, ((Groundhog2)o).number); diff --git a/equalshashcode/IndividualTest.java b/equalshashcode/IndividualTest.java index 9a6e8112e..0be8de2d9 100644 --- a/equalshashcode/IndividualTest.java +++ b/equalshashcode/IndividualTest.java @@ -1,9 +1,9 @@ // equalshashcode/IndividualTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import collections.MapOfList; -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class IndividualTest { diff --git a/equalshashcode/MapEntry.java b/equalshashcode/MapEntry.java index a6c106036..fff73332a 100644 --- a/equalshashcode/MapEntry.java +++ b/equalshashcode/MapEntry.java @@ -1,5 +1,5 @@ // equalshashcode/MapEntry.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A simple Map.Entry for sample Map implementations @@ -12,31 +12,25 @@ public MapEntry(K key, V value) { this.key = key; this.value = value; } - @Override - public K getKey() { return key; } - @Override - public V getValue() { return value; } - @Override - public V setValue(V v) { + @Override public K getKey() { return key; } + @Override public V getValue() { return value; } + @Override public V setValue(V v) { V result = value; value = v; return result; } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hash(key, value); } @SuppressWarnings("unchecked") - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof MapEntry && Objects.equals(key, ((MapEntry)rval).getKey()) && Objects.equals(value, ((MapEntry)rval).getValue()); } - @Override - public String toString() { + @Override public String toString() { return key + "=" + value; } } diff --git a/equalshashcode/Prediction.java b/equalshashcode/Prediction.java index 7706aec1f..ab945fc52 100644 --- a/equalshashcode/Prediction.java +++ b/equalshashcode/Prediction.java @@ -1,5 +1,5 @@ // equalshashcode/Prediction.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Predicting the weather @@ -7,8 +7,7 @@ public class Prediction { private static Random rand = new Random(47); - @Override - public String toString() { + @Override public String toString() { return rand.nextBoolean() ? "Six more weeks of Winter!" : "Early Spring!"; } diff --git a/equalshashcode/SimpleHashMap.java b/equalshashcode/SimpleHashMap.java index 4658ec53e..b47806441 100644 --- a/equalshashcode/SimpleHashMap.java +++ b/equalshashcode/SimpleHashMap.java @@ -1,5 +1,5 @@ // equalshashcode/SimpleHashMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A demonstration hashed Map @@ -16,8 +16,7 @@ class SimpleHashMap extends AbstractMap { @SuppressWarnings("unchecked") LinkedList>[] buckets = new LinkedList[SIZE]; - @Override - public V put(K key, V value) { + @Override public V put(K key, V value) { V oldValue = null; int index = Math.abs(key.hashCode()) % SIZE; if(buckets[index] == null) @@ -40,8 +39,7 @@ public V put(K key, V value) { buckets[index].add(pair); return oldValue; } - @Override - public V get(Object key) { + @Override public V get(Object key) { int index = Math.abs(key.hashCode()) % SIZE; if(buckets[index] == null) return null; for(MapEntry iPair : buckets[index]) @@ -49,8 +47,7 @@ public V get(Object key) { return iPair.getValue(); return null; } - @Override - public Set> entrySet() { + @Override public Set> entrySet() { Set> set= new HashSet<>(); for(LinkedList> bucket : buckets) { if(bucket == null) continue; diff --git a/equalshashcode/SlowMap.java b/equalshashcode/SlowMap.java index 91c9967dd..04d0a85d8 100644 --- a/equalshashcode/SlowMap.java +++ b/equalshashcode/SlowMap.java @@ -1,5 +1,5 @@ // equalshashcode/SlowMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A Map implemented with ArrayLists @@ -9,8 +9,7 @@ public class SlowMap extends AbstractMap { private List keys = new ArrayList<>(); private List values = new ArrayList<>(); - @Override - public V put(K key, V value) { + @Override public V put(K key, V value) { V oldValue = get(key); // The old value or null if(!keys.contains(key)) { keys.add(key); @@ -25,8 +24,7 @@ public V get(Object key) { // key: type Object, not K return null; return values.get(keys.indexOf(key)); } - @Override - public Set> entrySet() { + @Override public Set> entrySet() { Set> set= new HashSet<>(); Iterator ki = keys.iterator(); Iterator vi = values.iterator(); diff --git a/equalshashcode/SpringDetector.java b/equalshashcode/SpringDetector.java index 713d032c1..d92f20b54 100644 --- a/equalshashcode/SpringDetector.java +++ b/equalshashcode/SpringDetector.java @@ -1,5 +1,5 @@ // equalshashcode/SpringDetector.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // What will the weather be? @@ -47,16 +47,16 @@ public static void main(String[] args) { } } /* Output: -Groundhog #3: Six more weeks of Winter! +Groundhog #5: Six more weeks of Winter! +Groundhog #2: Early Spring! +Groundhog #1: Six more weeks of Winter! Groundhog #0: Early Spring! -Groundhog #8: Six more weeks of Winter! -Groundhog #6: Early Spring! +Groundhog #8: Early Spring! +Groundhog #6: Six more weeks of Winter! Groundhog #4: Early Spring! -Groundhog #2: Six more weeks of Winter! -Groundhog #1: Early Spring! -Groundhog #9: Early Spring! -Groundhog #5: Six more weeks of Winter! +Groundhog #3: Early Spring! Groundhog #7: Six more weeks of Winter! +Groundhog #9: Six more weeks of Winter! Looking up prediction for Groundhog #3 Key not found: Groundhog #3 */ diff --git a/equalshashcode/SpringDetector2.java b/equalshashcode/SpringDetector2.java index ed9db7249..fc0267562 100644 --- a/equalshashcode/SpringDetector2.java +++ b/equalshashcode/SpringDetector2.java @@ -1,5 +1,5 @@ // equalshashcode/SpringDetector2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A working key diff --git a/equalshashcode/StringHashCode.java b/equalshashcode/StringHashCode.java index 69b3df468..e8c2062be 100644 --- a/equalshashcode/StringHashCode.java +++ b/equalshashcode/StringHashCode.java @@ -1,5 +1,5 @@ // equalshashcode/StringHashCode.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/equalshashcode/SubtypeEquality.java b/equalshashcode/SubtypeEquality.java index 4dc1d060a..8d86d6bad 100644 --- a/equalshashcode/SubtypeEquality.java +++ b/equalshashcode/SubtypeEquality.java @@ -1,5 +1,5 @@ // equalshashcode/SubtypeEquality.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -15,20 +15,17 @@ class Animal { this.name = name; this.size = size; } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof Animal && // Objects.equals(id, ((Animal)rval).id) && // [1] Objects.equals(name, ((Animal)rval).name) && Objects.equals(size, ((Animal)rval).size); } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hash(name, size); - // return Objects.hash(name, size, id); // [2] + // return Objects.hash(name, size, id); // [2] } - @Override - public String toString() { + @Override public String toString() { return String.format("%s[%d]: %s %s %x", getClass().getSimpleName(), id, name, size, hashCode()); @@ -56,5 +53,5 @@ public static void main(String[] args) { } } /* Output: -Dog[0]: Ralph MEDIUM a752aeee +Dog[0]: Ralph MEDIUM 931523a9 */ diff --git a/equalshashcode/SubtypeEquality2.java b/equalshashcode/SubtypeEquality2.java index 881749293..a107409ff 100644 --- a/equalshashcode/SubtypeEquality2.java +++ b/equalshashcode/SubtypeEquality2.java @@ -1,5 +1,5 @@ // equalshashcode/SubtypeEquality2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -8,8 +8,7 @@ class Dog2 extends Animal { Dog2(String name, Size size) { super(name, size); } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof Dog2 && super.equals(rval); } @@ -19,8 +18,7 @@ class Pig2 extends Animal { Pig2(String name, Size size) { super(name, size); } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof Pig2 && super.equals(rval); } @@ -35,6 +33,6 @@ public static void main(String[] args) { } } /* Output: -Dog2[0]: Ralph MEDIUM a752aeee -Pig2[1]: Ralph MEDIUM a752aeee +Dog2[0]: Ralph MEDIUM 931523a9 +Pig2[1]: Ralph MEDIUM 931523a9 */ diff --git a/equalshashcode/SuccinctEquality.java b/equalshashcode/SuccinctEquality.java index a1734dadb..7564d5cc5 100644 --- a/equalshashcode/SuccinctEquality.java +++ b/equalshashcode/SuccinctEquality.java @@ -1,5 +1,5 @@ // equalshashcode/SuccinctEquality.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -9,8 +9,7 @@ public SuccinctEquality(int i, String s, double d) { super(i, s, d); System.out.println("made 'SuccinctEquality'"); } - @Override - public boolean equals(Object rval) { + @Override public boolean equals(Object rval) { return rval instanceof SuccinctEquality && Objects.equals(i, ((SuccinctEquality)rval).i) && Objects.equals(s, ((SuccinctEquality)rval).s) && diff --git a/exceptions/AlwaysFinally.java b/exceptions/AlwaysFinally.java index 38b15a12d..11d1e5dd6 100644 --- a/exceptions/AlwaysFinally.java +++ b/exceptions/AlwaysFinally.java @@ -1,5 +1,5 @@ // exceptions/AlwaysFinally.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Finally is always executed diff --git a/exceptions/AutoCloseableDetails.java b/exceptions/AutoCloseableDetails.java index e6f8f77d4..3c0a0d036 100644 --- a/exceptions/AutoCloseableDetails.java +++ b/exceptions/AutoCloseableDetails.java @@ -1,5 +1,5 @@ // exceptions/AutoCloseableDetails.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -8,7 +8,7 @@ class Reporter implements AutoCloseable { Reporter() { System.out.println("Creating " + name); } - public void close() { + @Override public void close() { System.out.println("Closing " + name); } } diff --git a/exceptions/BetterNullPointerReports.java b/exceptions/BetterNullPointerReports.java new file mode 100644 index 000000000..e5ef495b2 --- /dev/null +++ b/exceptions/BetterNullPointerReports.java @@ -0,0 +1,43 @@ +// exceptions/BetterNullPointerReports.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 15 + +class A { + String s; + A(String s) { + this.s = s; + } +} + +class B { + A a; + B(A a) { + this.a = a; + } +} + +class C { + B b; + C(B b) { + this.b = b; + } +} + +public class BetterNullPointerReports { + public static void main(String[] args) { + C[] ca = { + new C(new B(new A(null))), + new C(new B(null)), + new C(null), + }; + for(C c: ca) { + try { + System.out.println(c.b.a.s); + } catch(NullPointerException npe) { + System.out.println(npe); + } + } + } +} diff --git a/exceptions/BodyException.java b/exceptions/BodyException.java index 6e5d47777..25a952a63 100644 --- a/exceptions/BodyException.java +++ b/exceptions/BodyException.java @@ -1,5 +1,5 @@ // exceptions/BodyException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/Cleanup.java b/exceptions/Cleanup.java index 7eeebe32c..0912783d0 100644 --- a/exceptions/Cleanup.java +++ b/exceptions/Cleanup.java @@ -1,5 +1,5 @@ // exceptions/Cleanup.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Guaranteeing proper cleanup of a resource diff --git a/exceptions/CleanupIdiom.java b/exceptions/CleanupIdiom.java index 9b9e18668..fdf6bd1c9 100644 --- a/exceptions/CleanupIdiom.java +++ b/exceptions/CleanupIdiom.java @@ -1,5 +1,5 @@ // exceptions/CleanupIdiom.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Disposable objects must be followed by a try-finally diff --git a/exceptions/CloseExceptions.java b/exceptions/CloseExceptions.java index 6a1a51b0d..bc31496bc 100644 --- a/exceptions/CloseExceptions.java +++ b/exceptions/CloseExceptions.java @@ -1,5 +1,5 @@ // exceptions/CloseExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -10,6 +10,7 @@ class Reporter2 implements AutoCloseable { Reporter2() { System.out.println("Creating " + name); } + @Override public void close() throws CloseException { System.out.println("Closing " + name); } diff --git a/exceptions/ConstructorException.java b/exceptions/ConstructorException.java index 3c48ecf77..24191d1ce 100644 --- a/exceptions/ConstructorException.java +++ b/exceptions/ConstructorException.java @@ -1,5 +1,5 @@ // exceptions/ConstructorException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index dffc67166..07f02b955 100644 --- a/exceptions/DynamicFields.java +++ b/exceptions/DynamicFields.java @@ -1,5 +1,5 @@ // exceptions/DynamicFields.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A Class that dynamically adds fields to itself to @@ -14,8 +14,7 @@ public DynamicFields(int initialSize) { for(int i = 0; i < initialSize; i++) fields[i] = new Object[] { null, null }; } - @Override - public String toString() { + @Override public String toString() { StringBuilder result = new StringBuilder(); for(Object[] obj : fields) { result.append(obj[0]); @@ -121,10 +120,10 @@ public static void main(String[] args) { df.getField("d") : A new value for d DynamicFieldsException at -DynamicFields.setField(DynamicFields.java:65) - at DynamicFields.main(DynamicFields.java:97) +DynamicFields.setField(DynamicFields.java:64) + at DynamicFields.main(DynamicFields.java:96) Caused by: java.lang.NullPointerException at -DynamicFields.setField(DynamicFields.java:67) +DynamicFields.setField(DynamicFields.java:66) ... 1 more */ diff --git a/exceptions/EffectivelyFinalTWR.java b/exceptions/EffectivelyFinalTWR.java new file mode 100644 index 000000000..7ebeaf0d0 --- /dev/null +++ b/exceptions/EffectivelyFinalTWR.java @@ -0,0 +1,48 @@ +// exceptions/EffectivelyFinalTWR.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 9 +import java.io.*; + +public class EffectivelyFinalTWR { + static void old() { + try ( + InputStream r1 = new FileInputStream( + new File("TryWithResources.java")); + InputStream r2 = new FileInputStream( + new File("EffectivelyFinalTWR.java")); + ) { + r1.read(); + r2.read(); + } catch(IOException e) { + // Handle exceptions + } + } + static void jdk9() throws IOException { + final InputStream r1 = new FileInputStream( + new File("TryWithResources.java")); + // Effectively final: + InputStream r2 = new FileInputStream( + new File("EffectivelyFinalTWR.java")); + try (r1; r2) { + r1.read(); + r2.read(); + } + // r1 and r2 are still in scope. Accessing + // either one throws an exception: + r1.read(); + r2.read(); + } + public static void main(String[] args) { + old(); + try { + jdk9(); + } catch(IOException e) { + System.out.println(e); + } + } +} +/* Output: +java.io.IOException: Stream Closed +*/ diff --git a/exceptions/ExceptionMethods.java b/exceptions/ExceptionMethods.java index 3220c1974..d94c0b298 100644 --- a/exceptions/ExceptionMethods.java +++ b/exceptions/ExceptionMethods.java @@ -1,5 +1,5 @@ // exceptions/ExceptionMethods.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrating the Exception Methods diff --git a/exceptions/ExceptionSilencer.java b/exceptions/ExceptionSilencer.java index bb57a939a..c56132efe 100644 --- a/exceptions/ExceptionSilencer.java +++ b/exceptions/ExceptionSilencer.java @@ -1,5 +1,5 @@ // exceptions/ExceptionSilencer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/ExtraFeatures.java b/exceptions/ExtraFeatures.java index 57bb967b0..abf9d0bef 100644 --- a/exceptions/ExtraFeatures.java +++ b/exceptions/ExtraFeatures.java @@ -1,5 +1,5 @@ // exceptions/ExtraFeatures.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Further embellishment of exception classes @@ -13,8 +13,7 @@ class MyException2 extends Exception { this.x = x; } public int val() { return x; } - @Override - public String getMessage() { + @Override public String getMessage() { return "Detail Message: "+ x + " "+ super.getMessage(); } @@ -58,15 +57,15 @@ public static void main(String[] args) { /* Output: Throwing MyException2 from f() MyException2: Detail Message: 0 null - at ExtraFeatures.f(ExtraFeatures.java:24) - at ExtraFeatures.main(ExtraFeatures.java:38) + at ExtraFeatures.f(ExtraFeatures.java:23) + at ExtraFeatures.main(ExtraFeatures.java:37) Throwing MyException2 from g() MyException2: Detail Message: 0 Originated in g() - at ExtraFeatures.g(ExtraFeatures.java:29) - at ExtraFeatures.main(ExtraFeatures.java:43) + at ExtraFeatures.g(ExtraFeatures.java:28) + at ExtraFeatures.main(ExtraFeatures.java:42) Throwing MyException2 from h() MyException2: Detail Message: 47 Originated in h() - at ExtraFeatures.h(ExtraFeatures.java:34) - at ExtraFeatures.main(ExtraFeatures.java:48) + at ExtraFeatures.h(ExtraFeatures.java:33) + at ExtraFeatures.main(ExtraFeatures.java:47) e.val() = 47 */ diff --git a/exceptions/FinallyWorks.java b/exceptions/FinallyWorks.java index c406400da..9870849c3 100644 --- a/exceptions/FinallyWorks.java +++ b/exceptions/FinallyWorks.java @@ -1,5 +1,5 @@ // exceptions/FinallyWorks.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The finally clause is always executed diff --git a/exceptions/FullConstructors.java b/exceptions/FullConstructors.java index c67b4e2f5..bb10b0f1c 100644 --- a/exceptions/FullConstructors.java +++ b/exceptions/FullConstructors.java @@ -1,5 +1,5 @@ // exceptions/FullConstructors.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/Human.java b/exceptions/Human.java index fa067a9e4..b35f77954 100644 --- a/exceptions/Human.java +++ b/exceptions/Human.java @@ -1,5 +1,5 @@ // exceptions/Human.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Catching exception hierarchies diff --git a/exceptions/InheritingExceptions.java b/exceptions/InheritingExceptions.java index 7a6a4dff2..799134842 100644 --- a/exceptions/InheritingExceptions.java +++ b/exceptions/InheritingExceptions.java @@ -1,5 +1,5 @@ // exceptions/InheritingExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating your own exceptions diff --git a/exceptions/InputFile.java b/exceptions/InputFile.java index 0de1fbe9e..d843a8347 100644 --- a/exceptions/InputFile.java +++ b/exceptions/InputFile.java @@ -1,5 +1,5 @@ // exceptions/InputFile.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Paying attention to exceptions in constructors diff --git a/exceptions/InputFile2.java b/exceptions/InputFile2.java index 2cb71a4c1..4e8b8c49c 100644 --- a/exceptions/InputFile2.java +++ b/exceptions/InputFile2.java @@ -1,5 +1,5 @@ // exceptions/InputFile2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/exceptions/LoggingExceptions.java b/exceptions/LoggingExceptions.java index 26e9be687..67dcac911 100644 --- a/exceptions/LoggingExceptions.java +++ b/exceptions/LoggingExceptions.java @@ -1,5 +1,5 @@ // exceptions/LoggingExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // An exception that reports through a Logger @@ -33,13 +33,13 @@ public static void main(String[] args) { } /* Output: ___[ Error Output ]___ -May 09, 2017 6:07:17 AM LoggingException +Jan 24, 2021 8:48:54 AM LoggingException SEVERE: LoggingException at LoggingExceptions.main(LoggingExceptions.java:20) Caught LoggingException -May 09, 2017 6:07:17 AM LoggingException +Jan 24, 2021 8:48:54 AM LoggingException SEVERE: LoggingException at LoggingExceptions.main(LoggingExceptions.java:25) diff --git a/exceptions/LoggingExceptions2.java b/exceptions/LoggingExceptions2.java index 326c20089..2d1c1683c 100644 --- a/exceptions/LoggingExceptions2.java +++ b/exceptions/LoggingExceptions2.java @@ -1,5 +1,5 @@ // exceptions/LoggingExceptions2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Logging caught exceptions @@ -25,7 +25,7 @@ public static void main(String[] args) { } /* Output: ___[ Error Output ]___ -May 09, 2017 6:07:17 AM LoggingExceptions2 logException +Jan 24, 2021 8:48:54 AM LoggingExceptions2 logException SEVERE: java.lang.NullPointerException at LoggingExceptions2.main(LoggingExceptions2.java:17) diff --git a/exceptions/LostMessage.java b/exceptions/LostMessage.java index b0f7c318f..75c57e1c2 100644 --- a/exceptions/LostMessage.java +++ b/exceptions/LostMessage.java @@ -1,19 +1,17 @@ // exceptions/LostMessage.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // How an exception can be lost class VeryImportantException extends Exception { - @Override - public String toString() { + @Override public String toString() { return "A very important exception!"; } } class HoHumException extends Exception { - @Override - public String toString() { + @Override public String toString() { return "A trivial exception"; } } diff --git a/exceptions/MainException.java b/exceptions/MainException.java index 4c6477ec2..a6378469d 100644 --- a/exceptions/MainException.java +++ b/exceptions/MainException.java @@ -1,5 +1,5 @@ // exceptions/MainException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/exceptions/MessyExceptions.java b/exceptions/MessyExceptions.java index e79f929d9..1441abd04 100644 --- a/exceptions/MessyExceptions.java +++ b/exceptions/MessyExceptions.java @@ -1,5 +1,5 @@ // exceptions/MessyExceptions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; @@ -13,7 +13,7 @@ public static void main(String[] args) { int contents = in.read(); // Process contents } catch(IOException e) { - // Handle the error + // Handle errors } finally { if(in != null) { try { diff --git a/exceptions/MultiCatch.java b/exceptions/MultiCatch.java index 64b954e24..c54bab5ea 100644 --- a/exceptions/MultiCatch.java +++ b/exceptions/MultiCatch.java @@ -1,5 +1,5 @@ // exceptions/MultiCatch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/MultiCatch2.java b/exceptions/MultiCatch2.java index 2ba042919..7dfd32dfe 100644 --- a/exceptions/MultiCatch2.java +++ b/exceptions/MultiCatch2.java @@ -1,5 +1,5 @@ // exceptions/MultiCatch2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/MultipleReturns.java b/exceptions/MultipleReturns.java index e6caf3c18..cd8968cb6 100644 --- a/exceptions/MultipleReturns.java +++ b/exceptions/MultipleReturns.java @@ -1,5 +1,5 @@ // exceptions/MultipleReturns.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/NeverCaught.java b/exceptions/NeverCaught.java index a584d0612..bf8e101c2 100644 --- a/exceptions/NeverCaught.java +++ b/exceptions/NeverCaught.java @@ -1,5 +1,5 @@ // exceptions/NeverCaught.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Ignoring RuntimeExceptions diff --git a/exceptions/OnOffException1.java b/exceptions/OnOffException1.java index b15243285..28caacc87 100644 --- a/exceptions/OnOffException1.java +++ b/exceptions/OnOffException1.java @@ -1,5 +1,5 @@ // exceptions/OnOffException1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class OnOffException1 extends Exception {} diff --git a/exceptions/OnOffException2.java b/exceptions/OnOffException2.java index 878ea833f..99d149dae 100644 --- a/exceptions/OnOffException2.java +++ b/exceptions/OnOffException2.java @@ -1,5 +1,5 @@ // exceptions/OnOffException2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class OnOffException2 extends Exception {} diff --git a/exceptions/OnOffSwitch.java b/exceptions/OnOffSwitch.java index 7f4f35b50..f50273e0c 100644 --- a/exceptions/OnOffSwitch.java +++ b/exceptions/OnOffSwitch.java @@ -1,5 +1,5 @@ // exceptions/OnOffSwitch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Why use finally? diff --git a/exceptions/PreciseRethrow.java b/exceptions/PreciseRethrow.java index 8e9749380..1dc44e4ce 100644 --- a/exceptions/PreciseRethrow.java +++ b/exceptions/PreciseRethrow.java @@ -1,5 +1,5 @@ // exceptions/PreciseRethrow.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/RethrowNew.java b/exceptions/RethrowNew.java index e03f75099..1725d0a25 100644 --- a/exceptions/RethrowNew.java +++ b/exceptions/RethrowNew.java @@ -1,5 +1,5 @@ // exceptions/RethrowNew.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Rethrow a different object from the one you caught diff --git a/exceptions/Rethrowing.java b/exceptions/Rethrowing.java index 2a82dafef..7a9c7200a 100644 --- a/exceptions/Rethrowing.java +++ b/exceptions/Rethrowing.java @@ -1,5 +1,5 @@ // exceptions/Rethrowing.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrating fillInStackTrace() diff --git a/exceptions/SameHandler.java b/exceptions/SameHandler.java index 5229dc66e..0e2b18252 100644 --- a/exceptions/SameHandler.java +++ b/exceptions/SameHandler.java @@ -1,5 +1,5 @@ // exceptions/SameHandler.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/exceptions/StormyInning.java b/exceptions/StormyInning.java index 1656d062e..b12d3a944 100644 --- a/exceptions/StormyInning.java +++ b/exceptions/StormyInning.java @@ -1,5 +1,5 @@ // exceptions/StormyInning.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Overridden methods can throw only the exceptions @@ -43,15 +43,12 @@ public StormyInning(String s) //- public void event() throws RainedOut {} // If the method doesn't already exist in the // base class, the exception is OK: - @Override - public void rainHard() throws RainedOut {} + @Override public void rainHard() throws RainedOut {} // You can choose to not throw any exceptions, // even if the base version does: - @Override - public void event() {} + @Override public void event() {} // Overridden methods can throw inherited exceptions: - @Override - public void atBat() throws PopFoul {} + @Override public void atBat() throws PopFoul {} public static void main(String[] args) { try { StormyInning si = new StormyInning(); diff --git a/exceptions/StreamsAreAutoCloseable.java b/exceptions/StreamsAreAutoCloseable.java index 40317d88c..e07600c1e 100644 --- a/exceptions/StreamsAreAutoCloseable.java +++ b/exceptions/StreamsAreAutoCloseable.java @@ -1,5 +1,5 @@ // exceptions/StreamsAreAutoCloseable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; @@ -13,12 +13,12 @@ public class StreamsAreAutoCloseable { Stream in = Files.lines( Paths.get("StreamsAreAutoCloseable.java")); PrintWriter outfile = new PrintWriter( - "Results.txt"); // [1] + "Results.txt"); // [1] ) { in.skip(5) .limit(1) .map(String::toLowerCase) .forEachOrdered(outfile::println); - } // [2] + } // [2] } } diff --git a/exceptions/Switch.java b/exceptions/Switch.java index ea1323ce4..6fb0ec780 100644 --- a/exceptions/Switch.java +++ b/exceptions/Switch.java @@ -1,5 +1,5 @@ // exceptions/Switch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -14,8 +14,7 @@ public void off() { state = false; System.out.println(this); } - @Override - public String toString() { + @Override public String toString() { return state ? "on" : "off"; } } diff --git a/exceptions/TryAnything.java b/exceptions/TryAnything.java index 88e78a898..faa446cd3 100644 --- a/exceptions/TryAnything.java +++ b/exceptions/TryAnything.java @@ -1,5 +1,5 @@ // exceptions/TryAnything.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/exceptions/TryWithResources.java b/exceptions/TryWithResources.java index daf97a55a..a82d261c3 100644 --- a/exceptions/TryWithResources.java +++ b/exceptions/TryWithResources.java @@ -1,5 +1,5 @@ // exceptions/TryWithResources.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; @@ -13,7 +13,7 @@ public static void main(String[] args) { int contents = in.read(); // Process contents } catch(IOException e) { - // Handle the error + // Handle errors } } } diff --git a/exceptions/TurnOffChecking.java b/exceptions/TurnOffChecking.java index 8412b5c8a..63e67ae7e 100644 --- a/exceptions/TurnOffChecking.java +++ b/exceptions/TurnOffChecking.java @@ -1,5 +1,5 @@ // exceptions/TurnOffChecking.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // "Turning off" Checked exceptions diff --git a/exceptions/WhoCalled.java b/exceptions/WhoCalled.java index 8e5f611c3..9bdfb5abf 100644 --- a/exceptions/WhoCalled.java +++ b/exceptions/WhoCalled.java @@ -1,5 +1,5 @@ // exceptions/WhoCalled.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Programmatic access to stack trace information diff --git a/exceptions/WithFinally.java b/exceptions/WithFinally.java index fc893d6e7..d392d6be8 100644 --- a/exceptions/WithFinally.java +++ b/exceptions/WithFinally.java @@ -1,5 +1,5 @@ // exceptions/WithFinally.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Finally Guarantees cleanup diff --git a/files/AddAndSubtractPaths.java b/files/AddAndSubtractPaths.java index c13121bab..06409c9c8 100644 --- a/files/AddAndSubtractPaths.java +++ b/files/AddAndSubtractPaths.java @@ -1,5 +1,5 @@ // files/AddAndSubtractPaths.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; @@ -53,35 +53,29 @@ public static void main(String[] args) { } /* Output: Windows 10 -C:\Users\Bruce\Documents\GitHub -(1)r on- -java\ExtractedExamples\files\AddAndSubtractPaths.java -RealPath: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files\AddAndSubtractPaths.java -(2)r on-java\ExtractedExamples\strings\..\files -RealPath: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files -(3)r on-java\ExtractedExamples\files -RealPath: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files +C:\Git +(1)r OnJava8\ExtractedExamples\files\AddAndSubtractPaths.java +RealPath: +C:\Git\OnJava8\ExtractedExamples\files\AddAndSubtractPaths.java +(2)r OnJava8\ExtractedExamples\files +RealPath: C:\Git\OnJava8\ExtractedExamples\files +(3)r OnJava8\ExtractedExamples\files +RealPath: C:\Git\OnJava8\ExtractedExamples\files (4) ..\.. -RealPath: C:\Users\Bruce\Documents\GitHub\on-java +RealPath: C:\Git\OnJava8 (5) ..\.. -RealPath: C:\Users\Bruce\Documents\GitHub\on-java -(6)r on-java -RealPath: C:\Users\Bruce\Documents\GitHub\on-java -(7)r on-java\ExtractedExamples\files\.\..\.. -RealPath: C:\Users\Bruce\Documents\GitHub\on-java -(8)r on-java -RealPath: C:\Users\Bruce\Documents\GitHub\on-java -(9)r on-java\ExtractedExamples\files -RealPath: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files -(10)r on-java\ExtractedExamples\strings -RealPath: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\strings +RealPath: C:\Git\OnJava8 +(6)r OnJava8 +RealPath: C:\Git\OnJava8 +(7)r OnJava8 +RealPath: C:\Git\OnJava8 +(8)r OnJava8 +RealPath: C:\Git\OnJava8 +(9)r OnJava8\ExtractedExamples\files +RealPath: C:\Git\OnJava8\ExtractedExamples\files +(10)r OnJava8\ExtractedExamples\strings +RealPath: C:\Git\OnJava8\ExtractedExamples\strings (11) nonexistent java.nio.file.NoSuchFileException: -C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files\nonexistent +C:\Git\OnJava8\ExtractedExamples\files\nonexistent */ diff --git a/files/Directories.java b/files/Directories.java index fe41a2321..ffce7ecab 100644 --- a/files/Directories.java +++ b/files/Directories.java @@ -1,5 +1,5 @@ // files/Directories.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -59,7 +59,7 @@ static void populateTestDir() throws Exception { test\bag test\bar test\baz -test\DIR_5142667942049986036 +test\DIR_8683707748599240459 test\foo test\Hello.txt ********* @@ -68,27 +68,27 @@ static void populateTestDir() throws Exception { test\bag\foo test\bag\foo\bar test\bag\foo\bar\baz -test\bag\foo\bar\baz\8279660869874696036.tmp +test\bag\foo\bar\baz\4316127347949967230.tmp test\bag\foo\bar\baz\File.txt test\bar test\bar\baz test\bar\baz\bag test\bar\baz\bag\foo -test\bar\baz\bag\foo\1274043134240426261.tmp +test\bar\baz\bag\foo\1223263495976065729.tmp test\bar\baz\bag\foo\File.txt test\baz test\baz\bag test\baz\bag\foo test\baz\bag\foo\bar -test\baz\bag\foo\bar\6130572530014544105.tmp +test\baz\bag\foo\bar\6666183168609095028.tmp test\baz\bag\foo\bar\File.txt -test\DIR_5142667942049986036 -test\DIR_5142667942049986036\pre7704286843227113253.non +test\DIR_8683707748599240459 +test\DIR_8683707748599240459\pre6366626804787365549.non test\foo test\foo\bar test\foo\bar\baz test\foo\bar\baz\bag -test\foo\bar\baz\bag\5412864507741775436.tmp +test\foo\bar\baz\bag\4712324129011589115.tmp test\foo\bar\baz\bag\File.txt test\Hello.txt */ diff --git a/files/FileSystemDemo.java b/files/FileSystemDemo.java index 883c7537e..51f47cabd 100644 --- a/files/FileSystemDemo.java +++ b/files/FileSystemDemo.java @@ -1,5 +1,5 @@ // files/FileSystemDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; @@ -27,15 +27,21 @@ public static void main(String[] args) { } /* Output: Windows 10 -File Store: SSD (C:) +File Store: (C:) +File Store: System Reserved (E:) +File Store: (F:) +File Store: Google Drive (G:) Root Directory: C:\ Root Directory: D:\ +Root Directory: E:\ +Root Directory: F:\ +Root Directory: G:\ Separator: \ UserPrincipalLookupService: -sun.nio.fs.WindowsFileSystem$LookupService$1@15db9742 +sun.nio.fs.WindowsFileSystem$LookupService$1@1bd4fdd isOpen: true isReadOnly: false FileSystemProvider: -sun.nio.fs.WindowsFileSystemProvider@6d06d69c +sun.nio.fs.WindowsFileSystemProvider@55183b20 File Attribute Views: [owner, dos, acl, basic, user] */ diff --git a/files/Find.java b/files/Find.java index c9bafd0bc..d27c69ed7 100644 --- a/files/Find.java +++ b/files/Find.java @@ -1,5 +1,5 @@ // files/Find.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromGradle} diff --git a/files/ListOfLines.java b/files/ListOfLines.java index 0e948545b..ef1a7c4ec 100644 --- a/files/ListOfLines.java +++ b/files/ListOfLines.java @@ -1,5 +1,5 @@ // files/ListOfLines.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/files/PartsOfPaths.java b/files/PartsOfPaths.java index 9f27e035c..63a581e52 100644 --- a/files/PartsOfPaths.java +++ b/files/PartsOfPaths.java @@ -1,5 +1,5 @@ // files/PartsOfPaths.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; @@ -24,20 +24,14 @@ public static void main(String[] args) { } /* Output: Windows 10 -Users -Bruce -Documents -GitHub -on-java +Git +OnJava8 ExtractedExamples files PartsOfPaths.java ends with '.java': false -Users: false : false -Bruce: false : false -Documents: false : false -GitHub: false : false -on-java: false : false +Git: false : false +OnJava8: false : false ExtractedExamples: false : false files: false : false PartsOfPaths.java: false : true diff --git a/files/PathAnalysis.java b/files/PathAnalysis.java index fc617639a..9800ed2c5 100644 --- a/files/PathAnalysis.java +++ b/files/PathAnalysis.java @@ -1,5 +1,5 @@ // files/PathAnalysis.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; @@ -47,10 +47,10 @@ static void say(String id, Object result) { Writable: true notExists: false Hidden: false -size: 1631 -FileStore: SSD (C:) -LastModified: : 2017-05-09T12:07:00.428366Z -Owner: MINDVIEWTOSHIBA\Bruce (User) -ContentType: null +size: 1617 +FileStore: (C:) +LastModified: : 2021-11-08T00:34:52.693768Z +Owner: GROOT\Bruce (User) +ContentType: text/plain SymbolicLink: false */ diff --git a/files/PathInfo.java b/files/PathInfo.java index d963ee294..78ef9e48b 100644 --- a/files/PathInfo.java +++ b/files/PathInfo.java @@ -1,5 +1,5 @@ // files/PathInfo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; @@ -9,17 +9,17 @@ public class PathInfo { static void show(String id, Object p) { - System.out.println(id + ": " + p); + System.out.println(id + p); } static void info(Path p) { - show("toString", p); - show("Exists", Files.exists(p)); - show("RegularFile", Files.isRegularFile(p)); - show("Directory", Files.isDirectory(p)); - show("Absolute", p.isAbsolute()); - show("FileName", p.getFileName()); - show("Parent", p.getParent()); - show("Root", p.getRoot()); + show("toString:\n ", p); + show("Exists: ", Files.exists(p)); + show("RegularFile: ", Files.isRegularFile(p)); + show("Directory: ", Files.isDirectory(p)); + show("Absolute: ", p.isAbsolute()); + show("FileName: ", p.getFileName()); + show("Parent: ", p.getParent()); + show("Root: ", p.getRoot()); System.out.println("******************"); } public static void main(String[] args) { @@ -37,7 +37,7 @@ public static void main(String[] args) { System.out.println(e); } URI u = p.toUri(); - System.out.println("URI: " + u); + System.out.println("URI:\n" + u); Path puri = Paths.get(u); System.out.println(Files.exists(puri)); File f = ap.toFile(); // Don't be fooled @@ -45,7 +45,8 @@ public static void main(String[] args) { } /* Output: Windows 10 -toString: C:\path\to\nowhere\NoFile.txt +toString: + C:\path\to\nowhere\NoFile.txt Exists: false RegularFile: false Directory: false @@ -54,7 +55,8 @@ public static void main(String[] args) { Parent: C:\path\to\nowhere Root: C:\ ****************** -toString: PathInfo.java +toString: + PathInfo.java Exists: true RegularFile: true Directory: false @@ -63,40 +65,37 @@ public static void main(String[] args) { Parent: null Root: null ****************** -toString: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files\PathInfo.java +toString: + C:\Git\OnJava8\ExtractedExamples\files\PathInfo.java Exists: true RegularFile: true Directory: false Absolute: true FileName: PathInfo.java -Parent: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files +Parent: C:\Git\OnJava8\ExtractedExamples\files Root: C:\ ****************** -toString: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files +toString: + C:\Git\OnJava8\ExtractedExamples\files Exists: true RegularFile: false Directory: true Absolute: true FileName: files -Parent: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples +Parent: C:\Git\OnJava8\ExtractedExamples Root: C:\ ****************** -toString: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files\PathInfo.java +toString: + C:\Git\OnJava8\ExtractedExamples\files\PathInfo.java Exists: true RegularFile: true Directory: false Absolute: true FileName: PathInfo.java -Parent: C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\files +Parent: C:\Git\OnJava8\ExtractedExamples\files Root: C:\ ****************** -URI: file:///C:/Users/Bruce/Documents/GitHub/on- -java/ExtractedExamples/files/PathInfo.java +URI: +file:///C:/Git/OnJava8/ExtractedExamples/files/PathInfo.java true */ diff --git a/files/PathWatcher.java b/files/PathWatcher.java index d880219ae..8a1f46107 100644 --- a/files/PathWatcher.java +++ b/files/PathWatcher.java @@ -1,5 +1,5 @@ // files/PathWatcher.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromGradle} diff --git a/files/ReadLineStream.java b/files/ReadLineStream.java index 1409fbee1..812ed1058 100644 --- a/files/ReadLineStream.java +++ b/files/ReadLineStream.java @@ -1,5 +1,5 @@ // files/ReadLineStream.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; diff --git a/files/StreamInAndOut.java b/files/StreamInAndOut.java index 74a721e9b..4f7297d55 100644 --- a/files/StreamInAndOut.java +++ b/files/StreamInAndOut.java @@ -1,5 +1,5 @@ // files/StreamInAndOut.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/files/TreeWatcher.java b/files/TreeWatcher.java index ea36be3fb..1162ff807 100644 --- a/files/TreeWatcher.java +++ b/files/TreeWatcher.java @@ -1,5 +1,5 @@ // files/TreeWatcher.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromGradle} diff --git a/files/Writing.java b/files/Writing.java index a72816700..82745e4d5 100644 --- a/files/Writing.java +++ b/files/Writing.java @@ -1,5 +1,5 @@ // files/Writing.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/functional/AnonymousClosure.java b/functional/AnonymousClosure.java index 92c232c74..6faa0925e 100644 --- a/functional/AnonymousClosure.java +++ b/functional/AnonymousClosure.java @@ -1,5 +1,5 @@ // functional/AnonymousClosure.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/BiConsumerPermutations.java b/functional/BiConsumerPermutations.java index 90e2f3dc4..091967fb1 100644 --- a/functional/BiConsumerPermutations.java +++ b/functional/BiConsumerPermutations.java @@ -1,5 +1,5 @@ // functional/BiConsumerPermutations.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/ClassFunctionals.java b/functional/ClassFunctionals.java index 06d43a236..eb7548229 100644 --- a/functional/ClassFunctionals.java +++ b/functional/ClassFunctionals.java @@ -1,5 +1,5 @@ // functional/ClassFunctionals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/functional/Closure1.java b/functional/Closure1.java index f0dfdf060..90bd9671d 100644 --- a/functional/Closure1.java +++ b/functional/Closure1.java @@ -1,5 +1,5 @@ // functional/Closure1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/Closure2.java b/functional/Closure2.java index f42c77342..86129103d 100644 --- a/functional/Closure2.java +++ b/functional/Closure2.java @@ -1,5 +1,5 @@ // functional/Closure2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/Closure3.java b/functional/Closure3.java index 4719f90cf..40728b5f3 100644 --- a/functional/Closure3.java +++ b/functional/Closure3.java @@ -1,5 +1,5 @@ // functional/Closure3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/functional/Closure4.java b/functional/Closure4.java index 947417607..06f34afbf 100644 --- a/functional/Closure4.java +++ b/functional/Closure4.java @@ -1,5 +1,5 @@ // functional/Closure4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/Closure5.java b/functional/Closure5.java index ad98bad24..dcd7a08f4 100644 --- a/functional/Closure5.java +++ b/functional/Closure5.java @@ -1,5 +1,5 @@ // functional/Closure5.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/functional/Closure6.java b/functional/Closure6.java index 459dc6c8c..b102a67af 100644 --- a/functional/Closure6.java +++ b/functional/Closure6.java @@ -1,5 +1,5 @@ // functional/Closure6.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/Closure7.java b/functional/Closure7.java index 5dc34986d..098685296 100644 --- a/functional/Closure7.java +++ b/functional/Closure7.java @@ -1,5 +1,5 @@ // functional/Closure7.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/functional/Closure8.java b/functional/Closure8.java index 70ed1e248..8cfa1041b 100644 --- a/functional/Closure8.java +++ b/functional/Closure8.java @@ -1,5 +1,5 @@ // functional/Closure8.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/functional/Closure9.java b/functional/Closure9.java index af3cb8f4b..4679e474e 100644 --- a/functional/Closure9.java +++ b/functional/Closure9.java @@ -1,5 +1,5 @@ // functional/Closure9.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/functional/ConsumeFunction.java b/functional/ConsumeFunction.java index bbab0aa0d..328bd9fcf 100644 --- a/functional/ConsumeFunction.java +++ b/functional/ConsumeFunction.java @@ -1,5 +1,5 @@ // functional/ConsumeFunction.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/CtorReference.java b/functional/CtorReference.java index 0ea701774..ec74b00f7 100644 --- a/functional/CtorReference.java +++ b/functional/CtorReference.java @@ -1,5 +1,5 @@ // functional/CtorReference.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -25,9 +25,9 @@ interface Make2Args { public class CtorReference { public static void main(String[] args) { - MakeNoArgs mna = Dog::new; // [1] - Make1Arg m1a = Dog::new; // [2] - Make2Args m2a = Dog::new; // [3] + MakeNoArgs mna = Dog::new; // [1] + Make1Arg m1a = Dog::new; // [2] + Make2Args m2a = Dog::new; // [3] Dog dn = mna.make(); Dog d1 = m1a.make("Comet"); diff --git a/functional/CurriedIntAdd.java b/functional/CurriedIntAdd.java index 7b89d59cb..6c430f70e 100644 --- a/functional/CurriedIntAdd.java +++ b/functional/CurriedIntAdd.java @@ -1,5 +1,5 @@ // functional/CurriedIntAdd.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/Curry3Args.java b/functional/Curry3Args.java index e27fd0adb..5a307480f 100644 --- a/functional/Curry3Args.java +++ b/functional/Curry3Args.java @@ -1,5 +1,5 @@ // functional/Curry3Args.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/CurryingAndPartials.java b/functional/CurryingAndPartials.java index 795a1afda..d92912a72 100644 --- a/functional/CurryingAndPartials.java +++ b/functional/CurryingAndPartials.java @@ -1,5 +1,5 @@ // functional/CurryingAndPartials.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; @@ -12,12 +12,12 @@ static String uncurried(String a, String b) { public static void main(String[] args) { // Curried function: Function> sum = - a -> b -> a + b; // [1] + a -> b -> a + b; // [1] System.out.println(uncurried("Hi ", "Ho")); Function - hi = sum.apply("Hi "); // [2] + hi = sum.apply("Hi "); // [2] System.out.println(hi.apply("Ho")); // Partial application: diff --git a/functional/FunctionComposition.java b/functional/FunctionComposition.java index 74a66ddd4..f20b115ca 100644 --- a/functional/FunctionComposition.java +++ b/functional/FunctionComposition.java @@ -1,5 +1,5 @@ // functional/FunctionComposition.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/FunctionVariants.java b/functional/FunctionVariants.java index d09476ca6..0c4b42484 100644 --- a/functional/FunctionVariants.java +++ b/functional/FunctionVariants.java @@ -1,5 +1,5 @@ // functional/FunctionVariants.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/FunctionWithWrapped.java b/functional/FunctionWithWrapped.java index 99dd8743b..253f8820c 100644 --- a/functional/FunctionWithWrapped.java +++ b/functional/FunctionWithWrapped.java @@ -1,5 +1,5 @@ // functional/FunctionWithWrapped.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/FunctionalAnnotation.java b/functional/FunctionalAnnotation.java index 0116d87b6..29cc33056 100644 --- a/functional/FunctionalAnnotation.java +++ b/functional/FunctionalAnnotation.java @@ -1,5 +1,5 @@ // functional/FunctionalAnnotation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/functional/IntCall.java b/functional/IntCall.java index 73b985803..910c2ac35 100644 --- a/functional/IntCall.java +++ b/functional/IntCall.java @@ -1,5 +1,5 @@ // functional/IntCall.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/functional/LambdaExpressions.java b/functional/LambdaExpressions.java index 3f2b3f734..3c4a40b03 100644 --- a/functional/LambdaExpressions.java +++ b/functional/LambdaExpressions.java @@ -1,5 +1,5 @@ // functional/LambdaExpressions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -17,15 +17,15 @@ interface Multi { public class LambdaExpressions { - static Body bod = h -> h + " No Parens!"; // [1] + static Body bod = h -> h + " No Parens!"; // [1] static Body bod2 = (h) -> h + " More details"; // [2] - static Description desc = () -> "Short info"; // [3] + static Description desc = () -> "Short info"; // [3] - static Multi mult = (h, n) -> h + n; // [4] + static Multi mult = (h, n) -> h + n; // [4] - static Description moreLines = () -> { // [5] + static Description moreLines = () -> { // [5] System.out.println("moreLines()"); return "from moreLines()"; }; diff --git a/functional/MethodConversion.java b/functional/MethodConversion.java index 184f01b38..15e780749 100644 --- a/functional/MethodConversion.java +++ b/functional/MethodConversion.java @@ -1,5 +1,5 @@ // functional/MethodConversion.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/MethodReferences.java b/functional/MethodReferences.java index dde6ba0e0..4c1e5f9fb 100644 --- a/functional/MethodReferences.java +++ b/functional/MethodReferences.java @@ -1,47 +1,46 @@ // functional/MethodReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import java.util.*; -interface Callable { // [1] +interface Callable { // [1] void call(String s); } class Describe { - void show(String msg) { // [2] + void show(String msg) { // [2] System.out.println(msg); } } public class MethodReferences { - static void hello(String name) { // [3] + static void hello(String name) { // [3] System.out.println("Hello, " + name); } static class Description { String about; Description(String desc) { about = desc; } - void help(String msg) { // [4] + void help(String msg) { // [4] System.out.println(about + " " + msg); } } static class Helper { - static void assist(String msg) { // [5] + static void assist(String msg) { // [5] System.out.println(msg); } } public static void main(String[] args) { Describe d = new Describe(); - Callable c = d::show; // [6] - c.call("call()"); // [7] + Callable c = d::show; // [6] + c.call("call()"); // [7] - c = MethodReferences::hello; // [8] + c = MethodReferences::hello; // [8] c.call("Bob"); - c = new Description("valuable")::help; // [9] + c = new Description("valuable")::help; // [9] c.call("information"); - c = Helper::assist; // [10] + c = Helper::assist; // [10] c.call("Help!"); } } diff --git a/functional/MultiUnbound.java b/functional/MultiUnbound.java index ce50b2f4d..67defb7d5 100644 --- a/functional/MultiUnbound.java +++ b/functional/MultiUnbound.java @@ -1,5 +1,5 @@ // functional/MultiUnbound.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Unbound methods with multiple arguments diff --git a/functional/PredicateComposition.java b/functional/PredicateComposition.java index 5ebe4e77d..40ddb6001 100644 --- a/functional/PredicateComposition.java +++ b/functional/PredicateComposition.java @@ -1,5 +1,5 @@ // functional/PredicateComposition.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/ProduceFunction.java b/functional/ProduceFunction.java index 6682be9d9..5f0b0940b 100644 --- a/functional/ProduceFunction.java +++ b/functional/ProduceFunction.java @@ -1,15 +1,15 @@ // functional/ProduceFunction.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; interface -FuncSS extends Function {} // [1] +FuncSS extends Function {} // [1] public class ProduceFunction { static FuncSS produce() { - return s -> s.toLowerCase(); // [2] + return s -> s.toLowerCase(); // [2] } public static void main(String[] args) { FuncSS f = produce(); diff --git a/functional/RecursiveFactorial.java b/functional/RecursiveFactorial.java index 0a32d3346..5ddb0860c 100644 --- a/functional/RecursiveFactorial.java +++ b/functional/RecursiveFactorial.java @@ -1,5 +1,5 @@ // functional/RecursiveFactorial.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/functional/RecursiveFibonacci.java b/functional/RecursiveFibonacci.java index 8cb2c7d24..4b58bb06c 100644 --- a/functional/RecursiveFibonacci.java +++ b/functional/RecursiveFibonacci.java @@ -1,5 +1,5 @@ // functional/RecursiveFibonacci.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/functional/RunnableMethodReference.java b/functional/RunnableMethodReference.java index 92f2e2906..e135d06f6 100644 --- a/functional/RunnableMethodReference.java +++ b/functional/RunnableMethodReference.java @@ -1,5 +1,5 @@ // functional/RunnableMethodReference.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Method references with interface Runnable diff --git a/functional/SharedStorage.java b/functional/SharedStorage.java index 20da6917b..0a2489253 100644 --- a/functional/SharedStorage.java +++ b/functional/SharedStorage.java @@ -1,5 +1,5 @@ // functional/SharedStorage.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/functional/Strategize.java b/functional/Strategize.java index c101fd1d3..b4358ee7e 100644 --- a/functional/Strategize.java +++ b/functional/Strategize.java @@ -1,5 +1,5 @@ // functional/Strategize.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -8,6 +8,7 @@ interface Strategy { } class Soft implements Strategy { + @Override public String approach(String msg) { return msg.toLowerCase() + "?"; } @@ -23,7 +24,7 @@ public class Strategize { Strategy strategy; String msg; Strategize(String msg) { - strategy = new Soft(); // [1] + strategy = new Soft(); // [1] this.msg = msg; } void communicate() { @@ -34,19 +35,19 @@ void changeStrategy(Strategy strategy) { } public static void main(String[] args) { Strategy[] strategies = { - new Strategy() { // [2] + new Strategy() { // [2] public String approach(String msg) { return msg.toUpperCase() + "!"; } }, - msg -> msg.substring(0, 5), // [3] - Unrelated::twice // [4] + msg -> msg.substring(0, 5), // [3] + Unrelated::twice // [4] }; Strategize s = new Strategize("Hello there"); s.communicate(); for(Strategy newStrategy : strategies) { - s.changeStrategy(newStrategy); // [5] - s.communicate(); // [6] + s.changeStrategy(newStrategy); // [5] + s.communicate(); // [6] } } } diff --git a/functional/TransformFunction.java b/functional/TransformFunction.java index 8a8c4928d..dd3f7590b 100644 --- a/functional/TransformFunction.java +++ b/functional/TransformFunction.java @@ -1,17 +1,15 @@ // functional/TransformFunction.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; class I { - @Override - public String toString() { return "I"; } + @Override public String toString() { return "I"; } } class O { - @Override - public String toString() { return "O"; } + @Override public String toString() { return "O"; } } public class TransformFunction { diff --git a/functional/TriFunction.java b/functional/TriFunction.java index 47895dc95..40b91473a 100644 --- a/functional/TriFunction.java +++ b/functional/TriFunction.java @@ -1,5 +1,5 @@ // functional/TriFunction.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/functional/TriFunctionTest.java b/functional/TriFunctionTest.java index f87b4421e..5af98922c 100644 --- a/functional/TriFunctionTest.java +++ b/functional/TriFunctionTest.java @@ -1,5 +1,5 @@ // functional/TriFunctionTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/functional/UnboundMethodReference.java b/functional/UnboundMethodReference.java index 88c9d3d33..6c02b8b91 100644 --- a/functional/UnboundMethodReference.java +++ b/functional/UnboundMethodReference.java @@ -1,5 +1,5 @@ // functional/UnboundMethodReference.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Method reference without an object @@ -18,10 +18,10 @@ interface TransformX { public class UnboundMethodReference { public static void main(String[] args) { - // MakeString ms = X::f; // [1] + // MakeString ms = X::f; // [1] TransformX sp = X::f; X x = new X(); - System.out.println(sp.transform(x)); // [2] + System.out.println(sp.transform(x)); // [2] System.out.println(x.f()); // Same effect } } diff --git a/generics/Amphibian.java b/generics/Amphibian.java index fbff20b56..0dc8647f5 100644 --- a/generics/Amphibian.java +++ b/generics/Amphibian.java @@ -1,5 +1,5 @@ // generics/Amphibian.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Amphibian {} diff --git a/generics/Apply.java b/generics/Apply.java index d1923a279..8e3a23c97 100644 --- a/generics/Apply.java +++ b/generics/Apply.java @@ -1,5 +1,5 @@ // generics/Apply.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.reflect.*; diff --git a/generics/ApplyFunctional.java b/generics/ApplyFunctional.java index 2dd8aa1c8..2275ca854 100644 --- a/generics/ApplyFunctional.java +++ b/generics/ApplyFunctional.java @@ -1,5 +1,5 @@ // generics/ApplyFunctional.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/ApplyTest.java b/generics/ApplyTest.java index ea50a98bd..2ae0618d4 100644 --- a/generics/ApplyTest.java +++ b/generics/ApplyTest.java @@ -1,5 +1,5 @@ // generics/ApplyTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/ArrayMaker.java b/generics/ArrayMaker.java index 9b495d4e4..b728267cd 100644 --- a/generics/ArrayMaker.java +++ b/generics/ArrayMaker.java @@ -1,5 +1,5 @@ // generics/ArrayMaker.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.reflect.*; diff --git a/generics/ArrayOfGeneric.java b/generics/ArrayOfGeneric.java index 210d01368..68f7a5bdf 100644 --- a/generics/ArrayOfGeneric.java +++ b/generics/ArrayOfGeneric.java @@ -1,5 +1,5 @@ // generics/ArrayOfGeneric.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/ArrayOfGenericReference.java b/generics/ArrayOfGenericReference.java index a1484e2f9..3403e3c50 100644 --- a/generics/ArrayOfGenericReference.java +++ b/generics/ArrayOfGenericReference.java @@ -1,5 +1,5 @@ // generics/ArrayOfGenericReference.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/BankTeller.java b/generics/BankTeller.java index c0116a6ae..51bb12034 100644 --- a/generics/BankTeller.java +++ b/generics/BankTeller.java @@ -1,5 +1,5 @@ // generics/BankTeller.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A very simple bank teller simulation @@ -9,8 +9,7 @@ class Customer { private static long counter = 1; private final long id = counter++; - @Override - public String toString() { + @Override public String toString() { return "Customer " + id; } } @@ -18,8 +17,7 @@ public String toString() { class Teller { private static long counter = 1; private final long id = counter++; - @Override - public String toString() { + @Override public String toString() { return "Teller " + id; } } diff --git a/generics/BasicBounds.java b/generics/BasicBounds.java index 321e571e0..ca2c00dfa 100644 --- a/generics/BasicBounds.java +++ b/generics/BasicBounds.java @@ -1,5 +1,5 @@ // generics/BasicBounds.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -48,8 +48,7 @@ class Bounded extends Coord implements HasColor, Weight { @Override public java.awt.Color getColor() { return null; } - @Override - public int weight() { return 0; } + @Override public int weight() { return 0; } } public class BasicBounds { diff --git a/generics/BasicHolder.java b/generics/BasicHolder.java index 8d8838391..5a6bc5a4e 100644 --- a/generics/BasicHolder.java +++ b/generics/BasicHolder.java @@ -1,5 +1,5 @@ // generics/BasicHolder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/BasicSupplierDemo.java b/generics/BasicSupplierDemo.java index 1d34c2337..bf754154a 100644 --- a/generics/BasicSupplierDemo.java +++ b/generics/BasicSupplierDemo.java @@ -1,5 +1,5 @@ // generics/BasicSupplierDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/generics/ByteSet.java b/generics/ByteSet.java index ae1a2573b..860125b6a 100644 --- a/generics/ByteSet.java +++ b/generics/ByteSet.java @@ -1,5 +1,5 @@ // generics/ByteSet.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/CRGWithBasicHolder.java b/generics/CRGWithBasicHolder.java index 4db0784a3..f30f02da7 100644 --- a/generics/CRGWithBasicHolder.java +++ b/generics/CRGWithBasicHolder.java @@ -1,5 +1,5 @@ // generics/CRGWithBasicHolder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/CaptureConversion.java b/generics/CaptureConversion.java index 190140008..831ee7e94 100644 --- a/generics/CaptureConversion.java +++ b/generics/CaptureConversion.java @@ -1,5 +1,5 @@ // generics/CaptureConversion.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/CheckedList.java b/generics/CheckedList.java index b18abf2ee..71ebe3d0a 100644 --- a/generics/CheckedList.java +++ b/generics/CheckedList.java @@ -1,9 +1,9 @@ // generics/CheckedList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using Collection.checkedList() -import typeinfo.pets.*; +import reflection.pets.*; import java.util.*; public class CheckedList { @@ -30,6 +30,6 @@ public static void main(String[] args) { } /* Output: Expected: java.lang.ClassCastException: Attempt to -insert class typeinfo.pets.Cat element into collection -with element type class typeinfo.pets.Dog +insert class reflection.pets.Cat element into collection +with element type class reflection.pets.Dog */ diff --git a/generics/ClassCasting.java b/generics/ClassCasting.java index 714e9610b..9029b298e 100644 --- a/generics/ClassCasting.java +++ b/generics/ClassCasting.java @@ -1,5 +1,5 @@ // generics/ClassCasting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/generics/ClassTypeCapture.java b/generics/ClassTypeCapture.java index d98210c2c..cd4cb8375 100644 --- a/generics/ClassTypeCapture.java +++ b/generics/ClassTypeCapture.java @@ -1,5 +1,5 @@ // generics/ClassTypeCapture.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/ComparablePet.java b/generics/ComparablePet.java index 356cc6472..951b6cc15 100644 --- a/generics/ComparablePet.java +++ b/generics/ComparablePet.java @@ -1,5 +1,5 @@ // generics/ComparablePet.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/CompilerIntelligence.java b/generics/CompilerIntelligence.java index 437b44e14..6b1bc4155 100644 --- a/generics/CompilerIntelligence.java +++ b/generics/CompilerIntelligence.java @@ -1,5 +1,5 @@ // generics/CompilerIntelligence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/CountedObject.java b/generics/CountedObject.java index 81777402d..287b480fb 100644 --- a/generics/CountedObject.java +++ b/generics/CountedObject.java @@ -1,5 +1,5 @@ // generics/CountedObject.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -7,8 +7,7 @@ public class CountedObject { private static long counter = 0; private final long id = counter++; public long id() { return id; } - @Override - public String toString() { + @Override public String toString() { return "CountedObject " + id; } } diff --git a/generics/CovariantArrays.java b/generics/CovariantArrays.java index 3d30a4202..2a56b631e 100644 --- a/generics/CovariantArrays.java +++ b/generics/CovariantArrays.java @@ -1,5 +1,5 @@ // generics/CovariantArrays.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/CovariantReturnTypes.java b/generics/CovariantReturnTypes.java index 5a1c4797e..870f21e4f 100644 --- a/generics/CovariantReturnTypes.java +++ b/generics/CovariantReturnTypes.java @@ -1,5 +1,5 @@ // generics/CovariantReturnTypes.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -12,8 +12,7 @@ interface OrdinaryGetter { interface DerivedGetter extends OrdinaryGetter { // Overridden method return type can vary: - @Override - Derived get(); + @Override Derived get(); } public class CovariantReturnTypes { diff --git a/generics/CreatorGeneric.java b/generics/CreatorGeneric.java index 98bf7c161..e9a349740 100644 --- a/generics/CreatorGeneric.java +++ b/generics/CreatorGeneric.java @@ -1,5 +1,5 @@ // generics/CreatorGeneric.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -12,8 +12,7 @@ abstract class GenericWithCreate { class X {} class XCreator extends GenericWithCreate { - @Override - X create() { return new X(); } + @Override X create() { return new X(); } void f() { System.out.println( element.getClass().getSimpleName()); diff --git a/generics/CuriouslyRecurringGeneric.java b/generics/CuriouslyRecurringGeneric.java index 1d3a69cd1..53977f27b 100644 --- a/generics/CuriouslyRecurringGeneric.java +++ b/generics/CuriouslyRecurringGeneric.java @@ -1,5 +1,5 @@ // generics/CuriouslyRecurringGeneric.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/Diamond.java b/generics/Diamond.java index 3af10a18b..9ebc43d37 100644 --- a/generics/Diamond.java +++ b/generics/Diamond.java @@ -1,13 +1,11 @@ // generics/Diamond.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -class Bob {} - public class Diamond { public static void main(String[] args) { - GenericHolder h3 = new GenericHolder<>(); - h3.set(new Bob()); + GenericHolder h3 = + new GenericHolder<>(); } } diff --git a/generics/DogsAndRobotMethodReferences.java b/generics/DogsAndRobotMethodReferences.java index 81b2c078f..2e9d003e5 100644 --- a/generics/DogsAndRobotMethodReferences.java +++ b/generics/DogsAndRobotMethodReferences.java @@ -1,9 +1,9 @@ // generics/DogsAndRobotMethodReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // "Assisted Latent Typing" -import typeinfo.pets.*; +import reflection.pets.*; import java.util.function.*; class PerformingDogA extends Dog { diff --git a/generics/DogsAndRobots.cpp b/generics/DogsAndRobots.cpp index 212893a6d..a8b008f23 100644 --- a/generics/DogsAndRobots.cpp +++ b/generics/DogsAndRobots.cpp @@ -1,5 +1,5 @@ // generics/DogsAndRobots.cpp -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. #include diff --git a/generics/DogsAndRobots.java b/generics/DogsAndRobots.java index 95ee18a30..228e363d3 100644 --- a/generics/DogsAndRobots.java +++ b/generics/DogsAndRobots.java @@ -1,9 +1,9 @@ // generics/DogsAndRobots.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // No (direct) latent typing in Java -import typeinfo.pets.*; +import reflection.pets.*; class PerformingDog extends Dog implements Performs { @Override @@ -14,7 +14,9 @@ public void reproduce() {} } class Robot implements Performs { + @Override public void speak() { System.out.println("Click!"); } + @Override public void sit() { System.out.println("Clank!"); } public void oilChange() {} } diff --git a/generics/DogsAndRobots.py b/generics/DogsAndRobots.py index d09b24139..ed3bfd47d 100644 --- a/generics/DogsAndRobots.py +++ b/generics/DogsAndRobots.py @@ -1,5 +1,5 @@ # generics/DogsAndRobots.py -# (c)2017 MindView LLC: see Copyright.txt +# (c)2021 MindView LLC: see Copyright.txt # We make no guarantees that this code is fit for any purpose. # Visit http://OnJava8.com for more book information. diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index 5aaf96b7d..906278fba 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -1,5 +1,5 @@ // generics/DynamicProxyMixin.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.reflect.*; @@ -44,6 +44,7 @@ public static Object newInstance(Tuple2... pairs) { public class DynamicProxyMixin { public static void main(String[] args) { + @SuppressWarnings("unchecked") Object mixin = MixinProxy.newInstance( tuple(new BasicImp(), Basic.class), tuple(new TimeStampedImp(), TimeStamped.class), @@ -60,6 +61,6 @@ public static void main(String[] args) { } /* Output: Hello -1494331653339 +1611503350927 1 */ diff --git a/generics/EpicBattle.java b/generics/EpicBattle.java index f1453c9e5..716606608 100644 --- a/generics/EpicBattle.java +++ b/generics/EpicBattle.java @@ -1,5 +1,5 @@ // generics/EpicBattle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Bounds in Java generics @@ -41,10 +41,8 @@ class SuperSleuth class SuperHearSmell implements SuperHearing, SuperSmell { - @Override - public void hearSubtleNoises() {} - @Override - public void trackBySmell() {} + @Override public void hearSubtleNoises() {} + @Override public void trackBySmell() {} } class DogPerson extends CanineHero { diff --git a/generics/Erased.java b/generics/Erased.java index 0c60fbfd4..304385afb 100644 --- a/generics/Erased.java +++ b/generics/Erased.java @@ -1,5 +1,5 @@ // generics/Erased.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/generics/ErasedTypeEquivalence.java b/generics/ErasedTypeEquivalence.java index 9b3827df3..0368a1828 100644 --- a/generics/ErasedTypeEquivalence.java +++ b/generics/ErasedTypeEquivalence.java @@ -1,5 +1,5 @@ // generics/ErasedTypeEquivalence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/ErasureAndInheritance.java b/generics/ErasureAndInheritance.java index 9a723c1b5..4a2e2591c 100644 --- a/generics/ErasureAndInheritance.java +++ b/generics/ErasureAndInheritance.java @@ -1,5 +1,5 @@ // generics/ErasureAndInheritance.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/FactoryConstraint.java b/generics/FactoryConstraint.java index c2960da1d..5e721168b 100644 --- a/generics/FactoryConstraint.java +++ b/generics/FactoryConstraint.java @@ -1,5 +1,5 @@ // generics/FactoryConstraint.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -8,8 +8,7 @@ class IntegerFactory implements Supplier { private int i = 0; - @Override - public Integer get() { + @Override public Integer get() { return ++i; } } @@ -17,8 +16,7 @@ public Integer get() { class Widget { private int id; Widget(int n) { id = n; } - @Override - public String toString() { + @Override public String toString() { return "Widget " + id; } public static @@ -32,8 +30,9 @@ class Factory implements Supplier { class Fudge { private static int count = 1; private int n = count++; - @Override - public String toString() { return "Fudge " + n; } + @Override public String toString() { + return "Fudge " + n; + } } class Foo2 { @@ -41,8 +40,9 @@ class Foo2 { Foo2(Supplier factory) { Suppliers.fill(x, factory, 5); } - @Override - public String toString() { return x.toString(); } + @Override public String toString() { + return x.toString(); + } } public class FactoryConstraint { diff --git a/generics/Fibonacci.java b/generics/Fibonacci.java index 25d123589..c20bdf225 100644 --- a/generics/Fibonacci.java +++ b/generics/Fibonacci.java @@ -1,5 +1,5 @@ // generics/Fibonacci.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Generate a Fibonacci sequence diff --git a/generics/FilledList.java b/generics/FilledList.java index 064715f06..662d50f98 100644 --- a/generics/FilledList.java +++ b/generics/FilledList.java @@ -1,5 +1,5 @@ // generics/FilledList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/GenericArray.java b/generics/GenericArray.java index c272afcf1..39212feca 100644 --- a/generics/GenericArray.java +++ b/generics/GenericArray.java @@ -1,5 +1,5 @@ // generics/GenericArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/GenericArray2.java b/generics/GenericArray2.java index 50c9434d0..ee7962623 100644 --- a/generics/GenericArray2.java +++ b/generics/GenericArray2.java @@ -1,5 +1,5 @@ // generics/GenericArray2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/GenericArrayWithTypeToken.java b/generics/GenericArrayWithTypeToken.java index 41fcd124e..3005a540d 100644 --- a/generics/GenericArrayWithTypeToken.java +++ b/generics/GenericArrayWithTypeToken.java @@ -1,5 +1,5 @@ // generics/GenericArrayWithTypeToken.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.reflect.*; diff --git a/generics/GenericCast.java b/generics/GenericCast.java index ddf5deae1..eb4fb651d 100644 --- a/generics/GenericCast.java +++ b/generics/GenericCast.java @@ -1,5 +1,5 @@ // generics/GenericCast.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/GenericHolder.java b/generics/GenericHolder.java index 72cf4f2ce..15cfbb9e1 100644 --- a/generics/GenericHolder.java +++ b/generics/GenericHolder.java @@ -1,5 +1,5 @@ // generics/GenericHolder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/GenericHolder2.java b/generics/GenericHolder2.java index b71543191..59c3e3569 100644 --- a/generics/GenericHolder2.java +++ b/generics/GenericHolder2.java @@ -1,5 +1,5 @@ // generics/GenericHolder2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/GenericMethods.java b/generics/GenericMethods.java index 50db2061b..3ec451f93 100644 --- a/generics/GenericMethods.java +++ b/generics/GenericMethods.java @@ -1,5 +1,5 @@ // generics/GenericMethods.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/GenericReading.java b/generics/GenericReading.java index 2bb83cf83..a661798c5 100644 --- a/generics/GenericReading.java +++ b/generics/GenericReading.java @@ -1,5 +1,5 @@ // generics/GenericReading.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/GenericVarargs.java b/generics/GenericVarargs.java index 94f679a90..3dfca7d44 100644 --- a/generics/GenericVarargs.java +++ b/generics/GenericVarargs.java @@ -1,5 +1,5 @@ // generics/GenericVarargs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/GenericsAndCovariance.java b/generics/GenericsAndCovariance.java index 31cdc6605..023bb8763 100644 --- a/generics/GenericsAndCovariance.java +++ b/generics/GenericsAndCovariance.java @@ -1,5 +1,5 @@ // generics/GenericsAndCovariance.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/GenericsAndReturnTypes.java b/generics/GenericsAndReturnTypes.java index c64d6a18b..3eebd91ac 100644 --- a/generics/GenericsAndReturnTypes.java +++ b/generics/GenericsAndReturnTypes.java @@ -1,5 +1,5 @@ // generics/GenericsAndReturnTypes.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/HasF.java b/generics/HasF.java index 70f8c0606..436c19585 100644 --- a/generics/HasF.java +++ b/generics/HasF.java @@ -1,5 +1,5 @@ // generics/HasF.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/HijackedInterface.java b/generics/HijackedInterface.java index c417ecab2..edf01b7b2 100644 --- a/generics/HijackedInterface.java +++ b/generics/HijackedInterface.java @@ -1,5 +1,5 @@ // generics/HijackedInterface.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/generics/Holder.java b/generics/Holder.java index 0d8e85d00..50d22a3ca 100644 --- a/generics/Holder.java +++ b/generics/Holder.java @@ -1,5 +1,5 @@ // generics/Holder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.Objects; @@ -10,13 +10,11 @@ public Holder() {} public Holder(T val) { value = val; } public void set(T val) { value = val; } public T get() { return value; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof Holder && Objects.equals(value, ((Holder)o).value); } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hashCode(value); } public static void main(String[] args) { diff --git a/generics/Holder1.java b/generics/Holder1.java index dc9f7a115..7af6f1c15 100644 --- a/generics/Holder1.java +++ b/generics/Holder1.java @@ -1,5 +1,5 @@ // generics/Holder1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/InheritBounds.java b/generics/InheritBounds.java index 7f535f3b7..7bd7d22b1 100644 --- a/generics/InheritBounds.java +++ b/generics/InheritBounds.java @@ -1,5 +1,5 @@ // generics/InheritBounds.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/InstantiateGenericType.cpp b/generics/InstantiateGenericType.cpp index 6197e5c31..c260c39d5 100644 --- a/generics/InstantiateGenericType.cpp +++ b/generics/InstantiateGenericType.cpp @@ -1,5 +1,5 @@ // generics/InstantiateGenericType.cpp -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // C++, not Java! diff --git a/generics/InstantiateGenericType.java b/generics/InstantiateGenericType.java index 4c46b04ba..93c8d62a9 100644 --- a/generics/InstantiateGenericType.java +++ b/generics/InstantiateGenericType.java @@ -1,28 +1,29 @@ // generics/InstantiateGenericType.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; +import java.lang.reflect.InvocationTargetException; class ClassAsFactory implements Supplier { Class kind; ClassAsFactory(Class kind) { this.kind = kind; } - @Override - public T get() { + @Override public T get() { try { - return kind.newInstance(); - } catch(InstantiationException | - IllegalAccessException e) { + return kind.getConstructor().newInstance(); + } catch(Exception e) { throw new RuntimeException(e); } } } class Employee { - @Override - public String toString() { return "Employee"; } + public Employee() {} + @Override public String toString() { + return "Employee"; + } } public class InstantiateGenericType { @@ -41,5 +42,6 @@ public static void main(String[] args) { } /* Output: Employee -java.lang.InstantiationException: java.lang.Integer +java.lang.NoSuchMethodException: +java.lang.Integer.() */ diff --git a/generics/IterableFibonacci.java b/generics/IterableFibonacci.java index 69708eb28..2b56b102a 100644 --- a/generics/IterableFibonacci.java +++ b/generics/IterableFibonacci.java @@ -1,5 +1,5 @@ // generics/IterableFibonacci.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Adapt the Fibonacci class to make it Iterable @@ -9,13 +9,11 @@ public class IterableFibonacci extends Fibonacci implements Iterable { private int n; public IterableFibonacci(int count) { n = count; } - @Override - public Iterator iterator() { + @Override public Iterator iterator() { return new Iterator() { @Override public boolean hasNext() { return n > 0; } - @Override - public Integer next() { + @Override public Integer next() { n--; return IterableFibonacci.this.get(); } diff --git a/generics/LatentReflection.java b/generics/LatentReflection.java index 9ee02bf18..cfd9e751d 100644 --- a/generics/LatentReflection.java +++ b/generics/LatentReflection.java @@ -1,5 +1,5 @@ // generics/LatentReflection.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using reflection for latent typing @@ -12,8 +12,7 @@ public void sit() { System.out.println("Pretending to sit"); } public void pushInvisibleWalls() {} - @Override - public String toString() { return "Mime"; } + @Override public String toString() { return "Mime"; } } // Does not implement Performs: diff --git a/generics/LinkedStack.java b/generics/LinkedStack.java index 31f7fd0fd..932df84f0 100644 --- a/generics/LinkedStack.java +++ b/generics/LinkedStack.java @@ -1,5 +1,5 @@ // generics/LinkedStack.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A stack implemented with an internal linked structure diff --git a/generics/ListMaker.java b/generics/ListMaker.java index 7de76a847..f127e2dde 100644 --- a/generics/ListMaker.java +++ b/generics/ListMaker.java @@ -1,5 +1,5 @@ // generics/ListMaker.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/ListOfGenerics.java b/generics/ListOfGenerics.java index c0f5fae80..aa2f61873 100644 --- a/generics/ListOfGenerics.java +++ b/generics/ListOfGenerics.java @@ -1,5 +1,5 @@ // generics/ListOfGenerics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/ListOfInt.java b/generics/ListOfInt.java index 50491f8f2..a47754950 100644 --- a/generics/ListOfInt.java +++ b/generics/ListOfInt.java @@ -1,5 +1,5 @@ // generics/ListOfInt.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Autoboxing compensates for the inability diff --git a/generics/LostInformation.java b/generics/LostInformation.java index 031a166c1..6ca203424 100644 --- a/generics/LostInformation.java +++ b/generics/LostInformation.java @@ -1,5 +1,5 @@ // generics/LostInformation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/Manipulation.java b/generics/Manipulation.java index ff9cb384d..f3857515c 100644 --- a/generics/Manipulation.java +++ b/generics/Manipulation.java @@ -1,5 +1,5 @@ // generics/Manipulation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/generics/Manipulator2.java b/generics/Manipulator2.java index 7d044ef87..2d112dc60 100644 --- a/generics/Manipulator2.java +++ b/generics/Manipulator2.java @@ -1,5 +1,5 @@ // generics/Manipulator2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/Manipulator3.java b/generics/Manipulator3.java index 7b7b833fb..a737a727b 100644 --- a/generics/Manipulator3.java +++ b/generics/Manipulator3.java @@ -1,5 +1,5 @@ // generics/Manipulator3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/Mixins.cpp b/generics/Mixins.cpp index 3178f357c..defcac7d5 100644 --- a/generics/Mixins.cpp +++ b/generics/Mixins.cpp @@ -1,5 +1,5 @@ // generics/Mixins.cpp -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. #include diff --git a/generics/Mixins.java b/generics/Mixins.java index 3c3b94482..d64d07d6d 100644 --- a/generics/Mixins.java +++ b/generics/Mixins.java @@ -1,5 +1,5 @@ // generics/Mixins.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -42,12 +42,10 @@ class Mixin extends BasicImp private TimeStamped timeStamp = new TimeStampedImp(); private SerialNumbered serialNumber = new SerialNumberedImp(); - @Override - public long getStamp() { + @Override public long getStamp() { return timeStamp.getStamp(); } - @Override - public long getSerialNumber() { + @Override public long getSerialNumber() { return serialNumber.getSerialNumber(); } } @@ -66,6 +64,6 @@ public static void main(String[] args) { } } /* Output: -test string 1 1494331663026 1 -test string 2 1494331663027 2 +test string 1 1611503367257 1 +test string 2 1611503367258 2 */ diff --git a/generics/MultipleInterfaceVariants.java b/generics/MultipleInterfaceVariants.java index aca655945..c8a58fdd0 100644 --- a/generics/MultipleInterfaceVariants.java +++ b/generics/MultipleInterfaceVariants.java @@ -1,5 +1,5 @@ // generics/MultipleInterfaceVariants.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/generics/NeedCasting.java b/generics/NeedCasting.java index 910be732d..e8604e335 100644 --- a/generics/NeedCasting.java +++ b/generics/NeedCasting.java @@ -1,5 +1,5 @@ // generics/NeedCasting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/generics/NonCovariantGenerics.java b/generics/NonCovariantGenerics.java index c532708ed..9b56a1d95 100644 --- a/generics/NonCovariantGenerics.java +++ b/generics/NonCovariantGenerics.java @@ -1,5 +1,5 @@ // generics/NonCovariantGenerics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/generics/NotSelfBounded.java b/generics/NotSelfBounded.java index b691a397d..cdf78eb38 100644 --- a/generics/NotSelfBounded.java +++ b/generics/NotSelfBounded.java @@ -1,5 +1,5 @@ // generics/NotSelfBounded.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/ObjectHolder.java b/generics/ObjectHolder.java index 02f81bd19..a363f4070 100644 --- a/generics/ObjectHolder.java +++ b/generics/ObjectHolder.java @@ -1,5 +1,5 @@ // generics/ObjectHolder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/OrdinaryArguments.java b/generics/OrdinaryArguments.java index 351316bd0..02f0d5e15 100644 --- a/generics/OrdinaryArguments.java +++ b/generics/OrdinaryArguments.java @@ -1,5 +1,5 @@ // generics/OrdinaryArguments.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/Performs.java b/generics/Performs.java index 9a9f248e1..b9379e21e 100644 --- a/generics/Performs.java +++ b/generics/Performs.java @@ -1,5 +1,5 @@ // generics/Performs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/PlainGenericInheritance.java b/generics/PlainGenericInheritance.java index 4ef82c8d1..57e402768 100644 --- a/generics/PlainGenericInheritance.java +++ b/generics/PlainGenericInheritance.java @@ -1,5 +1,5 @@ // generics/PlainGenericInheritance.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/PrimitiveGenericTest.java b/generics/PrimitiveGenericTest.java index 6072b7e82..b745a8f72 100644 --- a/generics/PrimitiveGenericTest.java +++ b/generics/PrimitiveGenericTest.java @@ -1,5 +1,5 @@ // generics/PrimitiveGenericTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/generics/RandomList.java b/generics/RandomList.java index c87aa1624..470739f2b 100644 --- a/generics/RandomList.java +++ b/generics/RandomList.java @@ -1,5 +1,5 @@ // generics/RandomList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/RestrictedComparablePets.java b/generics/RestrictedComparablePets.java index a9e9ad742..7c87bb49c 100644 --- a/generics/RestrictedComparablePets.java +++ b/generics/RestrictedComparablePets.java @@ -1,10 +1,11 @@ // generics/RestrictedComparablePets.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. class Hamster extends ComparablePet implements Comparable { + @Override public int compareTo(ComparablePet arg) { return 0; } diff --git a/generics/ReturnGenericType.java b/generics/ReturnGenericType.java index 3d159679d..1e6dc005f 100644 --- a/generics/ReturnGenericType.java +++ b/generics/ReturnGenericType.java @@ -1,5 +1,5 @@ // generics/ReturnGenericType.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/SelfBounding.java b/generics/SelfBounding.java index 0a5dfa7c0..c0c509c3e 100644 --- a/generics/SelfBounding.java +++ b/generics/SelfBounding.java @@ -1,5 +1,5 @@ // generics/SelfBounding.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/SelfBoundingAndCovariantArguments.java b/generics/SelfBoundingAndCovariantArguments.java index ac5b70721..eefa864d1 100644 --- a/generics/SelfBoundingAndCovariantArguments.java +++ b/generics/SelfBoundingAndCovariantArguments.java @@ -1,5 +1,5 @@ // generics/SelfBoundingAndCovariantArguments.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/SelfBoundingMethods.java b/generics/SelfBoundingMethods.java index 76f0fb775..aab5b7b77 100644 --- a/generics/SelfBoundingMethods.java +++ b/generics/SelfBoundingMethods.java @@ -1,5 +1,5 @@ // generics/SelfBoundingMethods.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/Shape.java b/generics/Shape.java index 68a67ea70..271220b22 100644 --- a/generics/Shape.java +++ b/generics/Shape.java @@ -1,13 +1,12 @@ // generics/Shape.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Shape { private static long counter = 0; private final long id = counter++; - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName() + " " + id; } public void rotate() { diff --git a/generics/SimpleDogsAndRobots.java b/generics/SimpleDogsAndRobots.java index c659a9988..ebe1c9438 100644 --- a/generics/SimpleDogsAndRobots.java +++ b/generics/SimpleDogsAndRobots.java @@ -1,5 +1,5 @@ // generics/SimpleDogsAndRobots.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Removing the generic; code still works diff --git a/generics/SimpleHolder.java b/generics/SimpleHolder.java index b8673b243..5bc15f82b 100644 --- a/generics/SimpleHolder.java +++ b/generics/SimpleHolder.java @@ -1,5 +1,5 @@ // generics/SimpleHolder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/SimpleQueue.java b/generics/SimpleQueue.java index e74db48d3..18adc1bd7 100644 --- a/generics/SimpleQueue.java +++ b/generics/SimpleQueue.java @@ -1,5 +1,5 @@ // generics/SimpleQueue.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A different kind of Iterable collection @@ -9,8 +9,7 @@ public class SimpleQueue implements Iterable { private LinkedList storage = new LinkedList<>(); public void add(T t) { storage.offer(t); } public T get() { return storage.poll(); } - @Override - public Iterator iterator() { + @Override public Iterator iterator() { return storage.iterator(); } } diff --git a/generics/Square.java b/generics/Square.java index f12071f6c..5cca84a2c 100644 --- a/generics/Square.java +++ b/generics/Square.java @@ -1,5 +1,5 @@ // generics/Square.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Square extends Shape {} diff --git a/generics/Store.java b/generics/Store.java index 45120db26..921470845 100644 --- a/generics/Store.java +++ b/generics/Store.java @@ -1,5 +1,5 @@ // generics/Store.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Building a complex model using generic collections @@ -17,8 +17,7 @@ class Product { this.price = price; System.out.println(toString()); } - @Override - public String toString() { + @Override public String toString() { return id + ": " + description + ", price: $" + price; } @@ -28,8 +27,7 @@ public void priceChange(double change) { public static Supplier generator = new Supplier() { private Random rand = new Random(47); - @Override - public Product get() { + @Override public Product get() { return new Product(rand.nextInt(1000), "Test", Math.round( rand.nextDouble() * 1000.0) + 0.99); @@ -62,8 +60,7 @@ public Store( for(int i = 0; i < nAisles; i++) add(new Aisle(nShelves, nProducts)); } - @Override - public String toString() { + @Override public String toString() { StringBuilder result = new StringBuilder(); for(Aisle a : this) for(Shelf s : a) diff --git a/generics/SuperTypeWildcards.java b/generics/SuperTypeWildcards.java index c06a0d86f..e675bc74e 100644 --- a/generics/SuperTypeWildcards.java +++ b/generics/SuperTypeWildcards.java @@ -1,5 +1,5 @@ // generics/SuperTypeWildcards.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/Templates.cpp b/generics/Templates.cpp index 7434912a8..e56fdda7c 100644 --- a/generics/Templates.cpp +++ b/generics/Templates.cpp @@ -1,5 +1,5 @@ // generics/Templates.cpp -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. #include diff --git a/generics/ThrowGenericException.java b/generics/ThrowGenericException.java index 5152c00b3..2a8ddb5e9 100644 --- a/generics/ThrowGenericException.java +++ b/generics/ThrowGenericException.java @@ -1,5 +1,5 @@ // generics/ThrowGenericException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/TupleList.java b/generics/TupleList.java index 830b77421..896530b40 100644 --- a/generics/TupleList.java +++ b/generics/TupleList.java @@ -1,5 +1,5 @@ // generics/TupleList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Combining generic types to make complex generic types @@ -18,6 +18,6 @@ public static void main(String[] args) { } } /* Output: -(Vehicle@7cca494b, Amphibian@7ba4f24f, hi, 47) -(Vehicle@3b9a45b3, Amphibian@7699a589, hi, 47) +(Vehicle@ec7777, Amphibian@107d329, hi, 47) +(Vehicle@1629346, Amphibian@4b9385, hi, 47) */ diff --git a/generics/TupleTest.java b/generics/TupleTest.java index 7b22af561..0df194a2f 100644 --- a/generics/TupleTest.java +++ b/generics/TupleTest.java @@ -1,5 +1,5 @@ // generics/TupleTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; @@ -36,7 +36,7 @@ public static void main(String[] args) { } /* Output: (hi, 47) -(Amphibian@1540e19d, hi, 47) -(Vehicle@7f31245a, Amphibian@6d6f6e28, hi, 47) -(Vehicle@330bedb4, Amphibian@2503dbd3, hi, 47, 11.1) +(Amphibian@1c7c054, hi, 47) +(Vehicle@14991ad, Amphibian@d93b30, hi, 47) +(Vehicle@a14482, Amphibian@140e19d, hi, 47, 11.1) */ diff --git a/generics/TupleTest2.java b/generics/TupleTest2.java index 73e0e0ce4..f889d59f3 100644 --- a/generics/TupleTest2.java +++ b/generics/TupleTest2.java @@ -1,5 +1,5 @@ // generics/TupleTest2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; @@ -36,7 +36,7 @@ public static void main(String[] args) { /* Output: (hi, 47) (hi, 47) -(Amphibian@14ae5a5, hi, 47) -(Vehicle@135fbaa4, Amphibian@45ee12a7, hi, 47) -(Vehicle@4b67cf4d, Amphibian@7ea987ac, hi, 47, 11.1) +(Amphibian@a298b7, hi, 47) +(Vehicle@16d3586, Amphibian@154617c, hi, 47) +(Vehicle@17327b6, Amphibian@14ae5a5, hi, 47, 11.1) */ diff --git a/generics/UnboundedWildcards1.java b/generics/UnboundedWildcards1.java index 2a8ce8ae3..7aada9a6c 100644 --- a/generics/UnboundedWildcards1.java +++ b/generics/UnboundedWildcards1.java @@ -1,5 +1,5 @@ // generics/UnboundedWildcards1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/UnboundedWildcards2.java b/generics/UnboundedWildcards2.java index 159bab7b0..f1e17630e 100644 --- a/generics/UnboundedWildcards2.java +++ b/generics/UnboundedWildcards2.java @@ -1,5 +1,5 @@ // generics/UnboundedWildcards2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/Unconstrained.java b/generics/Unconstrained.java index 223c5f8c1..66c6bebd6 100644 --- a/generics/Unconstrained.java +++ b/generics/Unconstrained.java @@ -1,5 +1,5 @@ // generics/Unconstrained.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/generics/UseList.java b/generics/UseList.java index ff0262b03..3c9073aff 100644 --- a/generics/UseList.java +++ b/generics/UseList.java @@ -1,5 +1,5 @@ // generics/UseList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/generics/UseList2.java b/generics/UseList2.java index 4e7dcf294..bee17d0dc 100644 --- a/generics/UseList2.java +++ b/generics/UseList2.java @@ -1,5 +1,5 @@ // generics/UseList2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/generics/Vehicle.java b/generics/Vehicle.java index e45b5219c..dfe502c97 100644 --- a/generics/Vehicle.java +++ b/generics/Vehicle.java @@ -1,5 +1,5 @@ // generics/Vehicle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Vehicle {} diff --git a/generics/WatercolorSets.java b/generics/WatercolorSets.java index 04c7adc6e..2b285eaaa 100644 --- a/generics/WatercolorSets.java +++ b/generics/WatercolorSets.java @@ -1,5 +1,5 @@ // generics/WatercolorSets.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import generics.watercolors.*; @@ -36,19 +36,19 @@ public static void main(String[] args) { COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, BURNT_UMBER] -union(set1, set2): [BURNT_SIENNA, BRILLIANT_RED, -YELLOW_OCHRE, MAGENTA, SAP_GREEN, CERULEAN_BLUE_HUE, -ULTRAMARINE, VIRIDIAN_HUE, VIOLET, RAW_UMBER, -ROSE_MADDER, PERMANENT_GREEN, BURNT_UMBER, -PHTHALO_BLUE, CRIMSON, COBALT_BLUE_HUE] -intersection(set1, set2): [PERMANENT_GREEN, -CERULEAN_BLUE_HUE, ULTRAMARINE, VIRIDIAN_HUE, -PHTHALO_BLUE, COBALT_BLUE_HUE] -difference(set1, subset): [BRILLIANT_RED, MAGENTA, -VIOLET, CRIMSON, ROSE_MADDER] -difference(set2, subset): [BURNT_SIENNA, YELLOW_OCHRE, -BURNT_UMBER, SAP_GREEN, RAW_UMBER] -complement(set1, set2): [BURNT_SIENNA, BRILLIANT_RED, -YELLOW_OCHRE, MAGENTA, SAP_GREEN, VIOLET, RAW_UMBER, -ROSE_MADDER, BURNT_UMBER, CRIMSON] +union(set1, set2): [MAGENTA, COBALT_BLUE_HUE, VIOLET, +VIRIDIAN_HUE, BURNT_SIENNA, ULTRAMARINE, +CERULEAN_BLUE_HUE, BURNT_UMBER, BRILLIANT_RED, +PHTHALO_BLUE, YELLOW_OCHRE, SAP_GREEN, CRIMSON, +ROSE_MADDER, RAW_UMBER, PERMANENT_GREEN] +intersection(set1, set2): [COBALT_BLUE_HUE, +VIRIDIAN_HUE, ULTRAMARINE, CERULEAN_BLUE_HUE, +PHTHALO_BLUE, PERMANENT_GREEN] +difference(set1, subset): [CRIMSON, MAGENTA, VIOLET, +ROSE_MADDER, BRILLIANT_RED] +difference(set2, subset): [BURNT_SIENNA, BURNT_UMBER, +YELLOW_OCHRE, RAW_UMBER, SAP_GREEN] +complement(set1, set2): [MAGENTA, VIOLET, BURNT_SIENNA, +BURNT_UMBER, BRILLIANT_RED, YELLOW_OCHRE, SAP_GREEN, +CRIMSON, ROSE_MADDER, RAW_UMBER] */ diff --git a/generics/Wildcards.java b/generics/Wildcards.java index aa1a9163a..7c854bb43 100644 --- a/generics/Wildcards.java +++ b/generics/Wildcards.java @@ -1,5 +1,5 @@ // generics/Wildcards.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Exploring the meaning of wildcards diff --git a/generics/coffee/Americano.java b/generics/coffee/Americano.java index be25727ff..86c628288 100644 --- a/generics/coffee/Americano.java +++ b/generics/coffee/Americano.java @@ -1,5 +1,5 @@ // generics/coffee/Americano.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.coffee; diff --git a/generics/coffee/Breve.java b/generics/coffee/Breve.java index f5b521178..5afed481d 100644 --- a/generics/coffee/Breve.java +++ b/generics/coffee/Breve.java @@ -1,5 +1,5 @@ // generics/coffee/Breve.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.coffee; diff --git a/generics/coffee/Cappuccino.java b/generics/coffee/Cappuccino.java index 5804b7711..f50486849 100644 --- a/generics/coffee/Cappuccino.java +++ b/generics/coffee/Cappuccino.java @@ -1,5 +1,5 @@ // generics/coffee/Cappuccino.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.coffee; diff --git a/generics/coffee/Coffee.java b/generics/coffee/Coffee.java index 760788d40..3c893cb48 100644 --- a/generics/coffee/Coffee.java +++ b/generics/coffee/Coffee.java @@ -1,5 +1,5 @@ // generics/coffee/Coffee.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.coffee; @@ -7,8 +7,7 @@ public class Coffee { private static long counter = 0; private final long id = counter++; - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName() + " " + id; } } diff --git a/generics/coffee/CoffeeSupplier.java b/generics/coffee/CoffeeSupplier.java index f980c15d2..90df2e463 100644 --- a/generics/coffee/CoffeeSupplier.java +++ b/generics/coffee/CoffeeSupplier.java @@ -1,5 +1,5 @@ // generics/coffee/CoffeeSupplier.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java generics.coffee.CoffeeSupplier} @@ -7,6 +7,7 @@ import java.util.*; import java.util.function.*; import java.util.stream.*; +import java.lang.reflect.InvocationTargetException; public class CoffeeSupplier implements Supplier, Iterable { @@ -17,14 +18,16 @@ public CoffeeSupplier() {} // For iteration: private int size = 0; public CoffeeSupplier(int sz) { size = sz; } - @Override - public Coffee get() { + @Override public Coffee get() { try { return (Coffee) - types[rand.nextInt(types.length)].newInstance(); - // Report programmer errors at run time: - } catch(InstantiationException | - IllegalAccessException e) { + types[rand.nextInt(types.length)] + .getConstructor().newInstance(); + // Report programmer errors at runtime: + } catch(InstantiationException | + NoSuchMethodException | + InvocationTargetException | + IllegalAccessException e) { throw new RuntimeException(e); } } @@ -32,8 +35,7 @@ class CoffeeIterator implements Iterator { int count = size; @Override public boolean hasNext() { return count > 0; } - @Override - public Coffee next() { + @Override public Coffee next() { count--; return CoffeeSupplier.this.get(); } @@ -42,8 +44,7 @@ public void remove() { // Not implemented throw new UnsupportedOperationException(); } } - @Override - public Iterator iterator() { + @Override public Iterator iterator() { return new CoffeeIterator(); } public static void main(String[] args) { diff --git a/generics/coffee/Latte.java b/generics/coffee/Latte.java index 99bbfa70a..bf4d25831 100644 --- a/generics/coffee/Latte.java +++ b/generics/coffee/Latte.java @@ -1,5 +1,5 @@ // generics/coffee/Latte.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.coffee; diff --git a/generics/coffee/Mocha.java b/generics/coffee/Mocha.java index 87ef0f7ee..e4eaa5a20 100644 --- a/generics/coffee/Mocha.java +++ b/generics/coffee/Mocha.java @@ -1,5 +1,5 @@ // generics/coffee/Mocha.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.coffee; diff --git a/generics/decorator/Decoration.java b/generics/decorator/Decoration.java index d7f963253..07651bb35 100644 --- a/generics/decorator/Decoration.java +++ b/generics/decorator/Decoration.java @@ -1,5 +1,5 @@ // generics/decorator/Decoration.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java generics.decorator.Decoration} diff --git a/generics/dogsandrobots.go b/generics/dogsandrobots.go index 3b49bc52f..cba1e10c3 100644 --- a/generics/dogsandrobots.go +++ b/generics/dogsandrobots.go @@ -1,5 +1,5 @@ // generics/dogsandrobots.go -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package main diff --git a/generics/watercolors/Watercolors.java b/generics/watercolors/Watercolors.java index 205ed6ee7..33922ba10 100644 --- a/generics/watercolors/Watercolors.java +++ b/generics/watercolors/Watercolors.java @@ -1,5 +1,5 @@ // generics/watercolors/Watercolors.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package generics.watercolors; diff --git a/gradle.properties b/gradle.properties index f97ebb7d3..1cb5556b7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,3 @@ org.gradle.parallel=true +org.gradle.caching=true +org.gradle.warning.mode=none diff --git a/gradle/findbugs.gradle b/gradle/findbugs.gradle index f7e6383ba..ac628cb29 100644 --- a/gradle/findbugs.gradle +++ b/gradle/findbugs.gradle @@ -1,3 +1,4 @@ +/* apply plugin: 'findbugs' findbugs { @@ -10,4 +11,5 @@ tasks.withType(FindBugs) { xml.enabled = false html.enabled = true } -} \ No newline at end of file +} +*/ diff --git a/gradle/java.gradle b/gradle/java.gradle index eadc4ef94..99898c1d0 100644 --- a/gradle/java.gradle +++ b/gradle/java.gradle @@ -18,7 +18,7 @@ sourceSets { include '*.xml' } } - + test { java { srcDir file("tests") @@ -32,8 +32,8 @@ repositories { dependencies { // Logging: - compile 'org.slf4j:slf4j-api:1.7.21' - compile 'ch.qos.logback:logback-classic:1.1.7' + implementation 'org.slf4j:slf4j-api:1.7.21' + implementation 'ch.qos.logback:logback-classic:1.1.7' // You can also use the JDK's built-in logging as the back end: // compile group: 'org.slf4j:slf4j-jdk14:1.7.21' -} \ No newline at end of file +} diff --git a/gradle/junit-jupiter.gradle b/gradle/junit-jupiter.gradle index ccdd4ec02..98a778434 100644 --- a/gradle/junit-jupiter.gradle +++ b/gradle/junit-jupiter.gradle @@ -1,19 +1,15 @@ import org.apache.tools.ant.util.TeeOutputStream -apply plugin: 'org.junit.platform.gradle.plugin' - -ext { - junitJupiterVersion = '5.0.0-M2' -} - dependencies { - testCompile "org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}" - testRuntime "org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}" + testImplementation(platform('org.junit:junit-bom:5.7.0')) + testImplementation('org.junit.jupiter:junit-jupiter') } -junitPlatform { - platformVersion '1.0.0-M2' - includeClassNamePattern '.*' +test { + useJUnitPlatform() + testLogging { + events "passed", "skipped", "failed" + } } /* NEW: (REQUIRES CODE REWRITES IN BOOK AND TEST CODE) @@ -45,14 +41,28 @@ junitPlatform { JUnit 5's junitPlatformTest runs as a "javaExec" rather than a "test", so we can't hook into the before/after test behavior. */ -tasks.findByPath(":$name:junitPlatformTest").configure { +tasks.findByPath(":$name:test").configure { File testDir = file("tests") if(testDir.exists()) { File outFile = new File(testDir, 'report.txt') + + Writer taskOutput + doFirst { - standardOutput = new TeeOutputStream(new FileOutputStream(outFile, true), System.out) + taskOutput = project.file(outFile).newWriter() } + + testLogging.showStandardStreams = true + + onOutput { descriptor, event -> + taskOutput.append(event.message) + } + doLast { + // WARNING: if the task fails, this won't be executed and the file remains open. + // The memory cache version doesn't have this problem. + taskOutput.close() + if(outFile.size() == 0) outFile.delete() else if(outFile.text.contains("0 tests found")) diff --git a/gradle/subprojects.gradle b/gradle/subprojects.gradle index e9d857d87..945aa9231 100644 --- a/gradle/subprojects.gradle +++ b/gradle/subprojects.gradle @@ -6,7 +6,7 @@ project(':validating') { project(':equalshashcode') { dependencies { - compile project(':typeinfo') + compile project(':reflection') compile project(':collections') } } @@ -48,13 +48,19 @@ project(':hiding') { project(':generics') { dependencies { - compile project(':typeinfo') + compile project(':reflection') } } project(':collections') { dependencies { - compile project(':typeinfo') + compile project(':reflection') + } +} + +project(':patterns') { + dependencies { + compile project(':enums') } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 941144813..e708b1c02 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a2a607a91..28ff446a2 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https://services.gradle.org/distributions/gradle-3.5-bin.zip diff --git a/gradlew b/gradlew index 9d82f7891..4f906e0c8 100755 --- a/gradlew +++ b/gradlew @@ -1,4 +1,20 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## ## @@ -6,20 +22,38 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn ( ) { +warn () { echo "$*" } -die ( ) { +die () { echo echo "$*" echo @@ -30,6 +64,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,28 +75,14 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then @@ -85,7 +106,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then @@ -105,10 +126,11 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath @@ -134,27 +156,30 @@ if $cygwin ; then else eval `echo args$i`="\"$arg\"" fi - i=$((i+1)) + i=`expr $i + 1` done case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 8a0b282aa..107acd32c 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -8,20 +24,23 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,34 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/hiding/Cake.java b/hiding/Cake.java index ebb19720e..e4ee6698c 100644 --- a/hiding/Cake.java +++ b/hiding/Cake.java @@ -1,5 +1,5 @@ // hiding/Cake.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Accesses a class in a separate compilation unit diff --git a/hiding/ChocolateChip.java b/hiding/ChocolateChip.java index 0ba2066a2..dd98cc883 100644 --- a/hiding/ChocolateChip.java +++ b/hiding/ChocolateChip.java @@ -1,5 +1,5 @@ // hiding/ChocolateChip.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Can't use package-access member from another package diff --git a/hiding/ChocolateChip2.java b/hiding/ChocolateChip2.java index 7245a279f..bc85fb95f 100644 --- a/hiding/ChocolateChip2.java +++ b/hiding/ChocolateChip2.java @@ -1,5 +1,5 @@ // hiding/ChocolateChip2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import hiding.cookie2.*; diff --git a/hiding/CreatePackageAccessObject.java b/hiding/CreatePackageAccessObject.java index 3e057ea3f..823d6b265 100644 --- a/hiding/CreatePackageAccessObject.java +++ b/hiding/CreatePackageAccessObject.java @@ -1,5 +1,5 @@ // hiding/CreatePackageAccessObject.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/hiding/Dinner.java b/hiding/Dinner.java index 3c4d9e1a7..e027e6aa0 100644 --- a/hiding/Dinner.java +++ b/hiding/Dinner.java @@ -1,5 +1,5 @@ // hiding/Dinner.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Uses the library diff --git a/hiding/FullQualification.java b/hiding/FullQualification.java index 39e7cc343..e0a74371e 100644 --- a/hiding/FullQualification.java +++ b/hiding/FullQualification.java @@ -1,5 +1,5 @@ // hiding/FullQualification.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/hiding/IceCream.java b/hiding/IceCream.java index b9381f018..ad78cd7e4 100644 --- a/hiding/IceCream.java +++ b/hiding/IceCream.java @@ -1,5 +1,5 @@ // hiding/IceCream.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates "private" keyword diff --git a/hiding/ImportedMyClass.java b/hiding/ImportedMyClass.java index 63cb2bd5c..dfd0fc111 100644 --- a/hiding/ImportedMyClass.java +++ b/hiding/ImportedMyClass.java @@ -1,5 +1,5 @@ // hiding/ImportedMyClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import hiding.mypackage.*; diff --git a/hiding/LibTest.java b/hiding/LibTest.java index c75fa9379..4c2e970f9 100644 --- a/hiding/LibTest.java +++ b/hiding/LibTest.java @@ -1,5 +1,5 @@ // hiding/LibTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Uses the library diff --git a/hiding/Lunch.java b/hiding/Lunch.java index 1e4019205..81b46791a 100644 --- a/hiding/Lunch.java +++ b/hiding/Lunch.java @@ -1,5 +1,5 @@ // hiding/Lunch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates class access specifiers. Make a class @@ -7,14 +7,14 @@ class Soup1 { private Soup1() {} - public static Soup1 makeSoup() { // [1] + public static Soup1 makeSoup() { // [1] return new Soup1(); } } class Soup2 { private Soup2() {} - private static Soup2 ps1 = new Soup2(); // [2] + private static Soup2 ps1 = new Soup2(); // [2] public static Soup2 access() { return ps1; } diff --git a/hiding/OrganizedByAccess.java b/hiding/OrganizedByAccess.java index 67437c8f5..9553a7805 100644 --- a/hiding/OrganizedByAccess.java +++ b/hiding/OrganizedByAccess.java @@ -1,5 +1,5 @@ // hiding/OrganizedByAccess.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/hiding/Pie.java b/hiding/Pie.java index ce5abfee1..5cf3c12d7 100644 --- a/hiding/Pie.java +++ b/hiding/Pie.java @@ -1,5 +1,5 @@ // hiding/Pie.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The other class diff --git a/hiding/QualifiedMyClass.java b/hiding/QualifiedMyClass.java index 3b642f561..6b0beafcb 100644 --- a/hiding/QualifiedMyClass.java +++ b/hiding/QualifiedMyClass.java @@ -1,5 +1,5 @@ // hiding/QualifiedMyClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/hiding/SingleImport.java b/hiding/SingleImport.java index 4959fb541..4e7b26dc4 100644 --- a/hiding/SingleImport.java +++ b/hiding/SingleImport.java @@ -1,5 +1,5 @@ // hiding/SingleImport.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.ArrayList; diff --git a/hiding/cookie2/Cookie.java b/hiding/cookie2/Cookie.java index a3753a2e6..faa9bd5a9 100644 --- a/hiding/cookie2/Cookie.java +++ b/hiding/cookie2/Cookie.java @@ -1,5 +1,5 @@ // hiding/cookie2/Cookie.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package hiding.cookie2; diff --git a/hiding/dessert/Cookie.java b/hiding/dessert/Cookie.java index 58ac34bb7..b6de1bdb9 100644 --- a/hiding/dessert/Cookie.java +++ b/hiding/dessert/Cookie.java @@ -1,5 +1,5 @@ // hiding/dessert/Cookie.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creates a library diff --git a/hiding/mypackage/MyClass.java b/hiding/mypackage/MyClass.java index 5fd8c33a4..c029f6646 100644 --- a/hiding/mypackage/MyClass.java +++ b/hiding/mypackage/MyClass.java @@ -1,5 +1,5 @@ // hiding/mypackage/MyClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package hiding.mypackage; diff --git a/hiding/packageaccess/PublicConstructor.java b/hiding/packageaccess/PublicConstructor.java index 2e7c050ff..250090505 100644 --- a/hiding/packageaccess/PublicConstructor.java +++ b/hiding/packageaccess/PublicConstructor.java @@ -1,5 +1,5 @@ // hiding/packageaccess/PublicConstructor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package hiding.packageaccess; diff --git a/housekeeping/Apricot.java b/housekeeping/Apricot.java index da4c600f7..81932eaba 100644 --- a/housekeeping/Apricot.java +++ b/housekeeping/Apricot.java @@ -1,7 +1,8 @@ // housekeeping/Apricot.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + public class Apricot { void pick() { /* ... */ } void pit() { pick(); /* ... */ } diff --git a/housekeeping/ArrayClassObj.java b/housekeeping/ArrayClassObj.java index bd90c0f05..440087080 100644 --- a/housekeeping/ArrayClassObj.java +++ b/housekeeping/ArrayClassObj.java @@ -1,5 +1,5 @@ // housekeeping/ArrayClassObj.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating an array of nonprimitive objects diff --git a/housekeeping/ArrayInit.java b/housekeeping/ArrayInit.java index 5ccc56889..fc5ffb1ef 100644 --- a/housekeeping/ArrayInit.java +++ b/housekeeping/ArrayInit.java @@ -1,5 +1,5 @@ // housekeeping/ArrayInit.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Array initialization @@ -7,14 +7,8 @@ public class ArrayInit { public static void main(String[] args) { - Integer[] a = { - 1, 2, - 3, // Autoboxing - }; - Integer[] b = new Integer[]{ - 1, 2, - 3, // Autoboxing - }; + Integer[] a = { 1, 2, 3, }; + Integer[] b = new Integer[]{ 1, 2, 3, }; System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(b)); } diff --git a/housekeeping/ArrayNew.java b/housekeeping/ArrayNew.java index c37122b8e..8cba539a9 100644 --- a/housekeeping/ArrayNew.java +++ b/housekeeping/ArrayNew.java @@ -1,5 +1,5 @@ // housekeeping/ArrayNew.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating arrays with new diff --git a/housekeeping/ArraysOfPrimitives.java b/housekeeping/ArraysOfPrimitives.java index 0952aa7bf..cfd0cf2f6 100644 --- a/housekeeping/ArraysOfPrimitives.java +++ b/housekeeping/ArraysOfPrimitives.java @@ -1,5 +1,5 @@ // housekeeping/ArraysOfPrimitives.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/AutoboxingVarargs.java b/housekeeping/AutoboxingVarargs.java index 61cf17740..76bb5a7b0 100644 --- a/housekeeping/AutoboxingVarargs.java +++ b/housekeeping/AutoboxingVarargs.java @@ -1,5 +1,5 @@ // housekeeping/AutoboxingVarargs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/BananaPeel.java b/housekeeping/BananaPeel.java index badf828a6..30d1e8095 100644 --- a/housekeeping/BananaPeel.java +++ b/housekeeping/BananaPeel.java @@ -1,5 +1,5 @@ // housekeeping/BananaPeel.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/Burrito.java b/housekeeping/Burrito.java index 316f3324a..88bf16fc0 100644 --- a/housekeeping/Burrito.java +++ b/housekeeping/Burrito.java @@ -1,5 +1,5 @@ // housekeeping/Burrito.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/Counter.java b/housekeeping/Counter.java index 3db917be2..ef5733e72 100644 --- a/housekeeping/Counter.java +++ b/housekeeping/Counter.java @@ -1,5 +1,5 @@ // housekeeping/Counter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Counter { diff --git a/housekeeping/DefaultConstructor.java b/housekeeping/DefaultConstructor.java index a64294ead..ac8971130 100644 --- a/housekeeping/DefaultConstructor.java +++ b/housekeeping/DefaultConstructor.java @@ -1,5 +1,5 @@ // housekeeping/DefaultConstructor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/Demotion.java b/housekeeping/Demotion.java index e03ee8cca..5534bccb1 100644 --- a/housekeeping/Demotion.java +++ b/housekeeping/Demotion.java @@ -1,5 +1,5 @@ // housekeeping/Demotion.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demotion of primitives diff --git a/housekeeping/DynamicArray.java b/housekeeping/DynamicArray.java index 7c2cdf811..d94536e30 100644 --- a/housekeeping/DynamicArray.java +++ b/housekeeping/DynamicArray.java @@ -1,5 +1,5 @@ // housekeeping/DynamicArray.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Array initialization diff --git a/housekeeping/EnumOrder.java b/housekeeping/EnumOrder.java index 71e7855a0..8927ae50f 100644 --- a/housekeeping/EnumOrder.java +++ b/housekeeping/EnumOrder.java @@ -1,5 +1,5 @@ // housekeeping/EnumOrder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/ExplicitStatic.java b/housekeeping/ExplicitStatic.java index 885886486..034fbd417 100644 --- a/housekeeping/ExplicitStatic.java +++ b/housekeeping/ExplicitStatic.java @@ -1,5 +1,5 @@ // housekeeping/ExplicitStatic.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Explicit static initialization with "static" clause @@ -28,7 +28,7 @@ class Cups { public class ExplicitStatic { public static void main(String[] args) { System.out.println("Inside main()"); - Cups.cup1.f(99); // [1] + Cups.cup1.f(99); // [1] } // static Cups cups1 = new Cups(); // [2] // static Cups cups2 = new Cups(); // [2] diff --git a/housekeeping/Flower.java b/housekeeping/Flower.java index 5f2766d82..fa519d1d6 100644 --- a/housekeeping/Flower.java +++ b/housekeeping/Flower.java @@ -1,5 +1,5 @@ // housekeeping/Flower.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Calling constructors with "this" @@ -26,7 +26,7 @@ public class Flower { } Flower() { this("hi", 47); - System.out.println("no-arg constructor"); + System.out.println("Zero-argument constructor"); } void printPetalCount() { //- this(11); // Not inside non-constructor! @@ -41,6 +41,6 @@ public static void main(String[] args) { /* Output: Constructor w/ int arg only, petalCount= 47 String & int args -no-arg constructor +Zero-argument constructor petalCount = 47 s = hi */ diff --git a/housekeeping/ForTypeInference.java b/housekeeping/ForTypeInference.java new file mode 100644 index 000000000..8db4b9034 --- /dev/null +++ b/housekeeping/ForTypeInference.java @@ -0,0 +1,19 @@ +// housekeeping/ForTypeInference.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 11 + +public class ForTypeInference { + public static void main(String[] args) { + for(var s : Spiciness.values()) + System.out.println(s); + } +} +/* Output: +NOT +MILD +MEDIUM +HOT +FLAMING +*/ diff --git a/housekeeping/InitialValues.java b/housekeeping/InitialValues.java index c91360431..90c82ce14 100644 --- a/housekeeping/InitialValues.java +++ b/housekeeping/InitialValues.java @@ -1,5 +1,5 @@ // housekeeping/InitialValues.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Shows default initial values diff --git a/housekeeping/InitialValues2.java b/housekeeping/InitialValues2.java index ab0759534..678331e26 100644 --- a/housekeeping/InitialValues2.java +++ b/housekeeping/InitialValues2.java @@ -1,5 +1,5 @@ // housekeeping/InitialValues2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Providing explicit initial values diff --git a/housekeeping/Leaf.java b/housekeeping/Leaf.java index 761de2074..dc559c98d 100644 --- a/housekeeping/Leaf.java +++ b/housekeeping/Leaf.java @@ -1,5 +1,5 @@ // housekeeping/Leaf.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple use of the "this" keyword diff --git a/housekeeping/Measurement.java b/housekeeping/Measurement.java index a783e2c01..c97bfbd9f 100644 --- a/housekeeping/Measurement.java +++ b/housekeeping/Measurement.java @@ -1,5 +1,5 @@ // housekeeping/Measurement.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. class Depth {} diff --git a/housekeeping/MethodInit.java b/housekeeping/MethodInit.java index 6b8261aa7..242866b16 100644 --- a/housekeeping/MethodInit.java +++ b/housekeeping/MethodInit.java @@ -1,5 +1,5 @@ // housekeeping/MethodInit.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class MethodInit { diff --git a/housekeeping/MethodInit2.java b/housekeeping/MethodInit2.java index a6024f01b..d00d17900 100644 --- a/housekeeping/MethodInit2.java +++ b/housekeeping/MethodInit2.java @@ -1,5 +1,5 @@ // housekeeping/MethodInit2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class MethodInit2 { diff --git a/housekeeping/MethodInit3.java b/housekeeping/MethodInit3.java index 4361b7c5b..7b201f306 100644 --- a/housekeeping/MethodInit3.java +++ b/housekeeping/MethodInit3.java @@ -1,5 +1,5 @@ // housekeeping/MethodInit3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class MethodInit3 { diff --git a/housekeeping/Mugs.java b/housekeeping/Mugs.java index d9b928024..bdb6f1518 100644 --- a/housekeeping/Mugs.java +++ b/housekeeping/Mugs.java @@ -1,5 +1,5 @@ // housekeeping/Mugs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Instance initialization @@ -13,7 +13,7 @@ class Mug { public class Mugs { Mug mug1; Mug mug2; - { // [1] + { // [1] mug1 = new Mug(1); mug2 = new Mug(2); System.out.println("mug1 & mug2 initialized"); diff --git a/housekeeping/NewVarArgs.java b/housekeeping/NewVarArgs.java index 28eb2a9c5..6ee8d4a72 100644 --- a/housekeeping/NewVarArgs.java +++ b/housekeeping/NewVarArgs.java @@ -1,8 +1,8 @@ // housekeeping/NewVarArgs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Using array syntax to create variable argument lists +// Using ellipses to define a variable argument list public class NewVarArgs { static void printArray(Object... args) { @@ -25,6 +25,6 @@ public static void main(String[] args) { 47 3.14 11.11 47 3.14 11.11 one two three -A@15db9742 A@6d06d69c A@7852e922 +A@19e0bfd A@139a55 A@1db9742 1 2 3 4 */ diff --git a/housekeeping/NoSynthesis.java b/housekeeping/NoSynthesis.java index 88219e006..7cb90130d 100644 --- a/housekeeping/NoSynthesis.java +++ b/housekeeping/NoSynthesis.java @@ -1,5 +1,5 @@ // housekeeping/NoSynthesis.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/OptionalTrailingArguments.java b/housekeeping/OptionalTrailingArguments.java index f385bdd34..62b2a92f8 100644 --- a/housekeeping/OptionalTrailingArguments.java +++ b/housekeeping/OptionalTrailingArguments.java @@ -1,5 +1,5 @@ // housekeeping/OptionalTrailingArguments.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/OrderOfInitialization.java b/housekeeping/OrderOfInitialization.java index 7048f6202..dc175d315 100644 --- a/housekeeping/OrderOfInitialization.java +++ b/housekeeping/OrderOfInitialization.java @@ -1,5 +1,5 @@ // housekeeping/OrderOfInitialization.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates initialization order diff --git a/housekeeping/Overloading.java b/housekeeping/Overloading.java index 00f9e0477..55307f4fa 100644 --- a/housekeeping/Overloading.java +++ b/housekeeping/Overloading.java @@ -1,5 +1,5 @@ // housekeeping/Overloading.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Both constructor and ordinary method overloading @@ -32,7 +32,7 @@ public static void main(String[] args) { t.info(); t.info("overloaded method"); } - // Overloaded constructor: + // Calls overloaded constructor: new Tree(); } } diff --git a/housekeeping/OverloadingOrder.java b/housekeeping/OverloadingOrder.java index 694fff9a5..434768d77 100644 --- a/housekeeping/OverloadingOrder.java +++ b/housekeeping/OverloadingOrder.java @@ -1,8 +1,8 @@ // housekeeping/OverloadingOrder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Overloading based on the order of the arguments +// Overloading based on parameter order public class OverloadingOrder { static void f(String s, int i) { diff --git a/housekeeping/OverloadingVarargs.java b/housekeeping/OverloadingVarargs.java index fb96bad10..dea4785c5 100644 --- a/housekeeping/OverloadingVarargs.java +++ b/housekeeping/OverloadingVarargs.java @@ -1,5 +1,5 @@ // housekeeping/OverloadingVarargs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/OverloadingVarargs2.java b/housekeeping/OverloadingVarargs2.java index a9b779d8d..2c1755d41 100644 --- a/housekeeping/OverloadingVarargs2.java +++ b/housekeeping/OverloadingVarargs2.java @@ -1,5 +1,5 @@ // housekeeping/OverloadingVarargs2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/housekeeping/OverloadingVarargs3.java b/housekeeping/OverloadingVarargs3.java index 6245ea742..c49f472ea 100644 --- a/housekeeping/OverloadingVarargs3.java +++ b/housekeeping/OverloadingVarargs3.java @@ -1,5 +1,5 @@ // housekeeping/OverloadingVarargs3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/PassingThis.java b/housekeeping/PassingThis.java index c6769a53f..5a6bb9396 100644 --- a/housekeeping/PassingThis.java +++ b/housekeeping/PassingThis.java @@ -1,5 +1,5 @@ // housekeeping/PassingThis.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/PrimitiveOverloading.java b/housekeeping/PrimitiveOverloading.java index c54df4395..6a120b0cd 100644 --- a/housekeeping/PrimitiveOverloading.java +++ b/housekeeping/PrimitiveOverloading.java @@ -1,5 +1,5 @@ // housekeeping/PrimitiveOverloading.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Promotion of primitives and overloading @@ -101,20 +101,12 @@ public static void main(String[] args) { } } /* Output: -5: f1(int) f2(int) f3(int) f4(int) f5(long) f6(float) -f7(double) -char: f1(char) f2(int) f3(int) f4(int) f5(long) -f6(float) f7(double) -byte: f1(byte) f2(byte) f3(short) f4(int) f5(long) -f6(float) f7(double) -short: f1(short) f2(short) f3(short) f4(int) f5(long) -f6(float) f7(double) -int: f1(int) f2(int) f3(int) f4(int) f5(long) f6(float) -f7(double) -long: f1(long) f2(long) f3(long) f4(long) f5(long) -f6(float) f7(double) -float: f1(float) f2(float) f3(float) f4(float) -f5(float) f6(float) f7(double) -double: f1(double) f2(double) f3(double) f4(double) -f5(double) f6(double) f7(double) +5: f1(int) f2(int) f3(int) f4(int) f5(long) f6(float) f7(double) +char: f1(char) f2(int) f3(int) f4(int) f5(long) f6(float) f7(double) +byte: f1(byte) f2(byte) f3(short) f4(int) f5(long) f6(float) f7(double) +short: f1(short) f2(short) f3(short) f4(int) f5(long) f6(float) f7(double) +int: f1(int) f2(int) f3(int) f4(int) f5(long) f6(float) f7(double) +long: f1(long) f2(long) f3(long) f4(long) f5(long) f6(float) f7(double) +float: f1(float) f2(float) f3(float) f4(float) f5(float) f6(float) f7(double) +double: f1(double) f2(double) f3(double) f4(double) f5(double) f6(double) f7(double) */ diff --git a/housekeeping/SimpleConstructor.java b/housekeeping/SimpleConstructor.java index e6da947c5..ff28bd063 100644 --- a/housekeeping/SimpleConstructor.java +++ b/housekeeping/SimpleConstructor.java @@ -1,5 +1,5 @@ // housekeeping/SimpleConstructor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstration of a simple constructor diff --git a/housekeeping/SimpleConstructor2.java b/housekeeping/SimpleConstructor2.java index e2449f500..2a002daf6 100644 --- a/housekeeping/SimpleConstructor2.java +++ b/housekeeping/SimpleConstructor2.java @@ -1,8 +1,8 @@ // housekeeping/SimpleConstructor2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Constructors can have arguments +// Constructors can have parameters class Rock2 { Rock2(int i) { diff --git a/housekeeping/SimpleEnumUse.java b/housekeeping/SimpleEnumUse.java index c5e4b6a90..d1c69f024 100644 --- a/housekeeping/SimpleEnumUse.java +++ b/housekeeping/SimpleEnumUse.java @@ -1,5 +1,5 @@ // housekeeping/SimpleEnumUse.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/Spiciness.java b/housekeeping/Spiciness.java index e4988d88e..94ccfe85e 100644 --- a/housekeeping/Spiciness.java +++ b/housekeeping/Spiciness.java @@ -1,5 +1,5 @@ // housekeeping/Spiciness.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/housekeeping/Spoon.java b/housekeeping/Spoon.java index b8ce57882..bf9257689 100644 --- a/housekeeping/Spoon.java +++ b/housekeeping/Spoon.java @@ -1,5 +1,5 @@ // housekeeping/Spoon.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Spoon { diff --git a/housekeeping/StaticInitialization.java b/housekeeping/StaticInitialization.java index 27952629e..eaa743d84 100644 --- a/housekeeping/StaticInitialization.java +++ b/housekeeping/StaticInitialization.java @@ -1,5 +1,5 @@ // housekeeping/StaticInitialization.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Specifying initial values in a class definition diff --git a/housekeeping/TerminationCondition.java b/housekeeping/TerminationCondition.java index 2ef78ecba..532053b7c 100644 --- a/housekeeping/TerminationCondition.java +++ b/housekeeping/TerminationCondition.java @@ -1,5 +1,5 @@ // housekeeping/TerminationCondition.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using finalize() to detect an object that @@ -14,8 +14,8 @@ class Book { void checkIn() { checkedOut = false; } - @Override - public void finalize() { + @SuppressWarnings("deprecation") + @Override public void finalize() { if(checkedOut) System.out.println("Error: checked out"); // Normally, you'll also do this: diff --git a/housekeeping/TypeInference.java b/housekeeping/TypeInference.java new file mode 100644 index 000000000..9f06fc2d8 --- /dev/null +++ b/housekeeping/TypeInference.java @@ -0,0 +1,36 @@ +// housekeeping/TypeInference.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 11 + +class Plumbus {} + +public class TypeInference { + void method() { + // Explicit type: + String hello1 = "Hello"; + // Type inference: + var hello = "Hello!"; + // Works for user-defined types: + Plumbus pb1 = new Plumbus(); + var pb2 = new Plumbus(); + } + // Also works for static methods: + static void staticMethod() { + var hello = "Hello!"; + var pb2 = new Plumbus(); + } +} + +class NoInference { + String field1 = "Field initialization"; + // var field2 = "Can't do this"; + // void method() { + // var noInitializer; // No inference data + // var aNull = null; // No inference data + // } + // var inferReturnType() { + // return "Can't infer return type"; + // } +} diff --git a/housekeeping/VarArgs.java b/housekeeping/VarArgs.java index 36dfb5a0a..0899b8614 100644 --- a/housekeeping/VarArgs.java +++ b/housekeeping/VarArgs.java @@ -1,5 +1,5 @@ // housekeeping/VarArgs.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using array syntax to create variable argument lists @@ -13,8 +13,7 @@ static void printArray(Object[] args) { System.out.println(); } public static void main(String[] args) { - printArray(new Object[]{ - 47, (float) 3.14, 11.11}); + printArray(new Object[]{47, (float) 3.14, 11.11}); printArray(new Object[]{"one", "two", "three" }); printArray(new Object[]{new A(), new A(), new A()}); } @@ -22,5 +21,5 @@ public static void main(String[] args) { /* Output: 47 3.14 11.11 one two three -A@15db9742 A@6d06d69c A@7852e922 +A@19e0bfd A@139a55 A@1db9742 */ diff --git a/housekeeping/VarargType.java b/housekeeping/VarargType.java index 311b0487d..b6ea406bc 100644 --- a/housekeeping/VarargType.java +++ b/housekeeping/VarargType.java @@ -1,5 +1,5 @@ // housekeeping/VarargType.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/innerclasses/AnonymousConstructor.java b/innerclasses/AnonymousConstructor.java index 7395a3355..10a6b6433 100644 --- a/innerclasses/AnonymousConstructor.java +++ b/innerclasses/AnonymousConstructor.java @@ -1,5 +1,5 @@ // innerclasses/AnonymousConstructor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating a constructor for an anonymous inner class @@ -16,8 +16,7 @@ public static Base getBase(int i) { return new Base(i) { { System.out.println( "Inside instance initializer"); } - @Override - public void f() { + @Override public void f() { System.out.println("In anonymous f()"); } }; diff --git a/innerclasses/BigEgg.java b/innerclasses/BigEgg.java index c1572c594..96cb06f3a 100644 --- a/innerclasses/BigEgg.java +++ b/innerclasses/BigEgg.java @@ -1,5 +1,5 @@ // innerclasses/BigEgg.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // An inner class cannot be overridden like a method diff --git a/innerclasses/BigEgg2.java b/innerclasses/BigEgg2.java index 0eb0abce4..847165f3c 100644 --- a/innerclasses/BigEgg2.java +++ b/innerclasses/BigEgg2.java @@ -1,5 +1,5 @@ // innerclasses/BigEgg2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Proper inheritance of an inner class @@ -24,8 +24,7 @@ public class Yolk extends Egg2.Yolk { public Yolk() { System.out.println("BigEgg2.Yolk()"); } - @Override - public void f() { + @Override public void f() { System.out.println("BigEgg2.Yolk.f()"); } } diff --git a/innerclasses/Callbacks.java b/innerclasses/Callbacks.java index 214019c5f..9031ea242 100644 --- a/innerclasses/Callbacks.java +++ b/innerclasses/Callbacks.java @@ -1,5 +1,5 @@ // innerclasses/Callbacks.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using inner classes for callbacks @@ -13,8 +13,7 @@ interface Incrementable { // Very simple to just implement the interface: class Callee1 implements Incrementable { private int i = 0; - @Override - public void increment() { + @Override public void increment() { i++; System.out.println(i); } @@ -31,15 +30,13 @@ public void increment() { // some other way, you must use an inner class: class Callee2 extends MyIncrement { private int i = 0; - @Override - public void increment() { + @Override public void increment() { super.increment(); i++; System.out.println(i); } private class Closure implements Incrementable { - @Override - public void increment() { + @Override public void increment() { // Specify outer-class method, otherwise // you'll get an infinite recursion: Callee2.this.increment(); diff --git a/innerclasses/ClassInInterface.java b/innerclasses/ClassInInterface.java index a2e34ccb4..b06042743 100644 --- a/innerclasses/ClassInInterface.java +++ b/innerclasses/ClassInInterface.java @@ -1,5 +1,5 @@ // innerclasses/ClassInInterface.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java ClassInInterface$Test} @@ -7,8 +7,7 @@ public interface ClassInInterface { void howdy(); class Test implements ClassInInterface { - @Override - public void howdy() { + @Override public void howdy() { System.out.println("Howdy!"); } public static void main(String[] args) { diff --git a/innerclasses/Contents.java b/innerclasses/Contents.java index 98360c794..e31519124 100644 --- a/innerclasses/Contents.java +++ b/innerclasses/Contents.java @@ -1,5 +1,5 @@ // innerclasses/Contents.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public interface Contents { diff --git a/innerclasses/Destination.java b/innerclasses/Destination.java index 4b5ded927..0702be02f 100644 --- a/innerclasses/Destination.java +++ b/innerclasses/Destination.java @@ -1,5 +1,5 @@ // innerclasses/Destination.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public interface Destination { diff --git a/innerclasses/DotNew.java b/innerclasses/DotNew.java index e587e461e..3f77dc608 100644 --- a/innerclasses/DotNew.java +++ b/innerclasses/DotNew.java @@ -1,5 +1,5 @@ // innerclasses/DotNew.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating an inner class directly using .new syntax diff --git a/innerclasses/DotThis.java b/innerclasses/DotThis.java index 6ef93b930..881ba9a9e 100644 --- a/innerclasses/DotThis.java +++ b/innerclasses/DotThis.java @@ -1,5 +1,5 @@ // innerclasses/DotThis.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Accessing the outer-class object diff --git a/innerclasses/GreenhouseController.java b/innerclasses/GreenhouseController.java index cdec74565..5ec13cab6 100644 --- a/innerclasses/GreenhouseController.java +++ b/innerclasses/GreenhouseController.java @@ -1,5 +1,5 @@ // innerclasses/GreenhouseController.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Configure and execute the greenhouse system diff --git a/innerclasses/GreenhouseControls.java b/innerclasses/GreenhouseControls.java index 534deb9ac..4836f8c5e 100644 --- a/innerclasses/GreenhouseControls.java +++ b/innerclasses/GreenhouseControls.java @@ -1,5 +1,5 @@ // innerclasses/GreenhouseControls.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // This produces a specific application of the @@ -14,14 +14,12 @@ public class LightOn extends Event { public LightOn(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { // Put hardware control code here to // physically turn on the light. light = true; } - @Override - public String toString() { + @Override public String toString() { return "Light is on"; } } @@ -29,14 +27,12 @@ public class LightOff extends Event { public LightOff(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { // Put hardware control code here to // physically turn off the light. light = false; } - @Override - public String toString() { + @Override public String toString() { return "Light is off"; } } @@ -45,13 +41,11 @@ public class WaterOn extends Event { public WaterOn(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { // Put hardware control code here. water = true; } - @Override - public String toString() { + @Override public String toString() { return "Greenhouse water is on"; } } @@ -59,13 +53,11 @@ public class WaterOff extends Event { public WaterOff(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { // Put hardware control code here. water = false; } - @Override - public String toString() { + @Override public String toString() { return "Greenhouse water is off"; } } @@ -74,13 +66,11 @@ public class ThermostatNight extends Event { public ThermostatNight(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { // Put hardware control code here. thermostat = "Night"; } - @Override - public String toString() { + @Override public String toString() { return "Thermostat on night setting"; } } @@ -88,13 +78,11 @@ public class ThermostatDay extends Event { public ThermostatDay(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { // Put hardware control code here. thermostat = "Day"; } - @Override - public String toString() { + @Override public String toString() { return "Thermostat on day setting"; } } @@ -104,12 +92,10 @@ public class Bell extends Event { public Bell(long delayTime) { super(delayTime); } - @Override - public void action() { + @Override public void action() { addEvent(new Bell(delayTime.toMillis())); } - @Override - public String toString() { + @Override public String toString() { return "Bing!"; } } @@ -122,8 +108,7 @@ public class Restart extends Event { for(Event e : eventList) addEvent(e); } - @Override - public void action() { + @Override public void action() { for(Event e : eventList) { e.start(); // Rerun each event addEvent(e); @@ -131,8 +116,7 @@ public void action() { start(); // Rerun this Event addEvent(this); } - @Override - public String toString() { + @Override public String toString() { return "Restarting system"; } } @@ -142,8 +126,7 @@ public Terminate(long delayTime) { } @Override public void action() { System.exit(0); } - @Override - public String toString() { + @Override public String toString() { return "Terminating"; } } diff --git a/innerclasses/InheritInner.java b/innerclasses/InheritInner.java index 410e2864a..5e89cbe11 100644 --- a/innerclasses/InheritInner.java +++ b/innerclasses/InheritInner.java @@ -1,5 +1,5 @@ // innerclasses/InheritInner.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Inheriting an inner class diff --git a/innerclasses/LocalInnerClass.java b/innerclasses/LocalInnerClass.java index 533a25d04..efc2ec555 100644 --- a/innerclasses/LocalInnerClass.java +++ b/innerclasses/LocalInnerClass.java @@ -1,5 +1,5 @@ // innerclasses/LocalInnerClass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Holds a sequence of Objects @@ -17,8 +17,7 @@ class LocalCounter implements Counter { // Local inner class can have a constructor System.out.println("LocalCounter()"); } - @Override - public int next() { + @Override public int next() { System.out.print(name); // Access local final return count++; } @@ -33,8 +32,7 @@ Counter getCounter2(final String name) { { System.out.println("Counter()"); } - @Override - public int next() { + @Override public int next() { System.out.print(name); // Access local final return count++; } diff --git a/innerclasses/MultiImplementation.java b/innerclasses/MultiImplementation.java index 0b6db9e62..d5e4869af 100644 --- a/innerclasses/MultiImplementation.java +++ b/innerclasses/MultiImplementation.java @@ -1,5 +1,5 @@ // innerclasses/MultiImplementation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // For concrete or abstract classes, inner classes diff --git a/innerclasses/MultiNestingAccess.java b/innerclasses/MultiNestingAccess.java index a05eb0447..a97ffcfed 100644 --- a/innerclasses/MultiNestingAccess.java +++ b/innerclasses/MultiNestingAccess.java @@ -1,5 +1,5 @@ // innerclasses/MultiNestingAccess.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Nested classes can access all members of all diff --git a/innerclasses/Parcel1.java b/innerclasses/Parcel1.java index 33467b1e8..270134080 100644 --- a/innerclasses/Parcel1.java +++ b/innerclasses/Parcel1.java @@ -1,5 +1,5 @@ // innerclasses/Parcel1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating inner classes diff --git a/innerclasses/Parcel10.java b/innerclasses/Parcel10.java index 77684e413..1d02fb7a1 100644 --- a/innerclasses/Parcel10.java +++ b/innerclasses/Parcel10.java @@ -1,5 +1,5 @@ // innerclasses/Parcel10.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using "instance initialization" to perform diff --git a/innerclasses/Parcel11.java b/innerclasses/Parcel11.java index 40d8da484..ccedb3b40 100644 --- a/innerclasses/Parcel11.java +++ b/innerclasses/Parcel11.java @@ -1,5 +1,5 @@ // innerclasses/Parcel11.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Nested classes (static inner classes) @@ -8,8 +8,7 @@ public class Parcel11 { private static class ParcelContents implements Contents { private int i = 11; - @Override - public int value() { return i; } + @Override public int value() { return i; } } protected static final class ParcelDestination implements Destination { diff --git a/innerclasses/Parcel2.java b/innerclasses/Parcel2.java index 1f4f8274d..e7e106d98 100644 --- a/innerclasses/Parcel2.java +++ b/innerclasses/Parcel2.java @@ -1,5 +1,5 @@ // innerclasses/Parcel2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Returning a reference to an inner class diff --git a/innerclasses/Parcel3.java b/innerclasses/Parcel3.java index 6ee03313b..d35f9d6aa 100644 --- a/innerclasses/Parcel3.java +++ b/innerclasses/Parcel3.java @@ -1,5 +1,5 @@ // innerclasses/Parcel3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using .new to create instances of inner classes diff --git a/innerclasses/Parcel5.java b/innerclasses/Parcel5.java index 643322d1b..79ea40a89 100644 --- a/innerclasses/Parcel5.java +++ b/innerclasses/Parcel5.java @@ -1,5 +1,5 @@ // innerclasses/Parcel5.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Nesting a class within a method diff --git a/innerclasses/Parcel6.java b/innerclasses/Parcel6.java index 118ff6f51..4c4325ba9 100644 --- a/innerclasses/Parcel6.java +++ b/innerclasses/Parcel6.java @@ -1,5 +1,5 @@ // innerclasses/Parcel6.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Nesting a class within a scope diff --git a/innerclasses/Parcel7.java b/innerclasses/Parcel7.java index 7ed0ef514..c98947d49 100644 --- a/innerclasses/Parcel7.java +++ b/innerclasses/Parcel7.java @@ -1,5 +1,5 @@ // innerclasses/Parcel7.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Returning an instance of an anonymous inner class @@ -8,8 +8,7 @@ public class Parcel7 { public Contents contents() { return new Contents() { // Insert class definition private int i = 11; - @Override - public int value() { return i; } + @Override public int value() { return i; } }; // Semicolon required } public static void main(String[] args) { diff --git a/innerclasses/Parcel7b.java b/innerclasses/Parcel7b.java index 6c4a40484..31521df9e 100644 --- a/innerclasses/Parcel7b.java +++ b/innerclasses/Parcel7b.java @@ -1,5 +1,5 @@ // innerclasses/Parcel7b.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Expanded version of Parcel7.java @@ -7,8 +7,7 @@ public class Parcel7b { class MyContents implements Contents { private int i = 11; - @Override - public int value() { return i; } + @Override public int value() { return i; } } public Contents contents() { return new MyContents(); diff --git a/innerclasses/Parcel8.java b/innerclasses/Parcel8.java index ead289089..4ee309935 100644 --- a/innerclasses/Parcel8.java +++ b/innerclasses/Parcel8.java @@ -1,5 +1,5 @@ // innerclasses/Parcel8.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Calling the base-class constructor @@ -7,12 +7,11 @@ public class Parcel8 { public Wrapping wrapping(int x) { // Base constructor call: - return new Wrapping(x) { // [1] - @Override - public int value() { + return new Wrapping(x) { // [1] + @Override public int value() { return super.value() * 47; } - }; // [2] + }; // [2] } public static void main(String[] args) { Parcel8 p = new Parcel8(); diff --git a/innerclasses/Parcel9.java b/innerclasses/Parcel9.java index 599599c9c..53053cd16 100644 --- a/innerclasses/Parcel9.java +++ b/innerclasses/Parcel9.java @@ -1,5 +1,5 @@ // innerclasses/Parcel9.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/innerclasses/Sequence.java b/innerclasses/Sequence.java index ebcbdeea6..ad9869177 100644 --- a/innerclasses/Sequence.java +++ b/innerclasses/Sequence.java @@ -1,5 +1,5 @@ // innerclasses/Sequence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Holds a sequence of Objects diff --git a/innerclasses/TestBed.java b/innerclasses/TestBed.java index fb969a1fe..35a7fade2 100644 --- a/innerclasses/TestBed.java +++ b/innerclasses/TestBed.java @@ -1,5 +1,5 @@ // innerclasses/TestBed.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Putting test code in a nested class diff --git a/innerclasses/TestParcel.java b/innerclasses/TestParcel.java index c1549a631..76ec51bda 100644 --- a/innerclasses/TestParcel.java +++ b/innerclasses/TestParcel.java @@ -1,13 +1,12 @@ // innerclasses/TestParcel.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. class Parcel4 { private class PContents implements Contents { private int i = 11; - @Override - public int value() { return i; } + @Override public int value() { return i; } } protected final class PDestination implements Destination { diff --git a/innerclasses/Wrapping.java b/innerclasses/Wrapping.java index 15b2e76f1..74e9e9ab8 100644 --- a/innerclasses/Wrapping.java +++ b/innerclasses/Wrapping.java @@ -1,5 +1,5 @@ // innerclasses/Wrapping.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Wrapping { diff --git a/innerclasses/controller/Controller.java b/innerclasses/controller/Controller.java index 794dfaa37..de766961a 100644 --- a/innerclasses/controller/Controller.java +++ b/innerclasses/controller/Controller.java @@ -1,5 +1,5 @@ // innerclasses/controller/Controller.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The reusable framework for control systems diff --git a/innerclasses/controller/Event.java b/innerclasses/controller/Event.java index ed46f48cb..247e4c90b 100644 --- a/innerclasses/controller/Event.java +++ b/innerclasses/controller/Event.java @@ -1,5 +1,5 @@ // innerclasses/controller/Event.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The common methods for any control event diff --git a/innerclasses/mui/MultiInterfaces.java b/innerclasses/mui/MultiInterfaces.java index cdfc0cdab..ee69f61ab 100644 --- a/innerclasses/mui/MultiInterfaces.java +++ b/innerclasses/mui/MultiInterfaces.java @@ -1,5 +1,5 @@ // innerclasses/mui/MultiInterfaces.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Two ways a class can implement multiple interfaces diff --git a/interfaces/AbstractAccess.java b/interfaces/AbstractAccess.java index cb155163f..8645d9f36 100644 --- a/interfaces/AbstractAccess.java +++ b/interfaces/AbstractAccess.java @@ -1,5 +1,5 @@ // interfaces/AbstractAccess.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/AbstractWithoutAbstracts.java b/interfaces/AbstractWithoutAbstracts.java index 428590d1c..587248a02 100644 --- a/interfaces/AbstractWithoutAbstracts.java +++ b/interfaces/AbstractWithoutAbstracts.java @@ -1,5 +1,5 @@ // interfaces/AbstractWithoutAbstracts.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/AdaptedRandomDoubles.java b/interfaces/AdaptedRandomDoubles.java index dc80a5798..d965e5add 100644 --- a/interfaces/AdaptedRandomDoubles.java +++ b/interfaces/AdaptedRandomDoubles.java @@ -1,5 +1,5 @@ // interfaces/AdaptedRandomDoubles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating an adapter with inheritance @@ -12,8 +12,7 @@ public class AdaptedRandomDoubles public AdaptedRandomDoubles(int count) { this.count = count; } - @Override - public int read(CharBuffer cb) { + @Override public int read(CharBuffer cb) { if(count-- == 0) return -1; String result = Double.toString(next()) + " "; diff --git a/interfaces/Adventure.java b/interfaces/Adventure.java index 0691fd732..4e0bbbde2 100644 --- a/interfaces/Adventure.java +++ b/interfaces/Adventure.java @@ -1,5 +1,5 @@ // interfaces/Adventure.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Multiple interfaces @@ -22,8 +22,8 @@ public void fight() {} class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { - public void swim() {} - public void fly() {} + @Override public void swim() {} + @Override public void fly() {} } public class Adventure { diff --git a/interfaces/AnImplementation.java b/interfaces/AnImplementation.java index f22ae3610..29ca8df57 100644 --- a/interfaces/AnImplementation.java +++ b/interfaces/AnImplementation.java @@ -1,13 +1,13 @@ // interfaces/AnImplementation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class AnImplementation implements AnInterface { - public void firstMethod() { + @Override public void firstMethod() { System.out.println("firstMethod"); } - public void secondMethod() { + @Override public void secondMethod() { System.out.println("secondMethod"); } public static void main(String[] args) { diff --git a/interfaces/AnInterface.java b/interfaces/AnInterface.java index 070af2ca8..333dbe2b5 100644 --- a/interfaces/AnInterface.java +++ b/interfaces/AnInterface.java @@ -1,5 +1,5 @@ // interfaces/AnInterface.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/Applicator.java b/interfaces/Applicator.java index 1c57d8a68..1082629a1 100644 --- a/interfaces/Applicator.java +++ b/interfaces/Applicator.java @@ -1,5 +1,5 @@ // interfaces/Applicator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/interfaces/AttemptToUseBasic.java b/interfaces/AttemptToUseBasic.java index 25901d865..d8e67f72b 100644 --- a/interfaces/AttemptToUseBasic.java +++ b/interfaces/AttemptToUseBasic.java @@ -1,5 +1,5 @@ // interfaces/AttemptToUseBasic.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/interfaces/Basic.java b/interfaces/Basic.java index 9643027d0..943392b02 100644 --- a/interfaces/Basic.java +++ b/interfaces/Basic.java @@ -1,5 +1,5 @@ // interfaces/Basic.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/Basic2.java b/interfaces/Basic2.java index a0e8e9b26..1c33a54f9 100644 --- a/interfaces/Basic2.java +++ b/interfaces/Basic2.java @@ -1,5 +1,5 @@ // interfaces/Basic2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/CheckedDowncast.java b/interfaces/CheckedDowncast.java new file mode 100644 index 000000000..90689585d --- /dev/null +++ b/interfaces/CheckedDowncast.java @@ -0,0 +1,19 @@ +// interfaces/CheckedDowncast.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed interface II permits JJ {} +final class JJ implements II {} +class Something {} + +public class CheckedDowncast { + public void f() { + II i = new JJ(); + JJ j = (JJ)i; + // Something s = (Something)i; + // error: incompatible types: II cannot + // be converted to Something + } +} diff --git a/interfaces/Factories.java b/interfaces/Factories.java index 508df208f..8ab076014 100644 --- a/interfaces/Factories.java +++ b/interfaces/Factories.java @@ -1,5 +1,5 @@ // interfaces/Factories.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -14,34 +14,32 @@ interface ServiceFactory { class Service1 implements Service { Service1() {} // Package access - public void method1() { + @Override public void method1() { System.out.println("Service1 method1"); } - public void method2() { + @Override public void method2() { System.out.println("Service1 method2"); } } class Service1Factory implements ServiceFactory { - @Override - public Service getService() { + @Override public Service getService() { return new Service1(); } } class Service2 implements Service { Service2() {} // Package access - public void method1() { + @Override public void method1() { System.out.println("Service2 method1"); } - public void method2() { + @Override public void method2() { System.out.println("Service2 method2"); } } class Service2Factory implements ServiceFactory { - @Override - public Service getService() { + @Override public Service getService() { return new Service2(); } } diff --git a/interfaces/Games.java b/interfaces/Games.java index 9d0afbc45..3190d3b1e 100644 --- a/interfaces/Games.java +++ b/interfaces/Games.java @@ -1,5 +1,5 @@ // interfaces/Games.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A Game framework using Factory Methods @@ -10,8 +10,7 @@ interface GameFactory { Game getGame(); } class Checkers implements Game { private int moves = 0; private static final int MOVES = 3; - @Override - public boolean move() { + @Override public boolean move() { System.out.println("Checkers move " + moves); return ++moves != MOVES; } @@ -25,8 +24,7 @@ class CheckersFactory implements GameFactory { class Chess implements Game { private int moves = 0; private static final int MOVES = 4; - @Override - public boolean move() { + @Override public boolean move() { System.out.println("Chess move " + moves); return ++moves != MOVES; } diff --git a/interfaces/HorrorShow.java b/interfaces/HorrorShow.java index 90f84129d..079fe2ce3 100644 --- a/interfaces/HorrorShow.java +++ b/interfaces/HorrorShow.java @@ -1,5 +1,5 @@ // interfaces/HorrorShow.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Extending an interface with inheritance @@ -17,10 +17,8 @@ interface Lethal { } class DragonZilla implements DangerousMonster { - @Override - public void menace() {} - @Override - public void destroy() {} + @Override public void menace() {} + @Override public void destroy() {} } interface Vampire extends DangerousMonster, Lethal { @@ -28,14 +26,10 @@ interface Vampire extends DangerousMonster, Lethal { } class VeryBadVampire implements Vampire { - @Override - public void menace() {} - @Override - public void destroy() {} - @Override - public void kill() {} - @Override - public void drinkBlood() {} + @Override public void menace() {} + @Override public void destroy() {} + @Override public void kill() {} + @Override public void drinkBlood() {} } public class HorrorShow { diff --git a/interfaces/Implementation2.java b/interfaces/Implementation2.java index b94bc2cf1..07fb48324 100644 --- a/interfaces/Implementation2.java +++ b/interfaces/Implementation2.java @@ -1,14 +1,14 @@ // interfaces/Implementation2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Implementation2 implements InterfaceWithDefault { - public void firstMethod() { + @Override public void firstMethod() { System.out.println("firstMethod"); } - public void secondMethod() { + @Override public void secondMethod() { System.out.println("secondMethod"); } public static void main(String[] args) { diff --git a/interfaces/ImplementingAnInterface.java b/interfaces/ImplementingAnInterface.java index bded0ac5d..1504667fe 100644 --- a/interfaces/ImplementingAnInterface.java +++ b/interfaces/ImplementingAnInterface.java @@ -1,5 +1,5 @@ // interfaces/ImplementingAnInterface.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,6 +9,10 @@ interface Concept { // Package access } class Implementation implements Concept { - public void idea1() { System.out.println("idea1"); } - public void idea2() { System.out.println("idea2"); } + @Override public void idea1() { + System.out.println("idea1"); + } + @Override public void idea2() { + System.out.println("idea2"); + } } diff --git a/interfaces/Instantiable.java b/interfaces/Instantiable.java index b09dcd3e8..80b689895 100644 --- a/interfaces/Instantiable.java +++ b/interfaces/Instantiable.java @@ -1,5 +1,5 @@ // interfaces/Instantiable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,10 +9,8 @@ abstract class Uninstantiable { } public class Instantiable extends Uninstantiable { - @Override - void f() { System.out.println("f()"); } - @Override - int g() { return 22; } + @Override void f() { System.out.println("f()"); } + @Override int g() { return 22; } public static void main(String[] args) { Uninstantiable ui = new Instantiable(); } diff --git a/interfaces/InterfaceCollision.java b/interfaces/InterfaceCollision.java index 5d85b6149..e00fb8a84 100644 --- a/interfaces/InterfaceCollision.java +++ b/interfaces/InterfaceCollision.java @@ -1,5 +1,5 @@ // interfaces/InterfaceCollision.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -12,18 +12,17 @@ class C2 implements I1, I2 { @Override public void f() {} @Override - public int f(int i) { return 1; } // overloaded + public int f(int i) { return 1; } // Overloaded } class C3 extends C implements I2 { @Override - public int f(int i) { return 1; } // overloaded + public int f(int i) { return 1; } // Overloaded } class C4 extends C implements I3 { // Identical, no problem: - @Override - public int f() { return 1; } + @Override public int f() { return 1; } } // Methods differ only by return type: diff --git a/interfaces/InterfaceWithDefault.java b/interfaces/InterfaceWithDefault.java index 7d59408e1..983beb4b4 100644 --- a/interfaces/InterfaceWithDefault.java +++ b/interfaces/InterfaceWithDefault.java @@ -1,5 +1,5 @@ // interfaces/InterfaceWithDefault.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/Jim.java b/interfaces/Jim.java index 66c0ea7cf..a22f53dd3 100644 --- a/interfaces/Jim.java +++ b/interfaces/Jim.java @@ -1,5 +1,5 @@ // interfaces/Jim.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -17,8 +17,9 @@ default void jim() { } public class Jim implements Jim1, Jim2 { - @Override - public void jim() { Jim2.super.jim(); } + @Override public void jim() { + Jim2.super.jim(); + } public static void main(String[] args) { new Jim().jim(); } diff --git a/interfaces/MICollision.java b/interfaces/MICollision.java index fddfdbd9c..ab1c8090f 100644 --- a/interfaces/MICollision.java +++ b/interfaces/MICollision.java @@ -1,5 +1,5 @@ // interfaces/MICollision.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -37,7 +37,7 @@ default void sam(int i) { } } -// This works because the argument lists are distinct: +// Works because the argument lists are distinct: class Sam implements Sam1, Sam2 {} interface Max1 { diff --git a/interfaces/Machine.java b/interfaces/Machine.java deleted file mode 100644 index 7e1733a9a..000000000 --- a/interfaces/Machine.java +++ /dev/null @@ -1,36 +0,0 @@ -// interfaces/Machine.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -import java.util.*; -import onjava.Operations; - -class Bing implements Operations { - public void execute() { - Operations.show("Bing"); - } -} - -class Crack implements Operations { - public void execute() { - Operations.show("Crack"); - } -} - -class Twist implements Operations { - public void execute() { - Operations.show("Twist"); - } -} - -public class Machine { - public static void main(String[] args) { - Operations.runOps( - new Bing(), new Crack(), new Twist()); - } -} -/* Output: -Bing -Crack -Twist -*/ diff --git a/interfaces/MetalWork.java b/interfaces/MetalWork.java new file mode 100644 index 000000000..071b13ac9 --- /dev/null +++ b/interfaces/MetalWork.java @@ -0,0 +1,39 @@ +// interfaces/MetalWork.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import onjava.Operation; + +class Heat implements Operation { + @Override public void execute() { + Operation.show("Heat"); + } +} + +public class MetalWork { + public static void main(String[] args) { + // Must be defined in a static context + // to access a method reference: + Operation twist = new Operation() { + public void execute() { + Operation.show("Twist"); + } + }; + Operation.runOps( + new Heat(), // [1] + new Operation() { // [2] + public void execute() { + Operation.show("Hammer"); + } + }, + twist::execute, // [3] + () -> Operation.show("Anneal") // [4] + ); + } +} +/* Output: +Heat +Hammer +Twist +Anneal +*/ diff --git a/interfaces/Months.java b/interfaces/Months.java index 75158ed6d..d475340b1 100644 --- a/interfaces/Months.java +++ b/interfaces/Months.java @@ -1,5 +1,5 @@ // interfaces/Months.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using interfaces to create groups of constants diff --git a/interfaces/MultipleInheritance.java b/interfaces/MultipleInheritance.java index 0a7028e7c..e2b96777c 100644 --- a/interfaces/MultipleInheritance.java +++ b/interfaces/MultipleInheritance.java @@ -1,5 +1,5 @@ // interfaces/MultipleInheritance.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/interfaces/NonSealed.java b/interfaces/NonSealed.java new file mode 100644 index 000000000..8bc4b8fae --- /dev/null +++ b/interfaces/NonSealed.java @@ -0,0 +1,11 @@ +// interfaces/NonSealed.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed class Super permits Sub1, Sub2 {} +final class Sub1 extends Super {} +non-sealed class Sub2 extends Super {} +class Any1 extends Sub2 {} +class Any2 extends Sub2 {} diff --git a/interfaces/PermittedSubclasses.java b/interfaces/PermittedSubclasses.java new file mode 100644 index 000000000..73afd6eb7 --- /dev/null +++ b/interfaces/PermittedSubclasses.java @@ -0,0 +1,22 @@ +// interfaces/PermittedSubclasses.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed class Color permits Red, Green, Blue {} +final class Red extends Color {} +final class Green extends Color {} +final class Blue extends Color {} + +public class PermittedSubclasses { + public static void main(String[] args) { + for(var p: Color.class.getPermittedSubclasses()) + System.out.println(p.getSimpleName()); + } +} +/* Output: +Red +Green +Blue +*/ diff --git a/interfaces/PrivateInterfaceMethods.java b/interfaces/PrivateInterfaceMethods.java new file mode 100644 index 000000000..ebad9bd5b --- /dev/null +++ b/interfaces/PrivateInterfaceMethods.java @@ -0,0 +1,54 @@ +// interfaces/PrivateInterfaceMethods.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 9 + +interface Old { + default void fd() { + System.out.println("Old::fd()"); + } + static void fs() { + System.out.println("Old::fs()"); + } + default void f() { + fd(); + } + static void g() { + fs(); + } +} + +class ImplOld implements Old {} + +interface JDK9 { + private void fd() { // Automatically default + System.out.println("JDK9::fd()"); + } + private static void fs() { + System.out.println("JDK9::fs()"); + } + default void f() { + fd(); + } + static void g() { + fs(); + } +} + +class ImplJDK9 implements JDK9 {} + +public class PrivateInterfaceMethods { + public static void main(String[] args) { + new ImplOld().f(); + Old.g(); + new ImplJDK9().f(); + JDK9.g(); + } +} +/* Output: +Old::fd() +Old::fs() +JDK9::fd() +JDK9::fs() +*/ diff --git a/interfaces/PureInterface.java b/interfaces/PureInterface.java index b795fdccb..ef7732be1 100644 --- a/interfaces/PureInterface.java +++ b/interfaces/PureInterface.java @@ -1,5 +1,5 @@ // interfaces/PureInterface.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Interface only looked like this before Java 8 diff --git a/interfaces/RandVals.java b/interfaces/RandVals.java index fc2516f33..449ae3f0e 100644 --- a/interfaces/RandVals.java +++ b/interfaces/RandVals.java @@ -1,5 +1,5 @@ // interfaces/RandVals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Initializing interface fields with diff --git a/interfaces/RandomDoubles.java b/interfaces/RandomDoubles.java index 7898a023b..afe18dc0a 100644 --- a/interfaces/RandomDoubles.java +++ b/interfaces/RandomDoubles.java @@ -1,5 +1,5 @@ // interfaces/RandomDoubles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/interfaces/RandomStrings.java b/interfaces/RandomStrings.java index b9984011a..da45cf48e 100644 --- a/interfaces/RandomStrings.java +++ b/interfaces/RandomStrings.java @@ -1,5 +1,5 @@ // interfaces/RandomStrings.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Implementing an interface to conform to a method @@ -18,8 +18,7 @@ public class RandomStrings implements Readable { public RandomStrings(int count) { this.count = count; } - @Override - public int read(CharBuffer cb) { + @Override public int read(CharBuffer cb) { if(count-- == 0) return -1; // Indicates end of input cb.append(CAPITALS[rand.nextInt(CAPITALS.length)]); diff --git a/interfaces/SameFile.java b/interfaces/SameFile.java new file mode 100644 index 000000000..e20e93ae7 --- /dev/null +++ b/interfaces/SameFile.java @@ -0,0 +1,9 @@ +// interfaces/SameFile.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed class Shape {} +final class Circle extends Shape {} +final class Triangle extends Shape {} diff --git a/interfaces/Sealed.java b/interfaces/Sealed.java new file mode 100644 index 000000000..5124606c0 --- /dev/null +++ b/interfaces/Sealed.java @@ -0,0 +1,12 @@ +// interfaces/Sealed.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed class Base permits D1, D2 {} + +final class D1 extends Base {} +final class D2 extends Base {} +// Illegal: +// final class D3 extends Base {} diff --git a/interfaces/SealedCat.java b/interfaces/SealedCat.java new file mode 100644 index 000000000..0356ccac8 --- /dev/null +++ b/interfaces/SealedCat.java @@ -0,0 +1,6 @@ +// interfaces/SealedCat.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 +final class Cat extends Pet {} diff --git a/interfaces/SealedDog.java b/interfaces/SealedDog.java new file mode 100644 index 000000000..f0441afde --- /dev/null +++ b/interfaces/SealedDog.java @@ -0,0 +1,6 @@ +// interfaces/SealedDog.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 +final class Dog extends Pet {} diff --git a/interfaces/SealedInterface.java b/interfaces/SealedInterface.java new file mode 100644 index 000000000..315517bb1 --- /dev/null +++ b/interfaces/SealedInterface.java @@ -0,0 +1,12 @@ +// interfaces/SealedInterface.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed interface Ifc permits Imp1, Imp2 {} +final class Imp1 implements Ifc {} +final class Imp2 implements Ifc {} + +sealed abstract class AC permits X {} +final class X extends AC {} diff --git a/interfaces/SealedPets.java b/interfaces/SealedPets.java new file mode 100644 index 000000000..79ab9e5bc --- /dev/null +++ b/interfaces/SealedPets.java @@ -0,0 +1,6 @@ +// interfaces/SealedPets.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 +sealed class Pet permits Dog, Cat {} diff --git a/interfaces/SealedRecords.java b/interfaces/SealedRecords.java new file mode 100644 index 000000000..c1fd7b7eb --- /dev/null +++ b/interfaces/SealedRecords.java @@ -0,0 +1,12 @@ +// interfaces/SealedRecords.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed interface Employee + permits CLevel, Programmer {} +record CLevel(String type) + implements Employee {} +record Programmer(String experience) + implements Employee {} diff --git a/interfaces/SealedSubclasses.java b/interfaces/SealedSubclasses.java new file mode 100644 index 000000000..68b83af3e --- /dev/null +++ b/interfaces/SealedSubclasses.java @@ -0,0 +1,10 @@ +// interfaces/SealedSubclasses.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 17 + +sealed class Bottom permits Level1 {} +sealed class Level1 extends Bottom permits Level2 {} +sealed class Level2 extends Level1 permits Level3 {} +final class Level3 extends Level2 {} diff --git a/interfaces/TestRandVals.java b/interfaces/TestRandVals.java index ff4f60d5c..132d7af89 100644 --- a/interfaces/TestRandVals.java +++ b/interfaces/TestRandVals.java @@ -1,5 +1,5 @@ // interfaces/TestRandVals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/interfaces/filters/BandPass.java b/interfaces/filters/BandPass.java index 8e8367e98..e0e233904 100644 --- a/interfaces/filters/BandPass.java +++ b/interfaces/filters/BandPass.java @@ -1,5 +1,5 @@ // interfaces/filters/BandPass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.filters; diff --git a/interfaces/filters/Filter.java b/interfaces/filters/Filter.java index 5657a0de2..e2d0ae6dc 100644 --- a/interfaces/filters/Filter.java +++ b/interfaces/filters/Filter.java @@ -1,5 +1,5 @@ // interfaces/filters/Filter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.filters; diff --git a/interfaces/filters/HighPass.java b/interfaces/filters/HighPass.java index 07a0e174b..8167e1b8b 100644 --- a/interfaces/filters/HighPass.java +++ b/interfaces/filters/HighPass.java @@ -1,5 +1,5 @@ // interfaces/filters/HighPass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.filters; diff --git a/interfaces/filters/LowPass.java b/interfaces/filters/LowPass.java index d85d7bd79..77bedf515 100644 --- a/interfaces/filters/LowPass.java +++ b/interfaces/filters/LowPass.java @@ -1,5 +1,5 @@ // interfaces/filters/LowPass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.filters; diff --git a/interfaces/filters/Waveform.java b/interfaces/filters/Waveform.java index 3d246c3c0..8262fc102 100644 --- a/interfaces/filters/Waveform.java +++ b/interfaces/filters/Waveform.java @@ -1,5 +1,5 @@ // interfaces/filters/Waveform.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.filters; @@ -7,8 +7,7 @@ public class Waveform { private static long counter; private final long id = counter++; - @Override - public String toString() { + @Override public String toString() { return "Waveform " + id; } } diff --git a/interfaces/interfaceprocessor/Applicator.java b/interfaces/interfaceprocessor/Applicator.java index 15ca1f4af..3b063a473 100644 --- a/interfaces/interfaceprocessor/Applicator.java +++ b/interfaces/interfaceprocessor/Applicator.java @@ -1,5 +1,5 @@ // interfaces/interfaceprocessor/Applicator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.interfaceprocessor; diff --git a/interfaces/interfaceprocessor/FilterProcessor.java b/interfaces/interfaceprocessor/FilterProcessor.java index 45b2ef754..066be331a 100644 --- a/interfaces/interfaceprocessor/FilterProcessor.java +++ b/interfaces/interfaceprocessor/FilterProcessor.java @@ -1,5 +1,5 @@ // interfaces/interfaceprocessor/FilterProcessor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.interfaceprocessor.FilterProcessor} diff --git a/interfaces/interfaceprocessor/Processor.java b/interfaces/interfaceprocessor/Processor.java index d016f25c4..343803194 100644 --- a/interfaces/interfaceprocessor/Processor.java +++ b/interfaces/interfaceprocessor/Processor.java @@ -1,5 +1,5 @@ // interfaces/interfaceprocessor/Processor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package interfaces.interfaceprocessor; diff --git a/interfaces/interfaceprocessor/StringProcessor.java b/interfaces/interfaceprocessor/StringProcessor.java index 553899f50..f97472b7c 100644 --- a/interfaces/interfaceprocessor/StringProcessor.java +++ b/interfaces/interfaceprocessor/StringProcessor.java @@ -1,5 +1,5 @@ // interfaces/interfaceprocessor/StringProcessor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.interfaceprocessor.StringProcessor} @@ -8,11 +8,11 @@ interface StringProcessor extends Processor { @Override - String process(Object input); // [1] - String S = // [2] + String process(Object input); // [1] + String S = // [2] "If she weighs the same as a duck, " + "she's made of wood"; - static void main(String[] args) { // [3] + static void main(String[] args) { // [3] Applicator.apply(new Upcase(), S); Applicator.apply(new Downcase(), S); Applicator.apply(new Splitter(), S); diff --git a/interfaces/music4/Music4.java b/interfaces/music4/Music4.java index 22fcad72f..a875d4c4e 100644 --- a/interfaces/music4/Music4.java +++ b/interfaces/music4/Music4.java @@ -1,5 +1,5 @@ // interfaces/music4/Music4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Abstract classes and methods @@ -15,62 +15,51 @@ abstract class Instrument { } class Wind extends Instrument { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Wind.play() " + n); } - @Override - public String what() { return "Wind"; } - @Override - public void adjust() { + @Override public String what() { return "Wind"; } + @Override public void adjust() { System.out.println("Adjusting Wind"); } } class Percussion extends Instrument { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Percussion.play() " + n); } - @Override - public String what() { return "Percussion"; } - @Override - public void adjust() { + @Override public String what() { + return "Percussion"; + } + @Override public void adjust() { System.out.println("Adjusting Percussion"); } } class Stringed extends Instrument { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Stringed.play() " + n); } - @Override - public String what() { return "Stringed"; } - @Override - public void adjust() { + @Override public String what() { return "Stringed"; } + @Override public void adjust() { System.out.println("Adjusting Stringed"); } } class Brass extends Wind { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Brass.play() " + n); } - @Override - public void adjust() { + @Override public void adjust() { System.out.println("Adjusting Brass"); } } class Woodwind extends Wind { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Woodwind.play() " + n); } - @Override - public String what() { return "Woodwind"; } + @Override public String what() { return "Woodwind"; } } public class Music4 { diff --git a/interfaces/music5/Music5.java b/interfaces/music5/Music5.java index 14bfc9620..775e656b8 100644 --- a/interfaces/music5/Music5.java +++ b/interfaces/music5/Music5.java @@ -1,5 +1,5 @@ // interfaces/music5/Music5.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.music5.Music5} @@ -18,28 +18,33 @@ default void adjust() { } class Wind implements Instrument { - @Override - public String toString() { return "Wind"; } + @Override public String toString() { + return "Wind"; + } } class Percussion implements Instrument { - @Override - public String toString() { return "Percussion"; } + @Override public String toString() { + return "Percussion"; + } } class Stringed implements Instrument { - @Override - public String toString() { return "Stringed"; } + @Override public String toString() { + return "Stringed"; + } } class Brass extends Wind { - @Override - public String toString() { return "Brass"; } + @Override public String toString() { + return "Brass"; + } } class Woodwind extends Wind { - @Override - public String toString() { return "Woodwind"; } + @Override public String toString() { + return "Woodwind"; + } } public class Music5 { diff --git a/interfaces/nesting/NestingInterfaces.java b/interfaces/nesting/NestingInterfaces.java index b728253b3..fa4d482ce 100644 --- a/interfaces/nesting/NestingInterfaces.java +++ b/interfaces/nesting/NestingInterfaces.java @@ -1,5 +1,5 @@ // interfaces/nesting/NestingInterfaces.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.nesting.NestingInterfaces} @@ -10,34 +10,28 @@ interface B { void f(); } public class BImp implements B { - @Override - public void f() {} + @Override public void f() {} } private class BImp2 implements B { - @Override - public void f() {} + @Override public void f() {} } public interface C { void f(); } class CImp implements C { - @Override - public void f() {} + @Override public void f() {} } private class CImp2 implements C { - @Override - public void f() {} + @Override public void f() {} } private interface D { void f(); } private class DImp implements D { - @Override - public void f() {} + @Override public void f() {} } public class DImp2 implements D { - @Override - public void f() {} + @Override public void f() {} } public D getD() { return new DImp2(); } private D dRef; @@ -62,12 +56,10 @@ public interface H { public class NestingInterfaces { public class BImp implements A.B { - @Override - public void f() {} + @Override public void f() {} } class CImp implements A.C { - @Override - public void f() {} + @Override public void f() {} } // Cannot implement a private interface except // within that interface's defining class: @@ -75,19 +67,15 @@ public void f() {} //- public void f() {} //- } class EImp implements E { - @Override - public void g() {} + @Override public void g() {} } class EGImp implements E.G { - @Override - public void f() {} + @Override public void f() {} } class EImp2 implements E { - @Override - public void g() {} + @Override public void g() {} class EG implements E.G { - @Override - public void f() {} + @Override public void f() {} } } public static void main(String[] args) { diff --git a/iostreams/BasicFileOutput.java b/iostreams/BasicFileOutput.java index 8c1184de2..c31cf7f21 100644 --- a/iostreams/BasicFileOutput.java +++ b/iostreams/BasicFileOutput.java @@ -1,5 +1,5 @@ // iostreams/BasicFileOutput.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/iostreams/BufferedInputFile.java b/iostreams/BufferedInputFile.java index 76dc960fa..2c5c8ae7f 100644 --- a/iostreams/BufferedInputFile.java +++ b/iostreams/BufferedInputFile.java @@ -1,5 +1,5 @@ // iostreams/BufferedInputFile.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/iostreams/FileOutputShortcut.java b/iostreams/FileOutputShortcut.java index 7e949a4d0..54d3e0597 100644 --- a/iostreams/FileOutputShortcut.java +++ b/iostreams/FileOutputShortcut.java @@ -1,5 +1,5 @@ // iostreams/FileOutputShortcut.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/iostreams/FormattedMemoryInput.java b/iostreams/FormattedMemoryInput.java index b6b7e3168..f29e75128 100644 --- a/iostreams/FormattedMemoryInput.java +++ b/iostreams/FormattedMemoryInput.java @@ -1,5 +1,5 @@ // iostreams/FormattedMemoryInput.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/iostreams/MemoryInput.java b/iostreams/MemoryInput.java index 4989d0778..db5f8d4f9 100644 --- a/iostreams/MemoryInput.java +++ b/iostreams/MemoryInput.java @@ -1,5 +1,5 @@ // iostreams/MemoryInput.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {VisuallyInspectOutput} diff --git a/iostreams/StoringAndRecoveringData.java b/iostreams/StoringAndRecoveringData.java index 664eecc07..961f418d7 100644 --- a/iostreams/StoringAndRecoveringData.java +++ b/iostreams/StoringAndRecoveringData.java @@ -1,5 +1,5 @@ // iostreams/StoringAndRecoveringData.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/iostreams/TestEOF.java b/iostreams/TestEOF.java index dee0ba18d..a1c939667 100644 --- a/iostreams/TestEOF.java +++ b/iostreams/TestEOF.java @@ -1,5 +1,5 @@ // iostreams/TestEOF.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Testing for end of file diff --git a/iostreams/UsingRandomAccessFile.java b/iostreams/UsingRandomAccessFile.java index 256db78c4..98969a1d2 100644 --- a/iostreams/UsingRandomAccessFile.java +++ b/iostreams/UsingRandomAccessFile.java @@ -1,5 +1,5 @@ // iostreams/UsingRandomAccessFile.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/javadoc/Documentation1.java b/javadoc/Documentation1.java index 906df8dd7..790f69fd5 100644 --- a/javadoc/Documentation1.java +++ b/javadoc/Documentation1.java @@ -1,5 +1,5 @@ // javadoc/Documentation1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. /** A class comment */ diff --git a/javadoc/Documentation2.java b/javadoc/Documentation2.java index a19594726..397009e4c 100644 --- a/javadoc/Documentation2.java +++ b/javadoc/Documentation2.java @@ -1,5 +1,5 @@ // javadoc/Documentation2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. /**
diff --git a/javadoc/Documentation3.java b/javadoc/Documentation3.java
index 34f62ac3d..c48351ea5 100644
--- a/javadoc/Documentation3.java
+++ b/javadoc/Documentation3.java
@@ -1,7 +1,8 @@
 // javadoc/Documentation3.java
-// (c)2017 MindView LLC: see Copyright.txt
+// (c)2021 MindView LLC: see Copyright.txt
 // We make no guarantees that this code is fit for any purpose.
 // Visit http://OnJava8.com for more book information.
+
 /** You can even insert a list:
  * 
    *
  1. Item one @@ -9,4 +10,5 @@ *
  2. Item three *
*/ + public class Documentation3 {} diff --git a/javadoc/HelloDateDoc.java b/javadoc/HelloDateDoc.java index 6c248966e..b6ebe8b47 100644 --- a/javadoc/HelloDateDoc.java +++ b/javadoc/HelloDateDoc.java @@ -1,5 +1,5 @@ // javadoc/HelloDateDoc.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -22,5 +22,5 @@ public static void main(String[] args) { } /* Output: Hello, it's: -Tue May 09 06:07:27 MDT 2017 +Sun Jan 24 08:49:10 MST 2021 */ diff --git a/lowlevel/AtomicEvenProducer.java b/lowlevel/AtomicEvenProducer.java index 806b4503c..d45592c93 100644 --- a/lowlevel/AtomicEvenProducer.java +++ b/lowlevel/AtomicEvenProducer.java @@ -1,5 +1,5 @@ // lowlevel/AtomicEvenProducer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Atomic classes: occasionally useful in regular code @@ -8,8 +8,7 @@ public class AtomicEvenProducer extends IntGenerator { private AtomicInteger currentEvenValue = new AtomicInteger(0); - @Override - public int next() { + @Override public int next() { return currentEvenValue.addAndGet(2); } public static void main(String[] args) { diff --git a/lowlevel/AtomicIntegerTest.java b/lowlevel/AtomicIntegerTest.java index 31c6a106c..a93134a8e 100644 --- a/lowlevel/AtomicIntegerTest.java +++ b/lowlevel/AtomicIntegerTest.java @@ -1,5 +1,5 @@ // lowlevel/AtomicIntegerTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; @@ -10,6 +10,7 @@ public class AtomicIntegerTest extends IntTestable { private AtomicInteger i = new AtomicInteger(0); public int getAsInt() { return i.get(); } + @Override public void evenIncrement() { i.addAndGet(2); } public static void main(String[] args) { Atomicity.test(new AtomicIntegerTest()); diff --git a/lowlevel/AtomicSerialNumbers.java b/lowlevel/AtomicSerialNumbers.java index 53547bccb..ef1cdff51 100644 --- a/lowlevel/AtomicSerialNumbers.java +++ b/lowlevel/AtomicSerialNumbers.java @@ -1,5 +1,5 @@ // lowlevel/AtomicSerialNumbers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.*; @@ -8,7 +8,7 @@ AtomicSerialNumbers extends SerialNumbers { private AtomicInteger serialNumber = new AtomicInteger(); - public synchronized int nextSerialNumber() { + @Override public int nextSerialNumber() { return serialNumber.getAndIncrement(); } public static void main(String[] args) { diff --git a/lowlevel/Atomicity.java b/lowlevel/Atomicity.java index 380a5f1be..f8f01d641 100644 --- a/lowlevel/Atomicity.java +++ b/lowlevel/Atomicity.java @@ -1,5 +1,5 @@ // lowlevel/Atomicity.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/lowlevel/AttemptLocking.java b/lowlevel/AttemptLocking.java index 969143e6c..8632fd58b 100644 --- a/lowlevel/AttemptLocking.java +++ b/lowlevel/AttemptLocking.java @@ -1,5 +1,5 @@ // lowlevel/AttemptLocking.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Locks in the concurrent library allow you diff --git a/lowlevel/CaptureUncaughtException.java b/lowlevel/CaptureUncaughtException.java index b540e341f..90458aee5 100644 --- a/lowlevel/CaptureUncaughtException.java +++ b/lowlevel/CaptureUncaughtException.java @@ -1,12 +1,11 @@ // lowlevel/CaptureUncaughtException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; class ExceptionThread2 implements Runnable { - @Override - public void run() { + @Override public void run() { Thread t = Thread.currentThread(); System.out.println("run() by " + t.getName()); System.out.println( @@ -24,8 +23,7 @@ public void uncaughtException(Thread t, Throwable e) { } class HandlerThreadFactory implements ThreadFactory { - @Override - public Thread newThread(Runnable r) { + @Override public Thread newThread(Runnable r) { System.out.println(this + " creating new Thread"); Thread t = new Thread(r); System.out.println("created " + t); @@ -47,10 +45,10 @@ public static void main(String[] args) { } } /* Output: -HandlerThreadFactory@4e25154f creating new Thread +HandlerThreadFactory@106d69c creating new Thread created Thread[Thread-0,5,main] -eh = MyUncaughtExceptionHandler@70dea4e +eh = MyUncaughtExceptionHandler@52e922 run() by Thread-0 -eh = MyUncaughtExceptionHandler@70dea4e +eh = MyUncaughtExceptionHandler@52e922 caught java.lang.RuntimeException */ diff --git a/lowlevel/CircularSet.java b/lowlevel/CircularSet.java index 8f76fd197..f0ab28334 100644 --- a/lowlevel/CircularSet.java +++ b/lowlevel/CircularSet.java @@ -1,5 +1,5 @@ // lowlevel/CircularSet.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Reuses storage so we don't run out of memory diff --git a/lowlevel/DelayQueueDemo.java b/lowlevel/DelayQueueDemo.java index c0d85b020..bce53a85f 100644 --- a/lowlevel/DelayQueueDemo.java +++ b/lowlevel/DelayQueueDemo.java @@ -1,5 +1,5 @@ // lowlevel/DelayQueueDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -20,24 +20,20 @@ class DelayedTask implements Runnable, Delayed { NANOSECONDS.convert(delta, MILLISECONDS); sequence.add(this); } - @Override - public long getDelay(TimeUnit unit) { + @Override public long getDelay(TimeUnit unit) { return unit.convert( trigger - System.nanoTime(), NANOSECONDS); } - @Override - public int compareTo(Delayed arg) { + @Override public int compareTo(Delayed arg) { DelayedTask that = (DelayedTask)arg; if(trigger < that.trigger) return -1; if(trigger > that.trigger) return 1; return 0; } - @Override - public void run() { + @Override public void run() { System.out.print(this + " "); } - @Override - public String toString() { + @Override public String toString() { return String.format("[%d] Task %d", delta, id); } @@ -46,8 +42,7 @@ public String summary() { } public static class EndTask extends DelayedTask { EndTask(int delay) { super(delay); } - @Override - public void run() { + @Override public void run() { sequence.forEach(dt -> System.out.println(dt.summary())); } @@ -70,7 +65,7 @@ public class DelayQueueDemo { } } /* Output: -[128] Task 12 [429] Task 6 [551] Task 13 [555] Task 2 +[128] Task 12 [429] Task 6 [555] Task 2 [551] Task 13 [693] Task 3 [809] Task 15 [961] Task 5 [1258] Task 1 [1258] Task 20 [1520] Task 19 [1861] Task 4 [1998] Task 17 [2200] Task 8 [2207] Task 10 [2288] Task 11 [2522] diff --git a/lowlevel/EvenChecker.java b/lowlevel/EvenChecker.java index 75c89e0fb..4ba64637e 100644 --- a/lowlevel/EvenChecker.java +++ b/lowlevel/EvenChecker.java @@ -1,5 +1,5 @@ // lowlevel/EvenChecker.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -14,8 +14,7 @@ public EvenChecker(IntGenerator generator, int id) { this.generator = generator; this.id = id; } - @Override - public void run() { + @Override public void run() { while(!generator.isCanceled()) { int val = generator.next(); if(val % 2 != 0) { diff --git a/lowlevel/EvenProducer.java b/lowlevel/EvenProducer.java index adb7153d8..67774aa24 100644 --- a/lowlevel/EvenProducer.java +++ b/lowlevel/EvenProducer.java @@ -1,5 +1,5 @@ // lowlevel/EvenProducer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // When threads collide @@ -7,9 +7,8 @@ public class EvenProducer extends IntGenerator { private int currentEvenValue = 0; - @Override - public int next() { - ++currentEvenValue; // [1] + @Override public int next() { + ++currentEvenValue; // [1] ++currentEvenValue; return currentEvenValue; } diff --git a/lowlevel/ExceptionThread.java b/lowlevel/ExceptionThread.java index 859e86a32..9fee108c9 100644 --- a/lowlevel/ExceptionThread.java +++ b/lowlevel/ExceptionThread.java @@ -1,13 +1,12 @@ // lowlevel/ExceptionThread.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ThrowsException} import java.util.concurrent.*; public class ExceptionThread implements Runnable { - @Override - public void run() { + @Override public void run() { throw new RuntimeException(); } public static void main(String[] args) { @@ -21,7 +20,7 @@ public static void main(String[] args) { ___[ Error Output ]___ Exception in thread "pool-1-thread-1" java.lang.RuntimeException - at ExceptionThread.run(ExceptionThread.java:8) + at ExceptionThread.run(ExceptionThread.java:7) at java.util.concurrent.ThreadPoolExecutor.runW orker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Work diff --git a/lowlevel/IntGenerator.java b/lowlevel/IntGenerator.java index c9714d5d0..a5078a955 100644 --- a/lowlevel/IntGenerator.java +++ b/lowlevel/IntGenerator.java @@ -1,5 +1,5 @@ // lowlevel/IntGenerator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.atomic.AtomicBoolean; diff --git a/lowlevel/IntTestable.java b/lowlevel/IntTestable.java index a2a033fea..bd2f2abde 100644 --- a/lowlevel/IntTestable.java +++ b/lowlevel/IntTestable.java @@ -1,5 +1,5 @@ // lowlevel/IntTestable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; @@ -7,8 +7,7 @@ public abstract class IntTestable implements Runnable, IntSupplier { abstract void evenIncrement(); - @Override - public void run() { + @Override public void run() { while(true) evenIncrement(); } diff --git a/lowlevel/MutexEvenProducer.java b/lowlevel/MutexEvenProducer.java index c3f98866a..24ce0448a 100644 --- a/lowlevel/MutexEvenProducer.java +++ b/lowlevel/MutexEvenProducer.java @@ -1,5 +1,5 @@ // lowlevel/MutexEvenProducer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Preventing thread collisions with mutexes @@ -9,8 +9,7 @@ public class MutexEvenProducer extends IntGenerator { private int currentEvenValue = 0; private Lock lock = new ReentrantLock(); - @Override - public int next() { + @Override public int next() { lock.lock(); try { ++currentEvenValue; diff --git a/lowlevel/NaiveExceptionHandling.java b/lowlevel/NaiveExceptionHandling.java index 14a76d850..efda2778e 100644 --- a/lowlevel/NaiveExceptionHandling.java +++ b/lowlevel/NaiveExceptionHandling.java @@ -1,5 +1,5 @@ // lowlevel/NaiveExceptionHandling.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ThrowsException} @@ -23,7 +23,7 @@ public static void main(String[] args) { ___[ Error Output ]___ Exception in thread "pool-1-thread-1" java.lang.RuntimeException - at ExceptionThread.run(ExceptionThread.java:8) + at ExceptionThread.run(ExceptionThread.java:7) at java.util.concurrent.ThreadPoolExecutor.runW orker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Work diff --git a/lowlevel/NotAtomic.java b/lowlevel/NotAtomic.java index f77eb128f..00a1b0102 100644 --- a/lowlevel/NotAtomic.java +++ b/lowlevel/NotAtomic.java @@ -1,8 +1,9 @@ // lowlevel/NotAtomic.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// {javap -c NotAtomic} +// javap -c NotAtomic +// {ExcludeFromGradle} // {VisuallyInspectOutput} public class NotAtomic { @@ -18,8 +19,7 @@ public class NotAtomic { public NotAtomic(); Code: 0: aload_0 - 1: invokespecial #1 // Method -java/lang/Object."":()V + 1: invokespecial #1 // Method java/lang/Object."":()V 4: return void f1(); diff --git a/lowlevel/NumberOfProcessors.java b/lowlevel/NumberOfProcessors.java index 103d6c1d2..3c3abf81f 100644 --- a/lowlevel/NumberOfProcessors.java +++ b/lowlevel/NumberOfProcessors.java @@ -1,5 +1,5 @@ // lowlevel/NumberOfProcessors.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/lowlevel/PriorityBlockingQueueDemo.java b/lowlevel/PriorityBlockingQueueDemo.java index c62bf46f2..4683ed841 100644 --- a/lowlevel/PriorityBlockingQueueDemo.java +++ b/lowlevel/PriorityBlockingQueueDemo.java @@ -1,5 +1,5 @@ // lowlevel/PriorityBlockingQueueDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -19,13 +19,11 @@ class Prioritized implements Comparable { this.priority = priority; sequence.add(this); } - @Override - public int compareTo(Prioritized arg) { + @Override public int compareTo(Prioritized arg) { return priority < arg.priority ? 1 : (priority > arg.priority ? -1 : 0); } - @Override - public String toString() { + @Override public String toString() { return String.format( "[%d] Prioritized %d", priority, id); } @@ -51,8 +49,7 @@ class Producer implements Runnable { Producer(Queue q) { queue = q; } - @Override - public void run() { + @Override public void run() { rand.ints(10, 0, 20) .mapToObj(Prioritized::new) .peek(p -> new Nap(rand.nextDouble() / 10)) @@ -68,8 +65,7 @@ class Consumer implements Runnable { Consumer(PriorityBlockingQueue q) { this.q = q; } - @Override - public void run() { + @Override public void run() { while(true) { try { Prioritized pt = q.take(); @@ -98,21 +94,21 @@ public static void main(String[] args) { } } /* Output: -[15] Prioritized 2 -[17] Prioritized 1 +[15] Prioritized 1 +[17] Prioritized 0 [17] Prioritized 5 [16] Prioritized 6 [14] Prioritized 9 -[12] Prioritized 0 +[12] Prioritized 2 [11] Prioritized 4 [11] Prioritized 12 [13] Prioritized 13 [12] Prioritized 16 -[14] Prioritized 18 +[14] Prioritized 17 [15] Prioritized 23 [18] Prioritized 26 [16] Prioritized 29 -[12] Prioritized 17 +[12] Prioritized 18 [11] Prioritized 30 [11] Prioritized 24 [10] Prioritized 15 @@ -129,10 +125,10 @@ public static void main(String[] args) { [0] Prioritized 14 [0] Prioritized 21 [-1] Prioritized 28 -(0:12)(2:15)(1:17)(3:1)(4:11) +(0:17)(1:15)(2:12)(3:1)(4:11) (5:17)(6:16)(7:3)(8:0)(9:14) (10:8)(11:8)(12:11)(13:13)(14:0) -(15:10)(16:12)(17:12)(18:14)(19:0) +(15:10)(16:12)(17:14)(18:12)(19:0) (20:2)(21:0)(22:10)(23:15)(24:11) (25:8)(26:18)(27:-1)(28:-1)(29:16) (30:11)(31:6)(32:-1) diff --git a/lowlevel/ReOrdering.java b/lowlevel/ReOrdering.java index 9de9c4b81..77f07469e 100644 --- a/lowlevel/ReOrdering.java +++ b/lowlevel/ReOrdering.java @@ -1,13 +1,12 @@ // lowlevel/ReOrdering.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class ReOrdering implements Runnable { int one, two, three, four, five, six; volatile int volaTile; - @Override - public void run() { + @Override public void run() { one = 1; two = 2; three = 3; diff --git a/lowlevel/SafeReturn.java b/lowlevel/SafeReturn.java index 829a1f98e..70d21454e 100644 --- a/lowlevel/SafeReturn.java +++ b/lowlevel/SafeReturn.java @@ -1,5 +1,5 @@ // lowlevel/SafeReturn.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; @@ -8,6 +8,7 @@ public class SafeReturn extends IntTestable { private int i = 0; public synchronized int getAsInt() { return i; } + @Override public synchronized void evenIncrement() { i++; i++; } diff --git a/lowlevel/SerialNumberChecker.java b/lowlevel/SerialNumberChecker.java index 72ab795f0..d539411ee 100644 --- a/lowlevel/SerialNumberChecker.java +++ b/lowlevel/SerialNumberChecker.java @@ -1,5 +1,5 @@ // lowlevel/SerialNumberChecker.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Test SerialNumbers implementations for thread-safety @@ -12,8 +12,7 @@ public class SerialNumberChecker implements Runnable { public SerialNumberChecker(SerialNumbers producer) { this.producer = producer; } - @Override - public void run() { + @Override public void run() { while(true) { int serial = producer.nextSerialNumber(); if(serials.contains(serial)) { diff --git a/lowlevel/SerialNumberTest.java b/lowlevel/SerialNumberTest.java index 7da47cd8d..9c740d259 100644 --- a/lowlevel/SerialNumberTest.java +++ b/lowlevel/SerialNumberTest.java @@ -1,5 +1,5 @@ // lowlevel/SerialNumberTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,5 +9,8 @@ public static void main(String[] args) { } } /* Output: -Duplicate: 148044 +Duplicate: 33280 +Duplicate: 33278 +Duplicate: 33290 +Duplicate: 33277 */ diff --git a/lowlevel/SerialNumbers.java b/lowlevel/SerialNumbers.java index bf046b7ae..aaaf74bda 100644 --- a/lowlevel/SerialNumbers.java +++ b/lowlevel/SerialNumbers.java @@ -1,5 +1,5 @@ // lowlevel/SerialNumbers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/lowlevel/SettingDefaultHandler.java b/lowlevel/SettingDefaultHandler.java index 9b13362bf..7fe2d5c8a 100644 --- a/lowlevel/SettingDefaultHandler.java +++ b/lowlevel/SettingDefaultHandler.java @@ -1,5 +1,5 @@ // lowlevel/SettingDefaultHandler.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/lowlevel/SwallowedException.java b/lowlevel/SwallowedException.java index 33c824306..7f70f0cb4 100644 --- a/lowlevel/SwallowedException.java +++ b/lowlevel/SwallowedException.java @@ -1,5 +1,5 @@ // lowlevel/SwallowedException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.concurrent.*; diff --git a/lowlevel/SyncOnObject.java b/lowlevel/SyncOnObject.java index 0d0ff1526..d81ad9f4b 100644 --- a/lowlevel/SyncOnObject.java +++ b/lowlevel/SyncOnObject.java @@ -1,5 +1,5 @@ // lowlevel/SyncOnObject.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Synchronizing on another object diff --git a/lowlevel/SynchronizedComparison.java b/lowlevel/SynchronizedComparison.java index 11afebd2d..274f1f0b3 100644 --- a/lowlevel/SynchronizedComparison.java +++ b/lowlevel/SynchronizedComparison.java @@ -1,5 +1,5 @@ // lowlevel/SynchronizedComparison.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Synchronizing blocks instead of entire methods @@ -13,22 +13,21 @@ abstract class Guarded { AtomicLong callCount = new AtomicLong(); public abstract void method(); - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName() + ": " + callCount.get(); } } class SynchronizedMethod extends Guarded { - public synchronized void method() { + @Override public synchronized void method() { new Nap(0.01); callCount.incrementAndGet(); } } class CriticalSection extends Guarded { - public void method() { + @Override public void method() { new Nap(0.01); synchronized(this) { callCount.incrementAndGet(); @@ -43,8 +42,7 @@ class Caller implements Runnable { new AtomicLong(); private AtomicBoolean stop = new AtomicBoolean(false); - @Override - public void run() { + @Override public void run() { new Timer().schedule(new TimerTask() { public void run() { stop.set(true); } }, 2500); @@ -76,14 +74,14 @@ public static void main(String[] args) { } } /* Output: --> 243 --> 243 --> 243 --> 243 -CriticalSection: 972 --> 69 --> 61 --> 83 --> 36 -SynchronizedMethod: 249 +-> 159 +-> 159 +-> 159 +-> 159 +CriticalSection: 636 +-> 65 +-> 21 +-> 11 +-> 68 +SynchronizedMethod: 165 */ diff --git a/lowlevel/SynchronizedEvenProducer.java b/lowlevel/SynchronizedEvenProducer.java index b6f4f4843..7fb9b06f3 100644 --- a/lowlevel/SynchronizedEvenProducer.java +++ b/lowlevel/SynchronizedEvenProducer.java @@ -1,5 +1,5 @@ // lowlevel/SynchronizedEvenProducer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simplifying mutexes with the synchronized keyword @@ -8,8 +8,7 @@ public class SynchronizedEvenProducer extends IntGenerator { private int currentEvenValue = 0; - @Override - public synchronized int next() { + @Override public synchronized int next() { ++currentEvenValue; new Nap(0.01); // Cause failure faster ++currentEvenValue; diff --git a/lowlevel/SynchronizedSerialNumbers.java b/lowlevel/SynchronizedSerialNumbers.java index fff565e23..c73cd48ee 100644 --- a/lowlevel/SynchronizedSerialNumbers.java +++ b/lowlevel/SynchronizedSerialNumbers.java @@ -1,11 +1,12 @@ // lowlevel/SynchronizedSerialNumbers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class SynchronizedSerialNumbers extends SerialNumbers { private int serialNumber = 0; + @Override public synchronized int nextSerialNumber() { return serialNumber++; } diff --git a/lowlevel/TestAbort.java b/lowlevel/TestAbort.java index c5dc1069d..ae2477e1d 100644 --- a/lowlevel/TestAbort.java +++ b/lowlevel/TestAbort.java @@ -1,5 +1,5 @@ // lowlevel/TestAbort.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/lowlevel/ThreadSize.java b/lowlevel/ThreadSize.java index d518b2ac3..ff6f91fb5 100644 --- a/lowlevel/ThreadSize.java +++ b/lowlevel/ThreadSize.java @@ -1,5 +1,5 @@ // lowlevel/ThreadSize.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromGradle} Takes a long time or hangs @@ -8,8 +8,7 @@ public class ThreadSize { static class Dummy extends Thread { - @Override - public void run() { new Nap(1); } + @Override public void run() { new Nap(1); } } public static void main(String[] args) { ExecutorService exec = diff --git a/lowlevel/UnsafeReturn.java b/lowlevel/UnsafeReturn.java index d8463f32f..964cc3af4 100644 --- a/lowlevel/UnsafeReturn.java +++ b/lowlevel/UnsafeReturn.java @@ -1,5 +1,5 @@ // lowlevel/UnsafeReturn.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; @@ -8,6 +8,7 @@ public class UnsafeReturn extends IntTestable { private int i = 0; public int getAsInt() { return i; } + @Override public synchronized void evenIncrement() { i++; i++; } @@ -16,5 +17,5 @@ public static void main(String[] args) { } } /* Output: -failed with: 79 +failed with: 39 */ diff --git a/lowlevel/WorkStealingPool.java b/lowlevel/WorkStealingPool.java index b488cf2b4..9848b019d 100644 --- a/lowlevel/WorkStealingPool.java +++ b/lowlevel/WorkStealingPool.java @@ -1,13 +1,12 @@ // lowlevel/WorkStealingPool.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; import java.util.concurrent.*; class ShowThread implements Runnable { - @Override - public void run() { + @Override public void run() { System.out.println( Thread.currentThread().getName()); } @@ -28,14 +27,14 @@ public static void main(String[] args) } /* Output: 8 -ForkJoinPool-1-worker-2 ForkJoinPool-1-worker-1 ForkJoinPool-1-worker-2 -ForkJoinPool-1-worker-3 -ForkJoinPool-1-worker-2 ForkJoinPool-1-worker-1 ForkJoinPool-1-worker-3 -ForkJoinPool-1-worker-1 +ForkJoinPool-1-worker-4 ForkJoinPool-1-worker-4 ForkJoinPool-1-worker-2 +ForkJoinPool-1-worker-3 +ForkJoinPool-1-worker-5 +ForkJoinPool-1-worker-1 */ diff --git a/newio/AvailableCharSets.java b/newio/AvailableCharSets.java index b46b3dfb1..bb60164c9 100644 --- a/newio/AvailableCharSets.java +++ b/newio/AvailableCharSets.java @@ -1,5 +1,5 @@ // newio/AvailableCharSets.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Displays Charsets and aliases @@ -33,11 +33,9 @@ public static void main(String[] args) { Extended_UNIX_Code_Packed_Format_for_Japanese, euc_jp, eucjp, x-eucjp EUC-KR: ksc5601-1987, csEUCKR, ksc5601_1987, ksc5601, -5601, -euc_kr, ksc_5601, ks_c_5601-1987, euckr +5601, euc_kr, ksc_5601, ks_c_5601-1987, euckr GB18030: gb18030-2000 GB2312: gb2312, euc-cn, x-EUC-CN, euccn, EUC_CN, -gb2312-80, -gb2312-1980 +gb2312-80, gb2312-1980 ... */ diff --git a/newio/BufferToText.java b/newio/BufferToText.java index 81d541a22..147c8857b 100644 --- a/newio/BufferToText.java +++ b/newio/BufferToText.java @@ -1,5 +1,5 @@ // newio/BufferToText.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Converting text to and from ByteBuffers diff --git a/newio/ChannelCopy.java b/newio/ChannelCopy.java index 6aed504fe..039cecd67 100644 --- a/newio/ChannelCopy.java +++ b/newio/ChannelCopy.java @@ -1,5 +1,5 @@ // newio/ChannelCopy.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Copying a file using channels and buffers diff --git a/newio/Endians.java b/newio/Endians.java index 5ff8d7208..183019e36 100644 --- a/newio/Endians.java +++ b/newio/Endians.java @@ -1,5 +1,5 @@ // newio/Endians.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Endian differences and data storage diff --git a/newio/FileLocking.java b/newio/FileLocking.java index 8a8f776a8..7bd335244 100644 --- a/newio/FileLocking.java +++ b/newio/FileLocking.java @@ -1,5 +1,5 @@ // newio/FileLocking.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.channels.*; diff --git a/newio/GetChannel.java b/newio/GetChannel.java index 73bfe683d..1c16f1274 100644 --- a/newio/GetChannel.java +++ b/newio/GetChannel.java @@ -1,5 +1,5 @@ // newio/GetChannel.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Getting channels from streams diff --git a/newio/GetData.java b/newio/GetData.java index b05073db0..aafbdbad0 100644 --- a/newio/GetData.java +++ b/newio/GetData.java @@ -1,5 +1,5 @@ // newio/GetData.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Getting different representations from a ByteBuffer diff --git a/newio/IntBufferDemo.java b/newio/IntBufferDemo.java index 4b3838856..ae88d9a84 100644 --- a/newio/IntBufferDemo.java +++ b/newio/IntBufferDemo.java @@ -1,5 +1,5 @@ // newio/IntBufferDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Manipulating ints in a ByteBuffer with an IntBuffer diff --git a/newio/LargeMappedFiles.java b/newio/LargeMappedFiles.java index 980896021..dba19f8b5 100644 --- a/newio/LargeMappedFiles.java +++ b/newio/LargeMappedFiles.java @@ -1,5 +1,5 @@ // newio/LargeMappedFiles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating a very large file using mapping diff --git a/newio/LockingMappedFiles.java b/newio/LockingMappedFiles.java index f8ebcb5e3..eec5a46ec 100644 --- a/newio/LockingMappedFiles.java +++ b/newio/LockingMappedFiles.java @@ -1,5 +1,5 @@ // newio/LockingMappedFiles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Locking portions of a mapped file @@ -33,8 +33,7 @@ private static class LockAndModify extends Thread { buff = mbb.slice(); start(); } - @Override - public void run() { + @Override public void run() { try { // Exclusive lock with no overlap: FileLock fl = fc.lock(start, end, false); diff --git a/newio/MappedIO.java b/newio/MappedIO.java index beeadf3c1..f098ae269 100644 --- a/newio/MappedIO.java +++ b/newio/MappedIO.java @@ -1,7 +1,8 @@ // newio/MappedIO.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. +// {ExcludeFromGradle} Runs too long under WSL2 import java.util.*; import java.nio.*; import java.nio.channels.*; @@ -26,8 +27,7 @@ public void runTest() { } private static Tester[] tests = { new Tester("Stream Write") { - @Override - public void test() { + @Override public void test() { try( DataOutputStream dos = new DataOutputStream( @@ -43,8 +43,7 @@ public void test() { } }, new Tester("Mapped Write") { - @Override - public void test() { + @Override public void test() { try( FileChannel fc = new RandomAccessFile("temp.tmp", "rw") @@ -61,8 +60,7 @@ public void test() { } }, new Tester("Stream Read") { - @Override - public void test() { + @Override public void test() { try( DataInputStream dis = new DataInputStream( @@ -77,8 +75,7 @@ public void test() { } }, new Tester("Mapped Read") { - @Override - public void test() { + @Override public void test() { try( FileChannel fc = new FileInputStream( new File("temp.tmp")).getChannel() @@ -94,8 +91,7 @@ public void test() { } }, new Tester("Stream Read/Write") { - @Override - public void test() { + @Override public void test() { try( RandomAccessFile raf = new RandomAccessFile( @@ -112,8 +108,7 @@ public void test() { } }, new Tester("Mapped Read/Write") { - @Override - public void test() { + @Override public void test() { try( FileChannel fc = new RandomAccessFile( new File("temp.tmp"), "rw").getChannel() diff --git a/newio/TransferTo.java b/newio/TransferTo.java index d0cac844f..cafc1dc18 100644 --- a/newio/TransferTo.java +++ b/newio/TransferTo.java @@ -1,5 +1,5 @@ // newio/TransferTo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using transferTo() between channels diff --git a/newio/UsingBuffers.java b/newio/UsingBuffers.java index e4c493992..213132a34 100644 --- a/newio/UsingBuffers.java +++ b/newio/UsingBuffers.java @@ -1,5 +1,5 @@ // newio/UsingBuffers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.*; diff --git a/newio/ViewBuffers.java b/newio/ViewBuffers.java index c199101e1..0806f4df0 100644 --- a/newio/ViewBuffers.java +++ b/newio/ViewBuffers.java @@ -1,5 +1,5 @@ // newio/ViewBuffers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.*; diff --git a/objects/HelloDate.java b/objects/HelloDate.java index fa5b3d2c4..b408b1f48 100644 --- a/objects/HelloDate.java +++ b/objects/HelloDate.java @@ -1,5 +1,5 @@ // objects/HelloDate.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/objects/ShowProperties.java b/objects/ShowProperties.java index dcf7c737b..f61e1aaca 100644 --- a/objects/ShowProperties.java +++ b/objects/ShowProperties.java @@ -1,5 +1,5 @@ // objects/ShowProperties.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -13,14 +13,14 @@ public static void main(String[] args) { } /* Output: (First 20 Lines) -- listing properties -- -java.runtime.name=Java(TM) SE Runtime Environment -sun.boot.library.path=C:\Program -Files\Java\jdk1.8.0_112\jr... -java.vm.version=25.112-b15 +java.runtime.name=OpenJDK Runtime Environment +sun.boot.library.path=C:\Program Files\OpenJDK\java- +se-8u41... +java.vm.version=25.40-b25 java.vm.vendor=Oracle Corporation java.vendor.url=http://java.oracle.com/ path.separator=; -java.vm.name=Java HotSpot(TM) 64-Bit Server VM +java.vm.name=OpenJDK Client VM file.encoding.pkg=sun.io user.script= user.country=US @@ -28,12 +28,12 @@ public static void main(String[] args) { sun.os.patch.level= java.vm.specification.name=Java Virtual Machine Specification -user.dir=C:\Users\Bruce\Documents\GitHub\on-ja... -java.runtime.version=1.8.0_112-b15 +user.dir=C:\Git\OnJava8\ExtractedExamples\objects +java.runtime.version=1.8.0_41-b04 java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment -java.endorsed.dirs=C:\Program -Files\Java\jdk1.8.0_112\jr... -os.arch=amd64 +java.endorsed.dirs=C:\Program Files\OpenJDK\java- +se-8u41... +os.arch=x86 java.io.tmpdir=C:\Users\Bruce\AppData\Local\Temp\ ... */ diff --git a/onjava/ArrayShow.java b/onjava/ArrayShow.java index 4ccc5737d..1e87754b2 100644 --- a/onjava/ArrayShow.java +++ b/onjava/ArrayShow.java @@ -1,5 +1,5 @@ // onjava/ArrayShow.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/BasicSupplier.java b/onjava/BasicSupplier.java index 097375b61..45bb58111 100644 --- a/onjava/BasicSupplier.java +++ b/onjava/BasicSupplier.java @@ -1,22 +1,24 @@ // onjava/BasicSupplier.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Supplier from a class with a no-arg constructor +// Supplier from a class with a zero-argument constructor package onjava; import java.util.function.*; +import java.lang.reflect.InvocationTargetException; public class BasicSupplier implements Supplier { private Class type; public BasicSupplier(Class type) { this.type = type; } - @Override - public T get() { + @Override public T get() { try { // Assumes type is a public class: - return type.newInstance(); + return type.getConstructor().newInstance(); } catch(InstantiationException | + NoSuchMethodException | + InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } diff --git a/onjava/CollectionMethodDifferences.java b/onjava/CollectionMethodDifferences.java index d31a30f93..43262312b 100644 --- a/onjava/CollectionMethodDifferences.java +++ b/onjava/CollectionMethodDifferences.java @@ -1,5 +1,5 @@ // onjava/CollectionMethodDifferences.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.CollectionMethodDifferences} diff --git a/onjava/ConvertTo.java b/onjava/ConvertTo.java index e14697a5b..070723118 100644 --- a/onjava/ConvertTo.java +++ b/onjava/ConvertTo.java @@ -1,5 +1,5 @@ // onjava/ConvertTo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/Count.java b/onjava/Count.java index 1e2f90b5b..e2382f57b 100644 --- a/onjava/Count.java +++ b/onjava/Count.java @@ -1,5 +1,5 @@ // onjava/Count.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Generate incremental values of different types @@ -12,8 +12,7 @@ public interface Count { class Boolean implements Supplier { private boolean b = true; - @Override - public java.lang.Boolean get() { + @Override public java.lang.Boolean get() { b = !b; return java.lang.Boolean.valueOf(b); } @@ -66,8 +65,7 @@ public byte[] array(int sz) { class Character implements Supplier { private int i; - @Override - public java.lang.Character get() { + @Override public java.lang.Character get() { i = (i + 1) % CHARS.length; return CHARS[i]; } @@ -168,8 +166,7 @@ public long[] array(int sz) { class Float implements Supplier { private int i; - @Override - public java.lang.Float get() { + @Override public java.lang.Float get() { return java.lang.Float.valueOf(i++); } public java.lang.Float get(int n) { @@ -193,8 +190,7 @@ public float[] array(int sz) { class Double implements Supplier { private int i; - @Override - public java.lang.Double get() { + @Override public java.lang.Double get() { return java.lang.Double.valueOf(i++); } public java.lang.Double get(int n) { diff --git a/onjava/CountMap.java b/onjava/CountMap.java index c3208e71a..e4f08e7a5 100644 --- a/onjava/CountMap.java +++ b/onjava/CountMap.java @@ -1,5 +1,5 @@ // onjava/CountMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Unlimited-length Map containing sample data @@ -21,31 +21,25 @@ private static String value(int key) { public CountMap(int size) { this.size = size < 0 ? 0 : size; } - @Override - public String get(Object key) { + @Override public String get(Object key) { return value((Integer)key); } private static class Entry implements Map.Entry { int index; Entry(int index) { this.index = index; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof Entry && Objects.equals(index, ((Entry)o).index); } - @Override - public Integer getKey() { return index; } - @Override - public String getValue() { + @Override public Integer getKey() { return index; } + @Override public String getValue() { return value(index); } - @Override - public String setValue(String value) { + @Override public String setValue(String value) { throw new UnsupportedOperationException(); } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hashCode(index); } } diff --git a/onjava/CountingIntegerList.java b/onjava/CountingIntegerList.java index 20e11fa25..d7f73a1b5 100644 --- a/onjava/CountingIntegerList.java +++ b/onjava/CountingIntegerList.java @@ -1,5 +1,5 @@ // onjava/CountingIntegerList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // List of any length, containing sample data @@ -14,12 +14,10 @@ public class CountingIntegerList public CountingIntegerList(int size) { this.size = size < 0 ? 0 : size; } - @Override - public Integer get(int index) { + @Override public Integer get(int index) { return index; } - @Override - public int size() { return size; } + @Override public int size() { return size; } public static void main(String[] args) { List cil = new CountingIntegerList(30); diff --git a/onjava/Countries.java b/onjava/Countries.java index aff022731..666dda293 100644 --- a/onjava/Countries.java +++ b/onjava/Countries.java @@ -1,5 +1,5 @@ // onjava/Countries.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // "Flyweight" Maps and Lists of sample data @@ -130,7 +130,7 @@ public class Countries { {"MOLDOVA","Chisinau"}, {"RUSSIA","Moscow"}, {"TAJIKISTAN","Dushanbe"}, - {"TURKMENISTAN","Ashkabad"}, + {"TURKMENISTAN","Ashkhabad"}, {"UKRAINE","Kyiv"}, {"UZBEKISTAN","Tashkent"}, // Europe @@ -218,23 +218,19 @@ private static class Entry implements Map.Entry { int index; Entry(int index) { this.index = index; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof FlyweightMap && Objects.equals(DATA[index][0], o); } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hashCode(DATA[index][0]); } @Override public String getKey() { return DATA[index][0]; } - @Override - public String getValue() { + @Override public String getValue() { return DATA[index][1]; } - @Override - public String setValue(String value) { + @Override public String setValue(String value) { throw new UnsupportedOperationException(); } } @@ -251,14 +247,12 @@ else if(size > DATA.length) else this.size = size; } - @Override - public int size() { return size; } + @Override public int size() { return size; } private class Iter implements Iterator> { // Only one Entry object per Iterator: private Entry entry = new Entry(-1); - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return entry.index < size - 1; } @Override @@ -266,13 +260,11 @@ public Map.Entry next() { entry.index++; return entry; } - @Override - public void remove() { + @Override public void remove() { throw new UnsupportedOperationException(); } } - @Override - public + @Override public Iterator> iterator() { return new Iter(); } diff --git a/onjava/Enums.java b/onjava/Enums.java index f7df73a2e..2af4b0840 100644 --- a/onjava/Enums.java +++ b/onjava/Enums.java @@ -1,5 +1,5 @@ // onjava/Enums.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/FillMap.java b/onjava/FillMap.java index 9b87bc1f2..4f1650d52 100644 --- a/onjava/FillMap.java +++ b/onjava/FillMap.java @@ -1,5 +1,5 @@ // onjava/FillMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/HTMLColors.java b/onjava/HTMLColors.java index e84b9c90b..7a6421546 100644 --- a/onjava/HTMLColors.java +++ b/onjava/HTMLColors.java @@ -1,5 +1,5 @@ // onjava/HTMLColors.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Sample data for collection examples diff --git a/onjava/MouseClick.java b/onjava/MouseClick.java index 7d57022cd..ea7e530da 100644 --- a/onjava/MouseClick.java +++ b/onjava/MouseClick.java @@ -1,8 +1,8 @@ // onjava/MouseClick.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Helper interface to allow lambda expressions +// Helper interface to allow lambda expressions. package onjava; import java.awt.event.*; diff --git a/onjava/Nap.java b/onjava/Nap.java index ba9df34a2..264d7e69d 100644 --- a/onjava/Nap.java +++ b/onjava/Nap.java @@ -1,5 +1,5 @@ // onjava/Nap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/Null.java b/onjava/Null.java index 4f8659310..9dfae5f2f 100644 --- a/onjava/Null.java +++ b/onjava/Null.java @@ -1,5 +1,5 @@ // onjava/Null.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/OSExecute.java b/onjava/OSExecute.java index 7dc19f616..918f67e77 100644 --- a/onjava/OSExecute.java +++ b/onjava/OSExecute.java @@ -1,5 +1,5 @@ // onjava/OSExecute.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Run an operating system command diff --git a/onjava/OSExecuteException.java b/onjava/OSExecuteException.java index 6a7b13e56..1bf097b89 100644 --- a/onjava/OSExecuteException.java +++ b/onjava/OSExecuteException.java @@ -1,5 +1,5 @@ // onjava/OSExecuteException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/Operations.java b/onjava/Operation.java similarity index 56% rename from onjava/Operations.java rename to onjava/Operation.java index 442dd1acc..f540bb76a 100644 --- a/onjava/Operations.java +++ b/onjava/Operation.java @@ -1,14 +1,13 @@ -// onjava/Operations.java -// (c)2017 MindView LLC: see Copyright.txt +// onjava/Operation.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; -import java.util.*; -public interface Operations { +public interface Operation { void execute(); - static void runOps(Operations... ops) { - for(Operations op : ops) + static void runOps(Operation... ops) { + for(Operation op : ops) op.execute(); } static void show(String msg) { diff --git a/onjava/Pair.java b/onjava/Pair.java index 657aa56bb..6dce28e3e 100644 --- a/onjava/Pair.java +++ b/onjava/Pair.java @@ -1,5 +1,5 @@ // onjava/Pair.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/ProcessFiles.java b/onjava/ProcessFiles.java index 4072d6fc3..af9d5e2e8 100644 --- a/onjava/ProcessFiles.java +++ b/onjava/ProcessFiles.java @@ -1,5 +1,5 @@ // onjava/ProcessFiles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/Rand.java b/onjava/Rand.java index 019bac408..1a589302e 100644 --- a/onjava/Rand.java +++ b/onjava/Rand.java @@ -1,5 +1,5 @@ // onjava/Rand.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Generate random values of different types @@ -13,8 +13,7 @@ public interface Rand { class Boolean implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Boolean get() { + @Override public java.lang.Boolean get() { return r.nextBoolean(); } public java.lang.Boolean get(int n) { @@ -35,8 +34,7 @@ public boolean[] array(int sz) { class Byte implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Byte get() { + @Override public java.lang.Byte get() { return (byte)r.nextInt(MOD); } public java.lang.Byte get(int n) { @@ -57,8 +55,7 @@ public byte[] array(int sz) { class Character implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Character get() { + @Override public java.lang.Character get() { return (char)r.nextInt('a', 'z' + 1); } public java.lang.Character get(int n) { @@ -79,8 +76,7 @@ public char[] array(int sz) { class Short implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Short get() { + @Override public java.lang.Short get() { return (short)r.nextInt(MOD); } public java.lang.Short get(int n) { @@ -101,8 +97,7 @@ public short[] array(int sz) { class Integer implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Integer get() { + @Override public java.lang.Integer get() { return r.nextInt(MOD); } public java.lang.Integer get(int n) { @@ -119,8 +114,7 @@ public java.lang.Integer[] array(int sz) { } class Pint implements IntSupplier { SplittableRandom r = new SplittableRandom(47); - @Override - public int getAsInt() { + @Override public int getAsInt() { return r.nextInt(MOD); } public int get(int n) { return getAsInt(); } @@ -131,8 +125,7 @@ public int[] array(int sz) { class Long implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Long get() { + @Override public java.lang.Long get() { return r.nextLong(MOD); } public java.lang.Long get(int n) { @@ -149,8 +142,7 @@ public java.lang.Long[] array(int sz) { } class Plong implements LongSupplier { SplittableRandom r = new SplittableRandom(47); - @Override - public long getAsLong() { + @Override public long getAsLong() { return r.nextLong(MOD); } public long get(int n) { return getAsLong(); } @@ -161,8 +153,7 @@ public long[] array(int sz) { class Float implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Float get() { + @Override public java.lang.Float get() { return (float)trim(r.nextDouble()); } public java.lang.Float get(int n) { @@ -187,8 +178,7 @@ static double trim(double d) { class Double implements Supplier { SplittableRandom r = new SplittableRandom(47); - @Override - public java.lang.Double get() { + @Override public java.lang.Double get() { return trim(r.nextDouble()); } public java.lang.Double get(int n) { @@ -206,8 +196,7 @@ public java.lang.Double[] array(int sz) { } class Pdouble implements DoubleSupplier { SplittableRandom r = new SplittableRandom(47); - @Override - public double getAsDouble() { + @Override public double getAsDouble() { return trim(r.nextDouble()); } public double get(int n) { @@ -228,8 +217,7 @@ public String() {} public String(int strLength) { strlen = strLength; } - @Override - public java.lang.String get() { + @Override public java.lang.String get() { return r.ints(strlen, 'a', 'z' + 1) .collect(StringBuilder::new, StringBuilder::appendCodePoint, diff --git a/onjava/Range.java b/onjava/Range.java index 05e27fd8d..3003dbd52 100644 --- a/onjava/Range.java +++ b/onjava/Range.java @@ -1,34 +1,30 @@ // onjava/Range.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Array creation methods that can be used without -// qualifiers, using static imports: +// Create arrays initialized with integer values. package onjava; public class Range { - // Produce a sequence [0..n) - public static int[] range(int n) { - int[] result = new int[n]; - for(int i = 0; i < n; i++) - result[i] = i; - return result; - } - // Produce a sequence [start..end) - public static int[] range(int start, int end) { - int sz = end - start; - int[] result = new int[sz]; - for(int i = 0; i < sz; i++) - result[i] = start + i; - return result; - } // Produce sequence [start..end) incrementing by step public static int[] range(int start, int end, int step) { - int sz = (end - start)/step; + if(step == 0) + throw new + IllegalArgumentException("Step cannot be zero"); + int sz = Math.max(0, step >= 0 ? + (end + step - 1 - start) / step + : (end + step + 1 - start) / step); int[] result = new int[sz]; for(int i = 0; i < sz; i++) result[i] = start + (i * step); return result; + } // Produce a sequence [start..end) + public static int[] range(int start, int end) { + return range(start, end, 1); + } + // Produce a sequence [0..n) + public static int[] range(int n) { + return range(0, n); } } diff --git a/onjava/Repeat.java b/onjava/Repeat.java index 59aad0522..11f4cacd8 100644 --- a/onjava/Repeat.java +++ b/onjava/Repeat.java @@ -1,5 +1,5 @@ // onjava/Repeat.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/RmDir.java b/onjava/RmDir.java index f080f8cc3..fa6d1a5e9 100644 --- a/onjava/RmDir.java +++ b/onjava/RmDir.java @@ -1,5 +1,5 @@ // onjava/RmDir.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; @@ -12,15 +12,13 @@ public static void rmdir(Path dir) throws IOException { Files.walkFileTree(dir, new SimpleFileVisitor() { - @Override - public FileVisitResult + @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } - @Override - public FileVisitResult + @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); diff --git a/onjava/Sets.java b/onjava/Sets.java index 71afe50f8..542f5bb30 100644 --- a/onjava/Sets.java +++ b/onjava/Sets.java @@ -1,5 +1,5 @@ // onjava/Sets.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/Stack.java b/onjava/Stack.java index 84b08a4e3..97dc454fa 100644 --- a/onjava/Stack.java +++ b/onjava/Stack.java @@ -1,5 +1,5 @@ // onjava/Stack.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A Stack class built with an ArrayDeque @@ -13,8 +13,7 @@ public class Stack { public T peek() { return storage.peek(); } public T pop() { return storage.pop(); } public boolean isEmpty() { return storage.isEmpty(); } - @Override - public String toString() { + @Override public String toString() { return storage.toString(); } } diff --git a/onjava/Suppliers.java b/onjava/Suppliers.java index c746637a2..05ceafab2 100644 --- a/onjava/Suppliers.java +++ b/onjava/Suppliers.java @@ -1,5 +1,5 @@ // onjava/Suppliers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A utility to use with Suppliers diff --git a/onjava/TestRange.java b/onjava/TestRange.java new file mode 100644 index 000000000..cd132d791 --- /dev/null +++ b/onjava/TestRange.java @@ -0,0 +1,29 @@ +// onjava/TestRange.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Basic test of Range.java +import static onjava.Range.*; +import java.util.Arrays; + +public class TestRange { + private static void show(int[] rng) { + System.out.println(Arrays.toString(rng)); + } + public static void main(String[] args) { + show(range(10, 21, 3)); + show(range(21, 10, -3)); + show(range(-5, 5, -3)); + show(range(-5, 5, 3)); + show(range(10, 21)); + show(range(10)); + } +} +/* Output: +[10, 13, 16, 19] +[21, 18, 15, 12] +[] +[-5, -2, 1, 4] +[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +*/ diff --git a/onjava/TimedAbort.java b/onjava/TimedAbort.java index b378738d4..b9ebeaf89 100644 --- a/onjava/TimedAbort.java +++ b/onjava/TimedAbort.java @@ -1,5 +1,5 @@ // onjava/TimedAbort.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Terminate a program after t seconds diff --git a/onjava/Timer.java b/onjava/Timer.java index e1c3fc9ba..44a24faed 100644 --- a/onjava/Timer.java +++ b/onjava/Timer.java @@ -1,5 +1,5 @@ // onjava/Timer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; diff --git a/onjava/Tuple.java b/onjava/Tuple.java index 05da09f25..d1d9b80cd 100644 --- a/onjava/Tuple.java +++ b/onjava/Tuple.java @@ -1,5 +1,5 @@ // onjava/Tuple.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Tuple library using type argument inference diff --git a/onjava/Tuple2.java b/onjava/Tuple2.java index 862affe74..3e2874a90 100644 --- a/onjava/Tuple2.java +++ b/onjava/Tuple2.java @@ -1,5 +1,5 @@ // onjava/Tuple2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; @@ -9,8 +9,7 @@ public class Tuple2 { public final B a2; public Tuple2(A a, B b) { a1 = a; a2 = b; } public String rep() { return a1 + ", " + a2; } - @Override - public String toString() { + @Override public String toString() { return "(" + rep() + ")"; } } diff --git a/onjava/Tuple3.java b/onjava/Tuple3.java index c7b1007e8..117f4b668 100644 --- a/onjava/Tuple3.java +++ b/onjava/Tuple3.java @@ -1,5 +1,5 @@ // onjava/Tuple3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; @@ -10,8 +10,7 @@ public Tuple3(A a, B b, C c) { super(a, b); a3 = c; } - @Override - public String rep() { + @Override public String rep() { return super.rep() + ", " + a3; } } diff --git a/onjava/Tuple4.java b/onjava/Tuple4.java index 0fdaf2be6..1a62db093 100644 --- a/onjava/Tuple4.java +++ b/onjava/Tuple4.java @@ -1,5 +1,5 @@ // onjava/Tuple4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; @@ -11,8 +11,7 @@ public Tuple4(A a, B b, C c, D d) { super(a, b, c); a4 = d; } - @Override - public String rep() { + @Override public String rep() { return super.rep() + ", " + a4; } } diff --git a/onjava/Tuple5.java b/onjava/Tuple5.java index 58a80c03d..85a3d2d06 100644 --- a/onjava/Tuple5.java +++ b/onjava/Tuple5.java @@ -1,5 +1,5 @@ // onjava/Tuple5.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package onjava; @@ -11,8 +11,7 @@ public Tuple5(A a, B b, C c, D d, E e) { super(a, b, c, d); a5 = e; } - @Override - public String rep() { + @Override public String rep() { return super.rep() + ", " + a5; } } diff --git a/onjava/TypeCounter.java b/onjava/TypeCounter.java index 9c0fae021..6e89067bc 100644 --- a/onjava/TypeCounter.java +++ b/onjava/TypeCounter.java @@ -1,5 +1,5 @@ // onjava/TypeCounter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Counts instances of a type family @@ -26,11 +26,11 @@ private void countClass(Class type) { put(type, quantity == null ? 1 : quantity + 1); Class superClass = type.getSuperclass(); if(superClass != null && - baseType.isAssignableFrom(superClass)) + baseType.isAssignableFrom(superClass)) { countClass(superClass); + } } - @Override - public String toString() { + @Override public String toString() { String result = entrySet().stream() .map(pair -> String.format("%s=%s", pair.getKey().getSimpleName(), diff --git a/onjava/atunit/AtUnit.java b/onjava/atunit/AtUnit.java index fcd19aa45..976010884 100644 --- a/onjava/atunit/AtUnit.java +++ b/onjava/atunit/AtUnit.java @@ -1,5 +1,5 @@ // onjava/atunit/AtUnit.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // An annotation-based unit-test framework @@ -33,8 +33,7 @@ public class AtUnit implements ProcessFiles.Strategy { System.out.println(" " + failed); } } - @Override - public void process(File cFile) { + @Override public void process(File cFile) { try { String cName = ClassNameFinder.thisClass( Files.readAllBytes(cFile.toPath())); @@ -64,11 +63,11 @@ public void process(File cFile) { .getDeclaredConstructor() .getModifiers())) { System.out.println("Error: " + testClass + - " no-arg constructor must be public"); + " zero-argument constructor must be public"); System.exit(1); } } catch(NoSuchMethodException e) { - // Synthesized no-arg constructor; OK + // Synthesized zero-argument constructor; OK } System.out.println(testClass.getName()); } @@ -160,10 +159,13 @@ Method checkForCleanupMethod(Method m) { throw new RuntimeException("Couldn't run " + "@TestObject (creator) method."); } - } else { // Use the no-arg constructor: + } else { // Use the zero-argument constructor: try { - return testClass.newInstance(); + return testClass + .getConstructor().newInstance(); } catch(InstantiationException | + NoSuchMethodException | + InvocationTargetException | IllegalAccessException e) { throw new RuntimeException( "Couldn't create a test object. " + diff --git a/onjava/atunit/ClassNameFinder.java b/onjava/atunit/ClassNameFinder.java index af7f2aef6..315a44c5f 100644 --- a/onjava/atunit/ClassNameFinder.java +++ b/onjava/atunit/ClassNameFinder.java @@ -1,5 +1,5 @@ // onjava/atunit/ClassNameFinder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.atunit.ClassNameFinder} diff --git a/onjava/atunit/Test.java b/onjava/atunit/Test.java index fd4558f6c..ff7b10b9d 100644 --- a/onjava/atunit/Test.java +++ b/onjava/atunit/Test.java @@ -1,5 +1,5 @@ // onjava/atunit/Test.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The @Test tag diff --git a/onjava/atunit/TestObjectCleanup.java b/onjava/atunit/TestObjectCleanup.java index 55937f9cd..c15a0e1a1 100644 --- a/onjava/atunit/TestObjectCleanup.java +++ b/onjava/atunit/TestObjectCleanup.java @@ -1,5 +1,5 @@ // onjava/atunit/TestObjectCleanup.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The @Unit @TestObjectCleanup tag diff --git a/onjava/atunit/TestObjectCreate.java b/onjava/atunit/TestObjectCreate.java index 55c7a73ac..58cf17f9c 100644 --- a/onjava/atunit/TestObjectCreate.java +++ b/onjava/atunit/TestObjectCreate.java @@ -1,5 +1,5 @@ // onjava/atunit/TestObjectCreate.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The @Unit @TestObjectCreate tag diff --git a/onjava/atunit/TestProperty.java b/onjava/atunit/TestProperty.java index e8873fcc8..bbb685adb 100644 --- a/onjava/atunit/TestProperty.java +++ b/onjava/atunit/TestProperty.java @@ -1,5 +1,5 @@ // onjava/atunit/TestProperty.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The @Unit @TestProperty tag diff --git a/operators/AllOps.java b/operators/AllOps.java index 27a62f354..d48e82af1 100644 --- a/operators/AllOps.java +++ b/operators/AllOps.java @@ -1,12 +1,12 @@ // operators/AllOps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Tests all operators on all primitive data types // to show which ones are accepted by the Java compiler public class AllOps { - // To accept the results of a boolean test: + // To accept the results of a Boolean test: void f(boolean b) {} void boolTest(boolean x, boolean y) { // Arithmetic operators: diff --git a/operators/Assignment.java b/operators/Assignment.java index a341f38ff..c4b9a793e 100644 --- a/operators/Assignment.java +++ b/operators/Assignment.java @@ -1,5 +1,5 @@ // operators/Assignment.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Assignment with objects is a bit tricky diff --git a/operators/AutoInc.java b/operators/AutoInc.java index 71309a02d..bcb090935 100644 --- a/operators/AutoInc.java +++ b/operators/AutoInc.java @@ -1,8 +1,8 @@ // operators/AutoInc.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Demonstrates the ++ and -- operators +// The ++ and -- operators public class AutoInc { public static void main(String[] args) { diff --git a/operators/BitManipulation.java b/operators/BitManipulation.java index 2ec1b985c..80c64c93b 100644 --- a/operators/BitManipulation.java +++ b/operators/BitManipulation.java @@ -1,5 +1,5 @@ // operators/BitManipulation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using the bitwise operators diff --git a/operators/Bool.java b/operators/Bool.java index 79c3eac39..42668315b 100644 --- a/operators/Bool.java +++ b/operators/Bool.java @@ -1,5 +1,5 @@ // operators/Bool.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Relational and logical operators diff --git a/operators/Casting.java b/operators/Casting.java index 96ec6c7f8..22b2b221c 100644 --- a/operators/Casting.java +++ b/operators/Casting.java @@ -1,5 +1,5 @@ // operators/Casting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/operators/CastingNumbers.java b/operators/CastingNumbers.java index 2397496ad..007dc4e2c 100644 --- a/operators/CastingNumbers.java +++ b/operators/CastingNumbers.java @@ -1,5 +1,5 @@ // operators/CastingNumbers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // What happens when you cast a float diff --git a/operators/DoubleEquivalence.java b/operators/DoubleEquivalence.java new file mode 100644 index 000000000..5f06e25f5 --- /dev/null +++ b/operators/DoubleEquivalence.java @@ -0,0 +1,49 @@ +// operators/DoubleEquivalence.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class DoubleEquivalence { + static void show(String desc, Double n1, Double n2) { + System.out.println(desc + ":"); + System.out.printf( + "%e==%e %b %b%n", n1, n2, n1 == n2, n1.equals(n2)); + } + @SuppressWarnings("deprecation") + public static void test(double x1, double x2) { + // x1.equals(x2) // Won't compile + System.out.printf("%e==%e %b%n", x1, x2, x1 == x2); + Double d1 = x1; + Double d2 = x2; + show("Automatic", d1, d2); + Double r1 = new Double(x1); + Double r2 = new Double(x2); + show("new Double()", r1, r2); + Double v1 = Double.valueOf(x1); + Double v2 = Double.valueOf(x2); + show("Double.valueOf()", v1, v2); + } + public static void main(String[] args) { + test(0, Double.MIN_VALUE); + System.out.println("------------------------"); + test(Double.MAX_VALUE, + Double.MAX_VALUE - Double.MIN_VALUE * 1_000_000); + } +} +/* Output: +0.000000e+00==4.900000e-324 false +Automatic: +0.000000e+00==4.900000e-324 false false +new Double(): +0.000000e+00==4.900000e-324 false false +Double.valueOf(): +0.000000e+00==4.900000e-324 false false +------------------------ +1.797693e+308==1.797693e+308 true +Automatic: +1.797693e+308==1.797693e+308 false true +new Double(): +1.797693e+308==1.797693e+308 false true +Double.valueOf(): +1.797693e+308==1.797693e+308 false true +*/ diff --git a/operators/EqualsMethod.java b/operators/EqualsMethod.java index 50c5a8ff2..2f281aeb5 100644 --- a/operators/EqualsMethod.java +++ b/operators/EqualsMethod.java @@ -1,15 +1,35 @@ // operators/EqualsMethod.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. +// Default equals() does not compare contents + +class ValA { + int i; +} + +class ValB { + int i; + // Works for this example, not a complete equals(): + public boolean equals(Object o) { + ValB rval = (ValB)o; // Cast o to be a ValB + return i == rval.i; + } +} public class EqualsMethod { public static void main(String[] args) { - Integer n1 = 47; - Integer n2 = 47; - System.out.println(n1.equals(n2)); + ValA va1 = new ValA(); + ValA va2 = new ValA(); + va1.i = va2.i = 100; + System.out.println(va1.equals(va2)); + ValB vb1 = new ValB(); + ValB vb2 = new ValB(); + vb1.i = vb2.i = 100; + System.out.println(vb1.equals(vb2)); } } /* Output: +false true */ diff --git a/operators/EqualsMethod2.java b/operators/EqualsMethod2.java deleted file mode 100644 index 490d3f8cb..000000000 --- a/operators/EqualsMethod2.java +++ /dev/null @@ -1,21 +0,0 @@ -// operators/EqualsMethod2.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Default equals() does not compare contents - -class Value { - int i; -} - -public class EqualsMethod2 { - public static void main(String[] args) { - Value v1 = new Value(); - Value v2 = new Value(); - v1.i = v2.i = 100; - System.out.println(v1.equals(v2)); - } -} -/* Output: -false -*/ diff --git a/operators/Equivalence.java b/operators/Equivalence.java index 268a75be8..dafc49524 100644 --- a/operators/Equivalence.java +++ b/operators/Equivalence.java @@ -1,17 +1,54 @@ // operators/Equivalence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class Equivalence { + static void show(String desc, Integer n1, Integer n2) { + System.out.println(desc + ":"); + System.out.printf( + "%d==%d %b %b%n", n1, n2, n1 == n2, n1.equals(n2)); + } + @SuppressWarnings("deprecation") + public static void test(int value) { + Integer i1 = value; // [1] + Integer i2 = value; + show("Automatic", i1, i2); + // Old way, deprecated since Java 9: + Integer r1 = new Integer(value); // [2] + Integer r2 = new Integer(value); + show("new Integer()", r1, r2); + // Preferred since Java 9: + Integer v1 = Integer.valueOf(value); // [3] + Integer v2 = Integer.valueOf(value); + show("Integer.valueOf()", v1, v2); + // Primitives can't use equals(): + int x = value; // [4] + int y = value; + // x.equals(y); // Doesn't compile + System.out.println("Primitive int:"); + System.out.printf("%d==%d %b%n", x, y, x == y); + } public static void main(String[] args) { - Integer n1 = 47; - Integer n2 = 47; - System.out.println(n1 == n2); - System.out.println(n1 != n2); + test(127); + test(128); } } /* Output: -true -false +Automatic: +127==127 true true +new Integer(): +127==127 false true +Integer.valueOf(): +127==127 true true +Primitive int: +127==127 true +Automatic: +128==128 false true +new Integer(): +128==128 false true +Integer.valueOf(): +128==128 false true +Primitive int: +128==128 true */ diff --git a/operators/Exponents.java b/operators/Exponents.java index 1f7269cb3..8578aee51 100644 --- a/operators/Exponents.java +++ b/operators/Exponents.java @@ -1,5 +1,5 @@ // operators/Exponents.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // "e" means "10 to the power." diff --git a/operators/Literals.java b/operators/Literals.java index dbf19822d..67232c222 100644 --- a/operators/Literals.java +++ b/operators/Literals.java @@ -1,5 +1,5 @@ // operators/Literals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -17,7 +17,7 @@ public static void main(String[] args) { char c = 0xffff; // max char hex value System.out.println( "c: " + Integer.toBinaryString(c)); - byte b = 0x7f; // max byte hex value 10101111; + byte b = 0x7f; // max byte hex value 0111111; System.out.println( "b: " + Integer.toBinaryString(b)); short s = 0x7fff; // max short hex value diff --git a/operators/MathOps.java b/operators/MathOps.java index 32587fd74..125b312b8 100644 --- a/operators/MathOps.java +++ b/operators/MathOps.java @@ -1,5 +1,5 @@ // operators/MathOps.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The mathematical operators diff --git a/operators/Overflow.java b/operators/Overflow.java index 798d849e8..68e494490 100644 --- a/operators/Overflow.java +++ b/operators/Overflow.java @@ -1,5 +1,5 @@ // operators/Overflow.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Surprise! Java lets you overflow diff --git a/operators/PassObject.java b/operators/PassObject.java index 153efd857..698771a8d 100644 --- a/operators/PassObject.java +++ b/operators/PassObject.java @@ -1,5 +1,5 @@ // operators/PassObject.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Passing objects to methods might not be diff --git a/operators/Precedence.java b/operators/Precedence.java index f16942c33..e6dcc549c 100644 --- a/operators/Precedence.java +++ b/operators/Precedence.java @@ -1,5 +1,5 @@ // operators/Precedence.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/operators/RoundingNumbers.java b/operators/RoundingNumbers.java index 7ecc68299..e7396c113 100644 --- a/operators/RoundingNumbers.java +++ b/operators/RoundingNumbers.java @@ -1,5 +1,5 @@ // operators/RoundingNumbers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Rounding floats and doubles diff --git a/operators/ShortCircuit.java b/operators/ShortCircuit.java index c60ef20fb..8e611d469 100644 --- a/operators/ShortCircuit.java +++ b/operators/ShortCircuit.java @@ -1,5 +1,5 @@ // operators/ShortCircuit.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Short-circuiting behavior with logical operators diff --git a/operators/StringOperators.java b/operators/StringOperators.java index 1719fae58..c83387f9e 100644 --- a/operators/StringOperators.java +++ b/operators/StringOperators.java @@ -1,5 +1,5 @@ // operators/StringOperators.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/operators/TernaryIfElse.java b/operators/TernaryIfElse.java index 53361557a..51455aa74 100644 --- a/operators/TernaryIfElse.java +++ b/operators/TernaryIfElse.java @@ -1,5 +1,5 @@ // operators/TernaryIfElse.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/operators/URShift.java b/operators/URShift.java index 46bdbaa82..7596408cd 100644 --- a/operators/URShift.java +++ b/operators/URShift.java @@ -1,5 +1,5 @@ // operators/URShift.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Test of unsigned right shift @@ -30,8 +30,7 @@ public static void main(String[] args) { /* Output: 11111111111111111111111111111111 1111111111111111111111 -1111111111111111111111111111111111111111111111111111111 -111111111 +1111111111111111111111111111111111111111111111111111111111111111 111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 diff --git a/operators/Underscores.java b/operators/Underscores.java index cd862fb88..fa1394893 100644 --- a/operators/Underscores.java +++ b/operators/Underscores.java @@ -1,5 +1,5 @@ // operators/Underscores.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,7 +9,7 @@ public static void main(String[] args) { System.out.println(d); int bin = 0b0010_1111_1010_1111_1010_1111_1010_1111; System.out.println(Integer.toBinaryString(bin)); - System.out.printf("%x%n", bin); // [1] + System.out.printf("%x%n", bin); // [1] long hex = 0x7f_e9_b7_aa; System.out.printf("%x%n", hex); } diff --git a/patterns/BoxObserver.java b/patterns/BoxObserver.java index 0076eac21..b48120bc1 100644 --- a/patterns/BoxObserver.java +++ b/patterns/BoxObserver.java @@ -1,10 +1,10 @@ // patterns/BoxObserver.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Demonstration of Observer pattern using -// Java's built-in observer classes -// {ExcludeFromTravisCI} +// Demonstration of the Observer pattern using +// Java's built-in observer classes. +// {ExcludeFromGradle} // Won't work under WSL2 import javax.swing.*; import java.awt.*; import java.awt.event.*; @@ -12,42 +12,34 @@ import onjava.*; import onjava.MouseClick; -// You must inherit a new type of Observable: -class BoxObservable extends Observable { - @Override - public void notifyObservers(Object b) { - // Otherwise it won't propagate changes: - setChanged(); - super.notifyObservers(b); - } -} - -public class BoxObserver extends JFrame { - Observable notifier = new BoxObservable(); - public BoxObserver(int grid) { +@SuppressWarnings("deprecation") +class Boxes extends JFrame { + Observable notifier = new Observable() { + @Override + public void notifyObservers(Object b) { + setChanged(); + super.notifyObservers(b); + } + }; + public Boxes(int grid) { setTitle("Demonstrates Observer pattern"); Container cp = getContentPane(); cp.setLayout(new GridLayout(grid, grid)); for(int x = 0; x < grid; x++) for(int y = 0; y < grid; y++) - cp.add(new OCBox(x, y, notifier)); - } - public static void main(String[] args) { - new TimedAbort(4); - int grid = 8; - if(args.length > 0) - grid = Integer.parseInt(args[0]); - JFrame f = new BoxObserver(grid); - f.setSize(500, 400); - f.setVisible(true); - f.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + cp.add(new Box(x, y, notifier)); + setSize(500, 400); + setVisible(true); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); } } -class OCBox extends JPanel implements Observer { - Observable notifier; - int x, y; // Locations in grid - Color cColor = newColor(); +@SuppressWarnings("deprecation") +class Box extends JPanel implements Observer { + int x, y; // Location in grid + Color color = COLORS[ + (int)(Math.random() * COLORS.length) + ]; static final Color[] COLORS = { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, @@ -55,36 +47,38 @@ class OCBox extends JPanel implements Observer { Color.orange, Color.pink, Color.red, Color.white, Color.yellow }; - static Color newColor() { - return COLORS[ - (int)(Math.random() * COLORS.length) - ]; - } - OCBox(int x, int y, Observable notifier) { + Box(int x, int y, Observable notifier) { this.x = x; this.y = y; notifier.addObserver(this); - this.notifier = notifier; addMouseListener((MouseClick) - e -> notifier.notifyObservers(OCBox.this)); + e -> notifier.notifyObservers(Box.this)); } - @Override - public void paintComponent(Graphics g) { + @Override public void paintComponent(Graphics g) { super.paintComponent(g); - g.setColor(cColor); + g.setColor(color); Dimension s = getSize(); g.fillRect(0, 0, s.width, s.height); } @Override public void update(Observable o, Object arg) { - OCBox clicked = (OCBox)arg; + Box clicked = (Box)arg; if(nextTo(clicked)) { - cColor = clicked.cColor; + color = clicked.color; repaint(); } } - private boolean nextTo(OCBox b) { + private boolean nextTo(Box b) { return Math.abs(x - b.x) <= 1 && Math.abs(y - b.y) <= 1; } } + +public class BoxObserver { + public static void main(String[] args) { + int grid = 8; + if(args.length > 0) + grid = Integer.parseInt(args[0]); + new Boxes(grid); + } +} diff --git a/patterns/CleanTheFloor.java b/patterns/CleanTheFloor.java new file mode 100644 index 000000000..8196f44bd --- /dev/null +++ b/patterns/CleanTheFloor.java @@ -0,0 +1,42 @@ +// patterns/CleanTheFloor.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// State with different compositional interface. + +class FloorCleaner { + private Attachment attachment = new Vacuum(); + public void change(Attachment newAttachment) { + attachment = newAttachment; + } + public void clean() { attachment.action(); } +} + +interface Attachment { + void action(); +} + +class Vacuum implements Attachment { + @Override public void action() { + System.out.println("Vacuuming"); + } +} + +class Mop implements Attachment { + @Override public void action() { + System.out.println("Mopping"); + } +} + +public class CleanTheFloor { + public static void main(String[] args) { + FloorCleaner floorCleaner = new FloorCleaner(); + floorCleaner.clean(); + floorCleaner.change(new Mop()); + floorCleaner.clean(); + } +} +/* Output: +Vacuuming +Mopping +*/ diff --git a/patterns/CommandPattern.java b/patterns/CommandPattern.java index 277b1fb9f..05bc61202 100644 --- a/patterns/CommandPattern.java +++ b/patterns/CommandPattern.java @@ -1,19 +1,26 @@ // patterns/CommandPattern.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; +class Command { + public final String msg; + public Command(String msg) { + this.msg = msg; + } +} + public class CommandPattern { + public static void show(Command cmd) { + System.out.println(cmd.msg); + } public static void main(String[] args) { - List macro = Arrays.asList( - () -> System.out.print("Hello "), - () -> System.out.print("World! "), - () -> System.out.print("I'm the command pattern!") - ); - macro.forEach(Runnable::run); + show(new Command("First Command")); + show(new Command("Second Command")); } } /* Output: -Hello World! I'm the command pattern! +First Command +Second Command */ diff --git a/patterns/Facade.java b/patterns/Facade.java index 005acf13f..e290cff43 100644 --- a/patterns/Facade.java +++ b/patterns/Facade.java @@ -1,5 +1,5 @@ // patterns/Facade.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/patterns/Macro.java b/patterns/Macro.java new file mode 100644 index 000000000..586b128ea --- /dev/null +++ b/patterns/Macro.java @@ -0,0 +1,25 @@ +// patterns/Macro.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.*; + +public class Macro { + public static void main(String[] args) { + List macro = new ArrayList<>( + Arrays.asList( + () -> System.out.print("Hello "), + () -> System.out.println("World! ") + )); + macro.forEach(Runnable::run); + macro.add( + () -> System.out.print("I'm the command pattern!") + ); + macro.forEach(Runnable::run); + } +} +/* Output: +Hello World! +Hello World! +I'm the command pattern! +*/ diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java index f5c5e6148..478ac6755 100644 --- a/patterns/PaperScissorsRock.java +++ b/patterns/PaperScissorsRock.java @@ -1,86 +1,20 @@ // patterns/PaperScissorsRock.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Demonstration of multiple dispatching +// Demonstration of multiple dispatching. import java.util.*; import java.util.function.*; import java.util.stream.*; +import enums.Outcome; +import static enums.Outcome.*; +import enums.Item; +import enums.Paper; +import enums.Scissors; +import enums.Rock; import onjava.*; import static onjava.Tuple.*; -enum Outcome { WIN, LOSE, DRAW } - -interface Item { - Outcome compete(Item it); - Outcome eval(Paper p); - Outcome eval(Scissors s); - Outcome eval(Rock r); -} - -class Paper implements Item { - @Override - public Outcome compete(Item it) { - return it.eval(this); - } - @Override - public Outcome eval(Paper p) { - return Outcome.DRAW; - } - @Override - public Outcome eval(Scissors s) { - return Outcome.WIN; - } - @Override - public Outcome eval(Rock r) { - return Outcome.LOSE; - } - @Override - public String toString() { return "Paper"; } -} - -class Scissors implements Item { - @Override - public Outcome compete(Item it) { - return it.eval(this); - } - @Override - public Outcome eval(Paper p) { - return Outcome.LOSE; - } - @Override - public Outcome eval(Scissors s) { - return Outcome.DRAW; - } - @Override - public Outcome eval(Rock r) { - return Outcome.WIN; - } - @Override - public String toString() { return "Scissors"; } -} - -class Rock implements Item { - @Override - public Outcome compete(Item it) { - return it.eval(this); - } - @Override - public Outcome eval(Paper p) { - return Outcome.WIN; - } - @Override - public Outcome eval(Scissors s) { - return Outcome.LOSE; - } - @Override - public Outcome eval(Rock r) { - return Outcome.DRAW; - } - @Override - public String toString() { return "Rock"; } -} - class ItemFactory { static List> items = Arrays.asList( diff --git a/patterns/ProxyDemo.java b/patterns/ProxyDemo.java index 198117adb..31f45aedb 100644 --- a/patterns/ProxyDemo.java +++ b/patterns/ProxyDemo.java @@ -1,8 +1,8 @@ // patterns/ProxyDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Simple demonstration of the Proxy pattern +// Basic demonstration of the Proxy pattern. interface ProxyBase { void f(); @@ -11,10 +11,8 @@ interface ProxyBase { } class Proxy implements ProxyBase { - private ProxyBase implementation; - Proxy() { - implementation = new Implementation(); - } + private ProxyBase implementation = + new Implementation(); // Pass method calls to the implementation: @Override public void f() { implementation.f(); } @@ -25,13 +23,13 @@ class Proxy implements ProxyBase { } class Implementation implements ProxyBase { - public void f() { + @Override public void f() { System.out.println("Implementation.f()"); } - public void g() { + @Override public void g() { System.out.println("Implementation.g()"); } - public void h() { + @Override public void h() { System.out.println("Implementation.h()"); } } diff --git a/patterns/Resource.java b/patterns/Resource.java new file mode 100644 index 000000000..1a8ceda50 --- /dev/null +++ b/patterns/Resource.java @@ -0,0 +1,9 @@ +// patterns/Resource.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public interface Resource { + T get(); + void set(T x); +} diff --git a/patterns/ShapeFactory1.java b/patterns/ShapeFactory1.java index 2a4108879..a47b75b7d 100644 --- a/patterns/ShapeFactory1.java +++ b/patterns/ShapeFactory1.java @@ -1,14 +1,14 @@ // patterns/ShapeFactory1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// A simple static factory method +// A basic static factory method. import java.util.*; import java.util.stream.*; import patterns.shapes.*; public class ShapeFactory1 implements FactoryMethod { - public Shape create(String type) { + @Override public Shape create(String type) { switch(type) { case "Circle": return new Circle(); case "Square": return new Square(); diff --git a/patterns/ShapeFactory2.java b/patterns/ShapeFactory2.java index 0253fc864..552e36306 100644 --- a/patterns/ShapeFactory2.java +++ b/patterns/ShapeFactory2.java @@ -1,5 +1,5 @@ // patterns/ShapeFactory2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -8,9 +8,9 @@ import patterns.shapes.*; public class ShapeFactory2 implements FactoryMethod { - Map factories = + private Map factories = new HashMap<>(); - static Constructor load(String id) { + private static Constructor load(String id) { System.out.println("loading " + id); try { return Class.forName("patterns.shapes." + id) @@ -20,14 +20,12 @@ static Constructor load(String id) { throw new BadShapeCreation(id); } } - public Shape create(String id) { + @Override public Shape create(String id) { try { return (Shape)factories .computeIfAbsent(id, ShapeFactory2::load) .newInstance(); - } catch(InstantiationException | - IllegalAccessException | - InvocationTargetException e) { + } catch(Exception e) { throw new BadShapeCreation(id); } } diff --git a/patterns/ShapeFactory3.java b/patterns/ShapeFactory3.java index 123d27fa4..6571c5362 100644 --- a/patterns/ShapeFactory3.java +++ b/patterns/ShapeFactory3.java @@ -1,8 +1,8 @@ // patterns/ShapeFactory3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Polymorphic factory methods +// Polymorphic factory methods. import java.util.*; import java.util.function.*; import java.util.stream.*; @@ -18,15 +18,16 @@ class RandomShapes implements Supplier { RandomShapes(PolymorphicFactory... factories) { this.factories = factories; } - public Shape get() { - return factories[ - rand.nextInt(factories.length)].create(); + @Override public Shape get() { + return + factories[rand.nextInt(factories.length)] + .create(); } } public class ShapeFactory3 { public static void main(String[] args) { - RandomShapes rs = new RandomShapes( + RandomShapes rs = new RandomShapes( // [1] Circle::new, Square::new, Triangle::new ); Stream.generate(rs) diff --git a/patterns/Single.java b/patterns/Single.java new file mode 100644 index 000000000..6bdb2d6e8 --- /dev/null +++ b/patterns/Single.java @@ -0,0 +1,18 @@ +// patterns/Single.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +@SuppressWarnings("unchecked") +public final class Single { + private static Object single; // [1] + public Single(T val) { + if(single != null) + throw new RuntimeException( + "Attempt to reassign Single<" + + val.getClass().getSimpleName() + ">" + ); + single = val; + } + public T get() { return (T)single; } +} diff --git a/patterns/SingletonPattern.java b/patterns/SingletonPattern.java index f2e46e301..3ed313e6c 100644 --- a/patterns/SingletonPattern.java +++ b/patterns/SingletonPattern.java @@ -1,58 +1,47 @@ // patterns/SingletonPattern.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -interface Resource { - int getValue(); - void setValue(int x); -} - -// Since this isn't inherited from a Cloneable -// base class and cloneability isn't added, -// making it final prevents cloneability from -// being added through inheritance. This also -// implements thread-safe lazy initialization: - -final class Singleton { - private static final class - ResourceImpl implements Resource { - private int i; - private ResourceImpl(int i) { - this.i = i; - } - public synchronized int getValue() { - return i; - } - public synchronized void setValue(int x) { - i = x; - } +final class IntegerSingleton + implements Resource { + private static IntegerSingleton value = + new IntegerSingleton(); + private Integer i = Integer.valueOf(0); + private IntegerSingleton() { + System.out.println("IntegerSingleton()"); } - private static class ResourceHolder { - private static Resource resource = - new ResourceImpl(47); - } - public static Resource getResource() { - return ResourceHolder.resource; + public static IntegerSingleton instance() { + return value; } + @Override public synchronized + Integer get() { return i; } + @Override public synchronized + void set(Integer x) { i = x; } } public class SingletonPattern { + public static void show(Resource r) { + T val = r.get(); + System.out.println(val); + } + public static void put(Resource r, T val) { + r.set(val); + } public static void main(String[] args) { - Resource r = Singleton.getResource(); - System.out.println(r.getValue()); - Resource s2 = Singleton.getResource(); - s2.setValue(9); - System.out.println(r.getValue()); - try { - // Can't do this: compile-time error. - // Singleton s3 = (Singleton)s2.clone(); - } catch(Exception e) { - throw new RuntimeException(e); - } + System.out.println("Inside main()"); + Resource ir = + IntegerSingleton.instance(); + Resource ir2 = + IntegerSingleton.instance(); + show(ir); + put(ir2, Integer.valueOf(9)); + show(ir); } } /* Output: -47 +Inside main() +IntegerSingleton() +0 9 */ diff --git a/patterns/SingletonPattern2.java b/patterns/SingletonPattern2.java new file mode 100644 index 000000000..c02fa9f20 --- /dev/null +++ b/patterns/SingletonPattern2.java @@ -0,0 +1,16 @@ +// patterns/SingletonPattern2.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class SingletonPattern2 { + public static void main(String[] args) { + Single pi = + new Single<>(Double.valueOf(3.14159)); + Double x = pi.get(); + System.out.println(x); + } +} +/* Output: +3.14159 +*/ diff --git a/patterns/SingletonPattern3.java b/patterns/SingletonPattern3.java new file mode 100644 index 000000000..7aee59f08 --- /dev/null +++ b/patterns/SingletonPattern3.java @@ -0,0 +1,33 @@ +// patterns/SingletonPattern3.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +class MyString { + private String s; + public MyString(String s) { + this.s = s; + } + public synchronized + void change(String s) { + this.s = s; + } + @Override public synchronized + String toString() { + return s; + } +} + +public class SingletonPattern3 { + public static void main(String[] args) { + Single x = + new Single<>(new MyString("Hello")); + System.out.println(x.get()); + x.get().change("World!"); + System.out.println(x.get()); + } +} +/* Output: +Hello +World! +*/ diff --git a/patterns/StateDemo.java b/patterns/StateDemo.java index 041b4b98f..e96bac6ff 100644 --- a/patterns/StateDemo.java +++ b/patterns/StateDemo.java @@ -1,86 +1,67 @@ // patterns/StateDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Simple demonstration of the State pattern +// Basic demonstration of the State pattern. -interface StateBase { - void f(); - void g(); - void h(); - void changeImp(StateBase newImp); -} - -class State implements StateBase { - private StateBase implementation; - State(StateBase imp) { +class State { + private State implementation; + protected State() {} + public State(State imp) { implementation = imp; } - @Override - public void changeImp(StateBase newImp) { + public void change(State newImp) { implementation = newImp; } - // Pass method calls to the implementation: - @Override + // Forward method calls to the implementation: public void f() { implementation.f(); } - @Override public void g() { implementation.g(); } - @Override public void h() { implementation.h(); } } -class Implementation1 implements StateBase { - @Override - public void f() { +class Implementation1 extends State { + @Override public void f() { System.out.println("Implementation1.f()"); } - @Override - public void g() { + @Override public void g() { System.out.println("Implementation1.g()"); } - @Override - public void h() { + @Override public void h() { System.out.println("Implementation1.h()"); } - @Override - public void changeImp(StateBase newImp) {} } -class Implementation2 implements StateBase { - @Override - public void f() { +class Implementation2 extends State { + @Override public void f() { System.out.println("Implementation2.f()"); } - @Override - public void g() { + @Override public void g() { System.out.println("Implementation2.g()"); } - @Override - public void h() { + @Override public void h() { System.out.println("Implementation2.h()"); } - @Override - public void changeImp(StateBase newImp) {} } public class StateDemo { - static void test(StateBase b) { - b.f(); - b.g(); - b.h(); + static void test(State s) { + s.f(); + s.g(); + s.h(); } public static void main(String[] args) { - StateBase b = - new State(new Implementation1()); - test(b); - b.changeImp(new Implementation2()); - test(b); + State s = new State(new Implementation1()); + test(s); + System.out.println("Changing implementation"); + s.change(new Implementation2()); + test(s); } } /* Output: Implementation1.f() Implementation1.g() Implementation1.h() +Changing implementation Implementation2.f() Implementation2.g() Implementation2.h() diff --git a/patterns/TemplateMethod.java b/patterns/TemplateMethod.java index 0efbd71ce..e9774e183 100644 --- a/patterns/TemplateMethod.java +++ b/patterns/TemplateMethod.java @@ -1,32 +1,30 @@ // patterns/TemplateMethod.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Simple demonstration of Template Method +// Basic Template Method pattern. import java.util.stream.*; abstract class ApplicationFramework { ApplicationFramework() { templateMethod(); } - abstract void customize1(); - abstract void customize2(); + abstract void customize1(int n); + abstract void customize2(int n); // "private" means automatically "final": private void templateMethod() { IntStream.range(0, 5).forEach( - n -> { customize1(); customize2(); }); + n -> { customize1(n); customize2(n); }); } } -// Create a new "application": +// Create a new application: class MyApp extends ApplicationFramework { - @Override - void customize1() { - System.out.print("Hello "); + @Override void customize1(int n) { + System.out.print("customize1 " + n); } - @Override - void customize2() { - System.out.println("World!"); + @Override void customize2(int n) { + System.out.println(" customize2 " + n); } } @@ -36,9 +34,9 @@ public static void main(String[] args) { } } /* Output: -Hello World! -Hello World! -Hello World! -Hello World! -Hello World! +customize1 0 customize2 0 +customize1 1 customize2 1 +customize1 2 customize2 2 +customize1 3 customize2 3 +customize1 4 customize2 4 */ diff --git a/patterns/TestSingle.java b/patterns/TestSingle.java new file mode 100644 index 000000000..209f06477 --- /dev/null +++ b/patterns/TestSingle.java @@ -0,0 +1,20 @@ +// patterns/TestSingle.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class TestSingle { + public static void main(String[] args) { + Single ss = new Single<>("hello"); + System.out.println(ss.get()); + try { + Single ss2 = new Single<>("world"); + } catch(Exception e) { + System.out.println(e.getMessage()); + } + } +} +/* Output: +hello +Attempt to reassign Single +*/ diff --git a/patterns/TypeMap.java b/patterns/TypeMap.java new file mode 100644 index 000000000..db2f393a7 --- /dev/null +++ b/patterns/TypeMap.java @@ -0,0 +1,21 @@ +// patterns/TypeMap.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Generic TypeMap works for any types. +package patterns; +import java.util.*; +import java.util.stream.*; + +public class TypeMap { + public final Map> map = + new HashMap<>(); + public void add(T o) { + Class type = o.getClass(); + map.computeIfAbsent(type, + k -> new ArrayList()).add(o); + } + public Stream> values() { + return map.values().stream(); + } +} diff --git a/patterns/abstractfactory/GameEnvironment.java b/patterns/abstractfactory/GameEnvironment.java index 16acdc681..51b42d553 100644 --- a/patterns/abstractfactory/GameEnvironment.java +++ b/patterns/abstractfactory/GameEnvironment.java @@ -1,8 +1,8 @@ // patterns/abstractfactory/GameEnvironment.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// An example of the Abstract Factory pattern +// An example of the Abstract Factory pattern. // {java patterns.abstractfactory.GameEnvironment} package patterns.abstractfactory; import java.util.function.*; @@ -23,25 +23,23 @@ public void interactWith(Obstacle ob) { } } -class KungFuGuy implements Player { +class Fighter implements Player { @Override public void interactWith(Obstacle ob) { - System.out.print("KungFuGuy now battles a "); + System.out.print("Fighter now battles a "); ob.action(); } } class Puzzle implements Obstacle { - @Override - public void action() { + @Override public void action() { System.out.println("Puzzle"); } } -class NastyWeapon implements Obstacle { - @Override - public void action() { - System.out.println("NastyWeapon"); +class Weapon implements Obstacle { + @Override public void action() { + System.out.println("Weapon"); } } @@ -60,11 +58,11 @@ class KittiesAndPuzzles } } -class KillAndDismember +class Melee extends GameElementFactory { - KillAndDismember() { - player = KungFuGuy::new; - obstacle = NastyWeapon::new; + Melee() { + player = Fighter::new; + obstacle = Weapon::new; } } @@ -82,15 +80,15 @@ public void play() { public static void main(String[] args) { GameElementFactory kp = new KittiesAndPuzzles(), - kd = new KillAndDismember(); + ml = new Melee(); GameEnvironment g1 = new GameEnvironment(kp), - g2 = new GameEnvironment(kd); + g2 = new GameEnvironment(ml); g1.play(); g2.play(); } } /* Output: Kitty has encountered a Puzzle -KungFuGuy now battles a NastyWeapon +Fighter now battles a Weapon */ diff --git a/patterns/adapt/Adapter.java b/patterns/adapt/Adapter.java index 956740e58..0b3a0919f 100644 --- a/patterns/adapt/Adapter.java +++ b/patterns/adapt/Adapter.java @@ -1,8 +1,8 @@ // patterns/adapt/Adapter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Variations on the Adapter pattern +// Variations on the Adapter pattern. // {java patterns.adapt.Adapter} package patterns.adapt; @@ -20,8 +20,7 @@ class ProxyAdapter implements WhatIWant { ProxyAdapter(WhatIHave wih) { whatIHave = wih; } - @Override - public void f() { + @Override public void f() { // Implement behavior using // methods in WhatIHave: whatIHave.g(); @@ -45,8 +44,7 @@ public void op(WhatIHave wih) { // Approach 3: build adapter into WhatIHave: class WhatIHave2 extends WhatIHave implements WhatIWant { - @Override - public void f() { + @Override public void f() { g(); h(); } @@ -55,8 +53,7 @@ public void f() { // Approach 4: use an inner class: class WhatIHave3 extends WhatIHave { private class InnerAdapter implements WhatIWant{ - @Override - public void f() { + @Override public void f() { g(); h(); } diff --git a/patterns/chain/ChainOfResponsibility.java b/patterns/chain/ChainOfResponsibility.java index 208d52e31..b291c3e00 100644 --- a/patterns/chain/ChainOfResponsibility.java +++ b/patterns/chain/ChainOfResponsibility.java @@ -1,56 +1,33 @@ // patterns/chain/ChainOfResponsibility.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Using the Functional interface // {java patterns.chain.ChainOfResponsibility} package patterns.chain; import java.util.*; import java.util.function.*; -class Result { - boolean success; - List line; - Result(List data) { - success = true; - line = data; - } - Result() { - success = false; - line = Collections.emptyList(); - } -} - -class Fail extends Result {} - interface Algorithm { Result algorithm(List line); } class FindMinima { - public static Result leastSquares(List line) { - System.out.println("LeastSquares.algorithm"); - boolean weSucceed = false; - if(weSucceed) // Actual test/calculation here - return new Result(Arrays.asList(1.1, 2.2)); + public static Result test( + boolean success, String id, double d1, double d2) { + System.out.println(id); + if(success) // Actual test/calculation here + return new Result(Arrays.asList(d1, d2)); else // Try the next one in the chain: - return new Fail(); + return Result.fail; + } + public static Result leastSquares(List line) { + return test(false, "LeastSquares", 1.1, 2.2); } public static Result perturbation(List line) { - System.out.println("Perturbation.algorithm"); - boolean weSucceed = false; - if(weSucceed) // Actual test/calculation here - return new Result(Arrays.asList(3.3, 4.4)); - else - return new Fail(); + return test(false, "Perturbation", 3.3, 4.4); } public static Result bisection(List line) { - System.out.println("Bisection.algorithm"); - boolean weSucceed = true; - if(weSucceed) // Actual test/calculation here - return new Result(Arrays.asList(5.5, 6.6)); - else - return new Fail(); + return test(true, "Bisection", 5.5, 6.6); } static List, Result>> algorithms = Arrays.asList( @@ -65,7 +42,7 @@ public static Result minima(List line) { if(result.success) return result; } - return new Fail(); + return Result.fail; } } @@ -83,8 +60,8 @@ public static void main(String[] args) { } } /* Output: -LeastSquares.algorithm -Perturbation.algorithm -Bisection.algorithm +LeastSquares +Perturbation +Bisection [5.5, 6.6] */ diff --git a/patterns/chain/Result.java b/patterns/chain/Result.java new file mode 100644 index 000000000..dc459b399 --- /dev/null +++ b/patterns/chain/Result.java @@ -0,0 +1,21 @@ +// patterns/chain/Result.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Carries the result or indicates failure. +package patterns.chain; +import java.util.*; + +public class Result { + public final boolean success; + public final List line; + public Result(List data) { + success = true; + line = data; + } + private Result() { + success = false; + line = Collections.emptyList(); + } + public static final Result fail = new Result(); +} diff --git a/patterns/doubledispatch/Aluminum.java b/patterns/doubledispatch/Aluminum.java index b17f1d91f..9f5678b11 100644 --- a/patterns/doubledispatch/Aluminum.java +++ b/patterns/doubledispatch/Aluminum.java @@ -1,14 +1,14 @@ // patterns/doubledispatch/Aluminum.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Aluminum for double dispatching +// Aluminum with double dispatching. package patterns.doubledispatch; import patterns.trash.*; import java.util.*; public class Aluminum extends patterns.trash.Aluminum - implements TypedBinMember { +implements TypedBinMember { public Aluminum(double wt) { super(wt); } @Override public boolean addToBin(List tbins) { diff --git a/patterns/doubledispatch/Cardboard.java b/patterns/doubledispatch/Cardboard.java index c5e9d382d..390292322 100644 --- a/patterns/doubledispatch/Cardboard.java +++ b/patterns/doubledispatch/Cardboard.java @@ -1,14 +1,14 @@ // patterns/doubledispatch/Cardboard.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Cardboard for double dispatching +// Cardboard with double dispatching. package patterns.doubledispatch; import patterns.trash.*; import java.util.*; public class Cardboard extends patterns.trash.Cardboard - implements TypedBinMember { +implements TypedBinMember { public Cardboard(double wt) { super(wt); } @Override public boolean addToBin(List tbins) { diff --git a/patterns/doubledispatch/DoubleDispatch.java b/patterns/doubledispatch/DoubleDispatch.java index 4b82310a2..d1ddfe253 100644 --- a/patterns/doubledispatch/DoubleDispatch.java +++ b/patterns/doubledispatch/DoubleDispatch.java @@ -1,96 +1,106 @@ // patterns/doubledispatch/DoubleDispatch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using multiple dispatching to handle more -// than one unknown type during a method call +// than one unknown type during a method call. // {java patterns.doubledispatch.DoubleDispatch} package patterns.doubledispatch; import patterns.trash.*; import java.util.*; class AluminumBin extends TypedBin { - @Override - public boolean add(Aluminum a) { + public AluminumBin() { super("Aluminum"); } + @Override public boolean add(Aluminum a) { return addIt(a); } } class PaperBin extends TypedBin { - @Override - public boolean add(Paper a) { + public PaperBin() { super("Paper"); } + @Override public boolean add(Paper a) { return addIt(a); } } class GlassBin extends TypedBin { - @Override - public boolean add(Glass a) { + public GlassBin() { super("Glass"); } + @Override public boolean add(Glass a) { return addIt(a); } } class CardboardBin extends TypedBin { - @Override - public boolean add(Cardboard a) { + public CardboardBin() { super("Cardboard"); } + @Override public boolean add(Cardboard a) { return addIt(a); } } class TrashBinSet { - private List binSet = Arrays.asList( - new AluminumBin(), - new PaperBin(), - new GlassBin(), - new CardboardBin() - ); + public final List binSet = + Arrays.asList( + new AluminumBin(), new PaperBin(), + new GlassBin(), new CardboardBin() + ); @SuppressWarnings("unchecked") public void sortIntoBins(List bin) { bin.forEach( aBin -> { TypedBinMember t = (TypedBinMember)aBin; if(!t.addToBin(binSet)) - System.err.println("Couldn't add " + t); + throw new RuntimeException( + "sortIntoBins() couldn't add " + t); }); } - public List binSet() { return binSet; } } public class DoubleDispatch { public static void main(String[] args) { List bin = new ArrayList<>(); - TrashBinSet bins = new TrashBinSet(); - // ParseTrash still works, without changes: ParseTrash.fillBin("doubledispatch", bin); + TrashBinSet bins = new TrashBinSet(); // Sort from the master bin into the // individually-typed bins: bins.sortIntoBins(bin); - // Perform sumValue for each bin... - bins.binSet() - .forEach(tb -> Trash.sumValue(tb.v)); - // ... and for the master bin - Trash.sumValue(bin); + // Sum value of each bin... + bins.binSet.forEach(tb -> + TrashValue.sum(tb.bin(), tb.type)); + // ... and for the master bin: + TrashValue.sum(bin, "Trash"); } } -/* Output: (First and Last 10 Lines) -Loading patterns.doubledispatch.Glass +/* Output: +Loading patterns.doubledispatch.Cardboard Loading patterns.doubledispatch.Paper Loading patterns.doubledispatch.Aluminum -Loading patterns.doubledispatch.Cardboard -weight of patterns.doubledispatch.Aluminum = 89.0 -weight of patterns.doubledispatch.Aluminum = 76.0 -weight of patterns.doubledispatch.Aluminum = 25.0 -weight of patterns.doubledispatch.Aluminum = 34.0 -weight of patterns.doubledispatch.Aluminum = 27.0 -weight of patterns.doubledispatch.Aluminum = 18.0 -...________...________...________...________... -weight of patterns.doubledispatch.Aluminum = 93.0 -weight of patterns.doubledispatch.Glass = 93.0 -weight of patterns.doubledispatch.Paper = 80.0 -weight of patterns.doubledispatch.Glass = 36.0 -weight of patterns.doubledispatch.Glass = 12.0 -weight of patterns.doubledispatch.Glass = 60.0 -weight of patterns.doubledispatch.Paper = 66.0 -weight of patterns.doubledispatch.Aluminum = 36.0 -weight of patterns.doubledispatch.Cardboard = 22.0 -Total value = 1086.0599818825722 +Loading patterns.doubledispatch.Glass +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Total Aluminum value = 13.19 +Paper weight: 8.00 * price: 0.10 = 0.80 +Paper weight: 6.60 * price: 0.10 = 0.66 +Paper weight: 9.10 * price: 0.10 = 0.91 +Total Paper value = 2.37 +Glass weight: 5.40 * price: 0.23 = 1.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Glass value = 3.06 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Total Cardboard value = 0.86 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Paper weight: 8.00 * price: 0.10 = 0.80 +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Glass weight: 5.40 * price: 0.23 = 1.24 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Paper weight: 6.60 * price: 0.10 = 0.66 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Paper weight: 9.10 * price: 0.10 = 0.91 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Trash value = 19.48 */ diff --git a/patterns/doubledispatch/Glass.java b/patterns/doubledispatch/Glass.java index 2f26540a0..c0800cdf2 100644 --- a/patterns/doubledispatch/Glass.java +++ b/patterns/doubledispatch/Glass.java @@ -1,14 +1,14 @@ // patterns/doubledispatch/Glass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Glass for double dispatching +// Glass with double dispatching. package patterns.doubledispatch; import patterns.trash.*; import java.util.*; public class Glass extends patterns.trash.Glass - implements TypedBinMember { +implements TypedBinMember { public Glass(double wt) { super(wt); } @Override public boolean addToBin(List tbins) { diff --git a/patterns/doubledispatch/Paper.java b/patterns/doubledispatch/Paper.java index 47eea3171..de25cab37 100644 --- a/patterns/doubledispatch/Paper.java +++ b/patterns/doubledispatch/Paper.java @@ -1,14 +1,14 @@ // patterns/doubledispatch/Paper.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Paper for double dispatching +// Paper with double dispatching. package patterns.doubledispatch; import patterns.trash.*; import java.util.*; public class Paper extends patterns.trash.Paper - implements TypedBinMember { +implements TypedBinMember { public Paper(double wt) { super(wt); } @Override public boolean addToBin(List tbins) { diff --git a/patterns/doubledispatch/TypedBin.java b/patterns/doubledispatch/TypedBin.java index 72c84e4c5..8484552c4 100644 --- a/patterns/doubledispatch/TypedBin.java +++ b/patterns/doubledispatch/TypedBin.java @@ -1,16 +1,25 @@ // patterns/doubledispatch/TypedBin.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// A List that can grab the right type +// A List that can grab the right type. package patterns.doubledispatch; import patterns.trash.*; import java.util.*; public class TypedBin { - List v = new ArrayList<>(); + private List typedBin = + new ArrayList<>(); + public final String type; + public TypedBin(String type) { + this.type = type; + } + public List bin() { + // Returns a copy of typedBin: + return new ArrayList(typedBin); + } protected boolean addIt(Trash t) { - v.add(t); + typedBin.add(t); return true; } public boolean add(Aluminum a) { diff --git a/patterns/doubledispatch/TypedBinMember.java b/patterns/doubledispatch/TypedBinMember.java index 456d02c01..109745b4f 100644 --- a/patterns/doubledispatch/TypedBinMember.java +++ b/patterns/doubledispatch/TypedBinMember.java @@ -1,14 +1,13 @@ // patterns/doubledispatch/TypedBinMember.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// An interface for adding the double dispatching -// method to the trash hierarchy without -// modifying the original hierarchy +// Adapts the double-dispatching +// method into the trash hierarchy without +// modifying the original hierarchy. package patterns.doubledispatch; import java.util.*; public interface TypedBinMember { - // The new method: boolean addToBin(List bins); } diff --git a/patterns/dynatrash/DynaTrash.java b/patterns/dynatrash/DynaTrash.java deleted file mode 100644 index 59b366407..000000000 --- a/patterns/dynatrash/DynaTrash.java +++ /dev/null @@ -1,74 +0,0 @@ -// patterns/dynatrash/DynaTrash.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Using a Map of Lists and RTTI to automatically -// sort trash into Lists. This solution, despite -// the use of RTTI, is extensible. -// {java patterns.dynatrash.DynaTrash} -package patterns.dynatrash; -import patterns.trash.*; -import java.util.*; -import java.util.stream.*; - -// Generic TypeMap works in any situation: -class TypeMap { - private Map> t = new HashMap<>(); - public void add(T o) { - Class type = o.getClass(); - if(t.containsKey(type)) - t.get(type).add(o); - else { - List v = new ArrayList<>(); - v.add(o); - t.put(type,v); - } - } - public Stream> values() { - return t.values().stream(); - } -} - -// Adapter class for callbacks -// from ParseTrash.fillBin(): -class TypeMapAdapter implements Fillable { - TypeMap map; - TypeMapAdapter(TypeMap tm) { - map = tm; - } - @Override - public void addTrash(Trash t) { map.add(t); } -} - -public class DynaTrash { - @SuppressWarnings("unchecked") - public static void main(String[] args) { - TypeMap bin = new TypeMap<>(); - ParseTrash.fillBin( - "trash", new TypeMapAdapter(bin)); - bin.values().forEach(Trash::sumValue); - } -} -/* Output: (First and Last 10 Lines) -Loading patterns.trash.Glass -Loading patterns.trash.Paper -Loading patterns.trash.Aluminum -Loading patterns.trash.Cardboard -weight of patterns.trash.Paper = 22.0 -weight of patterns.trash.Paper = 11.0 -weight of patterns.trash.Paper = 88.0 -weight of patterns.trash.Paper = 91.0 -weight of patterns.trash.Paper = 80.0 -weight of patterns.trash.Paper = 66.0 -...________...________...________...________... -weight of patterns.trash.Aluminum = 81.0 -weight of patterns.trash.Aluminum = 36.0 -weight of patterns.trash.Aluminum = 93.0 -weight of patterns.trash.Aluminum = 36.0 -Total value = 860.0499778985977 -weight of patterns.trash.Cardboard = 96.0 -weight of patterns.trash.Cardboard = 44.0 -weight of patterns.trash.Cardboard = 12.0 -weight of patterns.trash.Cardboard = 22.0 -Total value = 40.02000072598457 -*/ diff --git a/patterns/observer/ObservedFlower.java b/patterns/observer/ObservedFlower.java index a15e8e35c..acfb0f656 100644 --- a/patterns/observer/ObservedFlower.java +++ b/patterns/observer/ObservedFlower.java @@ -1,78 +1,72 @@ // patterns/observer/ObservedFlower.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Demonstration of "Observer" pattern +// Demonstration of the Observer pattern. // {java patterns.observer.ObservedFlower} package patterns.observer; import java.util.*; +import java.util.function.*; +@SuppressWarnings("deprecation") class Flower { - private boolean isOpen; - private boolean alreadyOpen; - private boolean alreadyClosed; - Flower() { isOpen = false; } - OpenNotifier opening = new OpenNotifier(); - CloseNotifier closing = new CloseNotifier(); - public void open() { // Opens its petals - isOpen = true; - opening.notifyObservers(); - alreadyClosed = false; - } - public void close() { // Closes its petals - isOpen = false; - closing.notifyObservers(); - alreadyOpen = false; - } - class OpenNotifier extends Observable { - @Override - public void notifyObservers() { + private boolean isOpen = false; + private boolean alreadyOpen = false; + private boolean alreadyClosed = false; + Observable opening = new Observable() { + @Override public void notifyObservers() { if(isOpen && !alreadyOpen) { setChanged(); super.notifyObservers(); alreadyOpen = true; } } - } - class CloseNotifier extends Observable{ - @Override - public void notifyObservers() { + }; + Observable closing = new Observable() { + @Override public void notifyObservers() { if(!isOpen && !alreadyClosed) { setChanged(); super.notifyObservers(); alreadyClosed = true; } } + }; + public void open() { // Opens its petals + isOpen = true; + opening.notifyObservers(); + alreadyClosed = false; + } + public void close() { // Closes its petals + isOpen = false; + closing.notifyObservers(); + alreadyOpen = false; } } +@SuppressWarnings("deprecation") class Bee { - private String name; - Bee(String nm) { name = nm; } + private String id; + Bee(String name) { id = name; } // Observe openings: - public Observer openObserver() { - return (ob, a) -> System.out.println( - "Bee " + name + "'s breakfast time!"); - } + public final Observer whenOpened = (ob, a) -> + System.out.println( + "Bee " + id + "'s breakfast time!"); // Observe closings: - public Observer closeObserver() { - return (ob, a) -> System.out.println( - "Bee " + name + "'s bed time!"); - } + public final Observer whenClosed = (ob, a) -> + System.out.println( + "Bee " + id + "'s bed time!"); } +@SuppressWarnings("deprecation") class Hummingbird { - private String name; - Hummingbird(String nm) { name = nm; } - public Observer openObserver() { - return (ob, a) -> System.out.println( - "Hummingbird " + name + - "'s breakfast time!"); - } - public Observer closeObserver() { - return (ob, a) -> System.out.println( - "Hummingbird " + name + "'s bed time!"); - } + private String id; + Hummingbird(String name) { id = name; } + public final Observer whenOpened = (ob, a) -> + System.out.println("Hummingbird " + + id + "'s breakfast time!"); + public final Observer whenClosed = (ob, a) -> + System.out.println("Hummingbird " + + id + "'s bed time!"); } public class ObservedFlower { @@ -84,39 +78,46 @@ public static void main(String[] args) { Hummingbird ha = new Hummingbird("A"), hb = new Hummingbird("B"); - f.opening.addObserver(ha.openObserver()); - f.opening.addObserver(hb.openObserver()); - f.opening.addObserver(ba.openObserver()); - f.opening.addObserver(bb.openObserver()); - f.closing.addObserver(ha.closeObserver()); - f.closing.addObserver(hb.closeObserver()); - f.closing.addObserver(ba.closeObserver()); - f.closing.addObserver(bb.closeObserver()); - // Hummingbird B decides to sleep in: - f.opening.deleteObserver(hb.openObserver()); + f.opening.addObserver(ha.whenOpened); + f.opening.addObserver(hb.whenOpened); + f.opening.addObserver(ba.whenOpened); + f.opening.addObserver(bb.whenOpened); + f.closing.addObserver(ha.whenClosed); + f.closing.addObserver(hb.whenClosed); + f.closing.addObserver(ba.whenClosed); + f.closing.addObserver(bb.whenClosed); + // Hummingbird B decides to sleep in. + // Removing whenOpened stops open updates. + f.opening.deleteObserver(hb.whenOpened); // A change that interests observers: f.open(); - f.open(); // It's already open, no change. - // Bee A doesn't want to go to bed: - f.closing.deleteObserver(ba.closeObserver()); + f.open(); // No effect: it's already open. + System.out.println("---------------"); + // Bee A doesn't want to go to bed. + // Removing whenClosed stops close updates. + f.closing.deleteObserver(ba.whenClosed); f.close(); - f.close(); // It's already closed; no change + System.out.println("+++++++++++++++"); + f.close(); // No effect: it's already closed. + System.out.println("==============="); f.opening.deleteObservers(); - f.open(); - f.close(); + f.open(); // No observers to update. + System.out.println("###############"); + f.close(); // Close observers are still there. } } /* Output: Bee B's breakfast time! Bee A's breakfast time! -Hummingbird B's breakfast time! Hummingbird A's breakfast time! +--------------- Bee B's bed time! -Bee A's bed time! Hummingbird B's bed time! Hummingbird A's bed time! ++++++++++++++++ +=============== +############### Bee B's bed time! -Bee A's bed time! Hummingbird B's bed time! Hummingbird A's bed time! */ diff --git a/patterns/recyclea/RecycleA.java b/patterns/recyclea/RecycleA.java index 702fdb973..483e700ed 100644 --- a/patterns/recyclea/RecycleA.java +++ b/patterns/recyclea/RecycleA.java @@ -1,76 +1,26 @@ // patterns/recyclea/RecycleA.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Recycling with RTTI +// Recycling with reflection. // {java patterns.recyclea.RecycleA} package patterns.recyclea; import java.util.*; import java.util.function.*; import java.util.stream.*; +import patterns.trash.*; -abstract class Trash { - double weight; - Trash(double wt) { weight = wt; } - abstract double value(); - // Sums the value of Trash in a bin: - private static double val; - static void sumValue(List bin) { - val = 0.0f; - bin.forEach( t -> { - // Polymorphism in action: - val += t.weight * t.value(); - System.out.println( - "weight of " + - // Using RTTI to get type - // information about the class: - t.getClass().getSimpleName() + - " = " + t.weight); - }); - System.out.println("Total value = " + val); - } -} - -class Aluminum extends Trash { - static double val = 1.67f; - Aluminum(double wt) { super(wt); } - @Override - double value() { return val; } - static void value(double newval) { - val = newval; - } -} - -class Paper extends Trash { - static double val = 0.10f; - Paper(double wt) { super(wt); } - @Override - double value() { return val; } - static void value(double newval) { - val = newval; - } -} - -class Glass extends Trash { - static double val = 0.23f; - Glass(double wt) { super(wt); } - @Override - double value() { return val; } - static void value(double newval) { - val = newval; - } -} - -class TrashFactory { - static List> ttypes = +class SimpleFactory { + static final + List> constructors = Arrays.asList( Aluminum::new, Paper::new, Glass::new); - static final int SZ = ttypes.size(); + static final int SIZE = constructors.size(); private static SplittableRandom rand = - new SplittableRandom(47); - public static Trash newTrash() { - return ttypes - .get(rand.nextInt(SZ)) + new SplittableRandom(42); + public static Trash random() { + return constructors + .get(rand.nextInt(SIZE)) .apply(rand.nextDouble()); } } @@ -78,50 +28,37 @@ public static Trash newTrash() { public class RecycleA { public static void main(String[] args) { List bin = - Stream.generate(TrashFactory::newTrash) - .limit(25) + Stream.generate(SimpleFactory::random) + .limit(10) .collect(Collectors.toList()); - List glassBin = new ArrayList<>(); - List paperBin = new ArrayList<>(); - List alBin = new ArrayList<>(); - // Sort the Trash: - bin.forEach( t -> { - // RTTI to discover Trash type: - if(t instanceof Aluminum) - alBin.add((Aluminum)t); - if(t instanceof Paper) - paperBin.add((Paper)t); - if(t instanceof Glass) - glassBin.add((Glass)t); - }); - Trash.sumValue(alBin); - Trash.sumValue(paperBin); - Trash.sumValue(glassBin); - Trash.sumValue(bin); + Bins bins = new Bins(bin); + bins.show(); } } -/* Output: (First and Last 11 Lines) -weight of Aluminum = 0.2893030122276371 -weight of Aluminum = 0.1970234961398979 -weight of Aluminum = 0.36295525806274787 -weight of Aluminum = 0.4825532324565849 -weight of Aluminum = 0.8036398273294586 -weight of Aluminum = 0.510430896154935 -weight of Aluminum = 0.6703377164093444 -weight of Aluminum = 0.41477933066243455 -weight of Aluminum = 0.3603022312124007 -weight of Aluminum = 0.43690089841661006 -weight of Aluminum = 0.6708820087907101 -...________...________...________...________... -weight of Aluminum = 0.41477933066243455 -weight of Aluminum = 0.3603022312124007 -weight of Aluminum = 0.43690089841661006 -weight of Glass = 0.5999637765664924 -weight of Glass = 0.7748836191212746 -weight of Paper = 0.5735994548427199 -weight of Glass = 0.5362827750851034 -weight of Aluminum = 0.6708820087907101 -weight of Paper = 0.8370669795210507 -weight of Glass = 0.3397919679731668 -Total value = 9.90671597531968 +/* Output: +Aluminum weight: 0.34 * price: 1.67 = 0.57 +Aluminum weight: 0.62 * price: 1.67 = 1.03 +Aluminum weight: 0.49 * price: 1.67 = 0.82 +Aluminum weight: 0.50 * price: 1.67 = 0.83 +Total Aluminum value = 3.26 +Paper weight: 0.69 * price: 0.10 = 0.07 +Total Paper value = 0.07 +Glass weight: 0.16 * price: 0.23 = 0.04 +Glass weight: 0.87 * price: 0.23 = 0.20 +Glass weight: 0.80 * price: 0.23 = 0.18 +Glass weight: 0.52 * price: 0.23 = 0.12 +Glass weight: 0.20 * price: 0.23 = 0.05 +Total Glass value = 0.59 +Total Cardboard value = 0.00 +Glass weight: 0.16 * price: 0.23 = 0.04 +Aluminum weight: 0.34 * price: 1.67 = 0.57 +Glass weight: 0.87 * price: 0.23 = 0.20 +Glass weight: 0.80 * price: 0.23 = 0.18 +Aluminum weight: 0.62 * price: 1.67 = 1.03 +Aluminum weight: 0.49 * price: 1.67 = 0.82 +Glass weight: 0.52 * price: 0.23 = 0.12 +Glass weight: 0.20 * price: 0.23 = 0.05 +Aluminum weight: 0.50 * price: 1.67 = 0.83 +Paper weight: 0.69 * price: 0.10 = 0.07 +Total Trash value = 3.91 */ diff --git a/patterns/recycleb/RecycleB.java b/patterns/recycleb/RecycleB.java index 19e92f9d2..b65f1db3d 100644 --- a/patterns/recycleb/RecycleB.java +++ b/patterns/recycleb/RecycleB.java @@ -1,5 +1,5 @@ // patterns/recycleb/RecycleB.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java patterns.recycleb.RecycleB} @@ -10,47 +10,43 @@ public class RecycleB { public static void main(String[] args) { List bin = new ArrayList<>(); - // Fill up the Trash bin: ParseTrash.fillBin("trash", bin); - List glassBin = new ArrayList<>(); - List paperBin = new ArrayList<>(); - List alBin = new ArrayList<>(); - // Sort the Trash: - bin.forEach( t -> { - // RTTI to discover Trash type: - if(t instanceof Aluminum) - alBin.add((Aluminum)t); - if(t instanceof Paper) - paperBin.add((Paper)t); - if(t instanceof Glass) - glassBin.add((Glass)t); - }); - Trash.sumValue(alBin); - Trash.sumValue(paperBin); - Trash.sumValue(glassBin); - Trash.sumValue(bin); + Bins bins = new Bins(bin); + bins.show(); } } -/* Output: (First and Last 10 Lines) -Loading patterns.trash.Glass +/* Output: +Loading patterns.trash.Cardboard Loading patterns.trash.Paper Loading patterns.trash.Aluminum -Loading patterns.trash.Cardboard -weight of patterns.trash.Aluminum = 89.0 -weight of patterns.trash.Aluminum = 76.0 -weight of patterns.trash.Aluminum = 25.0 -weight of patterns.trash.Aluminum = 34.0 -weight of patterns.trash.Aluminum = 27.0 -weight of patterns.trash.Aluminum = 18.0 -...________...________...________...________... -weight of patterns.trash.Aluminum = 93.0 -weight of patterns.trash.Glass = 93.0 -weight of patterns.trash.Paper = 80.0 -weight of patterns.trash.Glass = 36.0 -weight of patterns.trash.Glass = 12.0 -weight of patterns.trash.Glass = 60.0 -weight of patterns.trash.Paper = 66.0 -weight of patterns.trash.Aluminum = 36.0 -weight of patterns.trash.Cardboard = 22.0 -Total value = 1086.0599818825722 +Loading patterns.trash.Glass +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Total Aluminum value = 13.19 +Paper weight: 8.00 * price: 0.10 = 0.80 +Paper weight: 6.60 * price: 0.10 = 0.66 +Paper weight: 9.10 * price: 0.10 = 0.91 +Total Paper value = 2.37 +Glass weight: 5.40 * price: 0.23 = 1.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Glass value = 3.06 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Total Cardboard value = 0.86 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Paper weight: 8.00 * price: 0.10 = 0.80 +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Glass weight: 5.40 * price: 0.23 = 1.24 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Paper weight: 6.60 * price: 0.10 = 0.66 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Paper weight: 9.10 * price: 0.10 = 0.91 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Trash value = 19.48 */ diff --git a/patterns/recyclec/RecycleC.java b/patterns/recyclec/RecycleC.java index abdc25d56..611c30907 100644 --- a/patterns/recyclec/RecycleC.java +++ b/patterns/recyclec/RecycleC.java @@ -1,84 +1,106 @@ // patterns/recyclec/RecycleC.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Adding more objects to the recycling problem // {java patterns.recyclec.RecycleC} package patterns.recyclec; import patterns.trash.*; import java.util.*; -// A List that admits only the right type: -class Tbin extends ArrayList { - Class binType; - Tbin(Class type) { - binType = type; +// A List that only admits the right type: +class +TrashBin extends ArrayList { + final Class binType; + TrashBin(Class binType) { + this.binType = binType; } @SuppressWarnings("unchecked") boolean grab(Trash t) { - // Comparing class types: + // Compare class types: if(t.getClass().equals(binType)) { - add((T)t); // Downcast to this TBin's type - return true; // Object grabbed + add((T)t); // Downcast to this TrashBin type + return true; // Trash grabbed } - return false; // Object not grabbed + return false; // Trash not grabbed } } -class TbinList -extends ArrayList> { // [1] - boolean sort(T t) { - for(Tbin ts : this) +class TrashBinList +extends ArrayList> { // [1] + @SuppressWarnings("unchecked") + public TrashBinList(Class... types) { + for(Class type : types) + add(new TrashBin<>(type)); + } + public boolean sort(T t) { + for(TrashBin ts : this) if(ts.grab(t)) return true; - return false; // bin not found for t + return false; // TrashBin not found for t + } + public void sortBin(TrashBin bin) { // [2] + for(T trash : bin) + if(!sort(trash)) + throw new RuntimeException( + "Bin not found for " + trash); } - void sortBin(Tbin bin) { // [2] - for(T aBin : bin) - if(!sort(aBin)) - System.err.println("Bin not found"); + public void show() { + for(TrashBin tbin : this) { + String typeName = tbin.binType.getSimpleName(); + TrashValue.sum(tbin, typeName); + } } } public class RecycleC { - static Tbin bin = new Tbin<>(Trash.class); public static void main(String[] args) { - // Fill up the Trash bin: + TrashBin bin = + new TrashBin<>(Trash.class); ParseTrash.fillBin("trash", bin); - - TbinList trashBins = new TbinList<>(); - trashBins.add(new Tbin<>(Aluminum.class)); - trashBins.add(new Tbin<>(Paper.class)); - trashBins.add(new Tbin<>(Glass.class)); - // add one line here: [*3*] - trashBins.add(new Tbin<>(Cardboard.class)); - - trashBins.sortBin(bin); // [4] - - trashBins.forEach(Trash::sumValue); - Trash.sumValue(bin); + @SuppressWarnings("unchecked") + TrashBinList trashBins = + new TrashBinList<>( + Aluminum.class, Paper.class, Glass.class, + // Add one item: + Cardboard.class // [3] + ); + trashBins.sortBin(bin); // [4] + trashBins.show(); + TrashValue.sum(bin, "Trash"); } } -/* Output: (First and Last 10 Lines) -Loading patterns.trash.Glass +/* Output: +Loading patterns.trash.Cardboard Loading patterns.trash.Paper Loading patterns.trash.Aluminum -Loading patterns.trash.Cardboard -weight of patterns.trash.Aluminum = 89.0 -weight of patterns.trash.Aluminum = 76.0 -weight of patterns.trash.Aluminum = 25.0 -weight of patterns.trash.Aluminum = 34.0 -weight of patterns.trash.Aluminum = 27.0 -weight of patterns.trash.Aluminum = 18.0 -...________...________...________...________... -weight of patterns.trash.Aluminum = 93.0 -weight of patterns.trash.Glass = 93.0 -weight of patterns.trash.Paper = 80.0 -weight of patterns.trash.Glass = 36.0 -weight of patterns.trash.Glass = 12.0 -weight of patterns.trash.Glass = 60.0 -weight of patterns.trash.Paper = 66.0 -weight of patterns.trash.Aluminum = 36.0 -weight of patterns.trash.Cardboard = 22.0 -Total value = 1086.0599818825722 +Loading patterns.trash.Glass +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Total Aluminum value = 13.19 +Paper weight: 8.00 * price: 0.10 = 0.80 +Paper weight: 6.60 * price: 0.10 = 0.66 +Paper weight: 9.10 * price: 0.10 = 0.91 +Total Paper value = 2.37 +Glass weight: 5.40 * price: 0.23 = 1.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Glass value = 3.06 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Total Cardboard value = 0.86 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Paper weight: 8.00 * price: 0.10 = 0.80 +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Glass weight: 5.40 * price: 0.23 = 1.24 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Paper weight: 6.60 * price: 0.10 = 0.66 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Paper weight: 9.10 * price: 0.10 = 0.91 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Trash value = 19.48 */ diff --git a/patterns/shapes/BadShapeCreation.java b/patterns/shapes/BadShapeCreation.java index daa3f7f57..52edcb692 100644 --- a/patterns/shapes/BadShapeCreation.java +++ b/patterns/shapes/BadShapeCreation.java @@ -1,5 +1,5 @@ // patterns/shapes/BadShapeCreation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; diff --git a/patterns/shapes/Circle.java b/patterns/shapes/Circle.java index b50d5abfe..3c05e664a 100644 --- a/patterns/shapes/Circle.java +++ b/patterns/shapes/Circle.java @@ -1,5 +1,5 @@ // patterns/shapes/Circle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; diff --git a/patterns/shapes/FactoryMethod.java b/patterns/shapes/FactoryMethod.java index b03c8239c..9a4174a83 100644 --- a/patterns/shapes/FactoryMethod.java +++ b/patterns/shapes/FactoryMethod.java @@ -1,5 +1,5 @@ // patterns/shapes/FactoryMethod.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; diff --git a/patterns/shapes/FactoryTest.java b/patterns/shapes/FactoryTest.java index 2a9e671ee..506d90360 100644 --- a/patterns/shapes/FactoryTest.java +++ b/patterns/shapes/FactoryTest.java @@ -1,5 +1,5 @@ // patterns/shapes/FactoryTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; diff --git a/patterns/shapes/Shape.java b/patterns/shapes/Shape.java index dfff783cc..38ce61440 100644 --- a/patterns/shapes/Shape.java +++ b/patterns/shapes/Shape.java @@ -1,5 +1,5 @@ // patterns/shapes/Shape.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; @@ -7,8 +7,7 @@ public class Shape { private static int counter = 0; private int id = counter++; - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName() + "[" + id + "]"; } diff --git a/patterns/shapes/Square.java b/patterns/shapes/Square.java index 602b3282c..91f879fa9 100644 --- a/patterns/shapes/Square.java +++ b/patterns/shapes/Square.java @@ -1,5 +1,5 @@ // patterns/shapes/Square.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; diff --git a/patterns/shapes/Triangle.java b/patterns/shapes/Triangle.java index 11559f896..c54af659c 100644 --- a/patterns/shapes/Triangle.java +++ b/patterns/shapes/Triangle.java @@ -1,5 +1,5 @@ // patterns/shapes/Triangle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.shapes; diff --git a/patterns/state/StateMachineDemo.java b/patterns/state/StateMachineDemo.java index 3911fe019..1b9630a9c 100644 --- a/patterns/state/StateMachineDemo.java +++ b/patterns/state/StateMachineDemo.java @@ -1,10 +1,11 @@ // patterns/state/StateMachineDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// The StateMachine pattern and Template method +// The State Machine pattern. // {java patterns.state.StateMachineDemo} package patterns.state; +import java.util.*; import onjava.Nap; interface State { @@ -16,7 +17,7 @@ abstract class StateMachine { protected abstract boolean changeState(); // Template method: protected final void runAll() { - while(changeState()) // Customizable + while(changeState()) currentState.run(); } } @@ -24,24 +25,21 @@ protected final void runAll() { // A different subclass for each state: class Wash implements State { - @Override - public void run() { + @Override public void run() { System.out.println("Washing"); new Nap(0.5); } } class Spin implements State { - @Override - public void run() { + @Override public void run() { System.out.println("Spinning"); new Nap(0.5); } } class Rinse implements State { - @Override - public void run() { + @Override public void run() { System.out.println("Rinsing"); new Nap(0.5); } @@ -49,21 +47,19 @@ public void run() { class Washer extends StateMachine { private int i = 0; - // The state table: - private State[] states = { - new Wash(), new Spin(), - new Rinse(), new Spin(), - }; + private Iterator states = + Arrays.asList( + new Wash(), new Spin(), + new Rinse(), new Spin() + ).iterator(); Washer() { runAll(); } - @Override - public boolean changeState() { - if(i < states.length) { - // Change the state by setting the - // surrogate reference to a new object: - currentState = states[i++]; - return true; - } else + @Override public boolean changeState() { + if(!states.hasNext()) return false; + // Set the surrogate reference + // to a new State object: + currentState = states.next(); + return true; } } diff --git a/patterns/strategy/StrategyPattern.java b/patterns/strategy/StrategyPattern.java index fbc8daa49..7e06bc1e6 100644 --- a/patterns/strategy/StrategyPattern.java +++ b/patterns/strategy/StrategyPattern.java @@ -1,5 +1,5 @@ // patterns/strategy/StrategyPattern.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java patterns.strategy.StrategyPattern} @@ -9,13 +9,14 @@ // The common strategy base type: class FindMinima { + protected Function, List> algorithm; } -// The various strategies: +// The various strategies, each producing dummy data: class LeastSquares extends FindMinima { LeastSquares() { - // Line is a sequence of points (Dummy data): + // Line is a sequence of points: algorithm = (line) -> Arrays.asList(1.1, 2.2); } } @@ -35,8 +36,8 @@ class Bisection extends FindMinima { // The "Context" controls the strategy: class MinimaSolver { private FindMinima strategy; - MinimaSolver(FindMinima strat) { - strategy = strat; + MinimaSolver(FindMinima strategy) { + this.strategy = strategy; } List minima(List line) { return strategy.algorithm.apply(line); @@ -54,11 +55,14 @@ public static void main(String[] args) { 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 ); System.out.println(solver.minima(line)); + solver.changeAlgorithm(new Perturbation()); + System.out.println(solver.minima(line)); solver.changeAlgorithm(new Bisection()); System.out.println(solver.minima(line)); } } /* Output: [1.1, 2.2] +[3.3, 4.4] [5.5, 6.6] */ diff --git a/patterns/strategy/StrategyPattern2.java b/patterns/strategy/StrategyPattern2.java index e8db61547..640b1c05d 100644 --- a/patterns/strategy/StrategyPattern2.java +++ b/patterns/strategy/StrategyPattern2.java @@ -1,5 +1,5 @@ // patterns/strategy/StrategyPattern2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java patterns.strategy.StrategyPattern2} @@ -9,6 +9,7 @@ // "Context" is now incorporated: class FindMinima2 { + private Function, List> algorithm; FindMinima2() { leastSquares(); } // default // The various strategies: @@ -33,11 +34,14 @@ public static void main(String[] args) { 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 ); System.out.println(solver.minima(line)); + solver.perturbation(); + System.out.println(solver.minima(line)); solver.bisection(); System.out.println(solver.minima(line)); } } /* Output: [1.1, 2.2] +[3.3, 4.4] [5.5, 6.6] */ diff --git a/patterns/trash/Aluminum.java b/patterns/trash/Aluminum.java index 210e57014..620cd5e62 100644 --- a/patterns/trash/Aluminum.java +++ b/patterns/trash/Aluminum.java @@ -1,15 +1,16 @@ // patterns/trash/Aluminum.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.trash; public class Aluminum extends Trash { - private static double val = 1.67f; public Aluminum(double wt) { super(wt); } - @Override - public double value() { return val; } - public static void value(double newVal) { - val = newVal; + @Override public double price() { + return Price.ALUMINUM; + } + // Ignore for now; to be used later: + @Override public void accept(Visitor v) { + v.visit(this); } } diff --git a/patterns/trash/Bins.java b/patterns/trash/Bins.java new file mode 100644 index 000000000..304708b39 --- /dev/null +++ b/patterns/trash/Bins.java @@ -0,0 +1,35 @@ +// patterns/trash/Bins.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package patterns.trash; +import java.util.*; + +public class Bins { + final List bin; + final List aluminum = new ArrayList<>(); + final List paper = new ArrayList<>(); + final List glass = new ArrayList<>(); + final List cardboard = new ArrayList<>(); + public Bins(List source) { + bin = new ArrayList<>(source); // Copy + bin.forEach( t -> { + // Use reflection to discover Trash type: + if(t instanceof Aluminum) + aluminum.add((Aluminum)t); + if(t instanceof Paper) + paper.add((Paper)t); + if(t instanceof Glass) + glass.add((Glass)t); + if(t instanceof Cardboard) + cardboard.add((Cardboard)t); + }); + } + public void show() { + TrashValue.sum(aluminum, "Aluminum"); + TrashValue.sum(paper, "Paper"); + TrashValue.sum(glass, "Glass"); + TrashValue.sum(cardboard, "Cardboard"); + TrashValue.sum(bin, "Trash"); + } +} diff --git a/patterns/trash/Cardboard.java b/patterns/trash/Cardboard.java index bb7f84a86..923f6647e 100644 --- a/patterns/trash/Cardboard.java +++ b/patterns/trash/Cardboard.java @@ -1,15 +1,16 @@ // patterns/trash/Cardboard.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.trash; public class Cardboard extends Trash { - private static double val = 0.23f; public Cardboard(double wt) { super(wt); } - @Override - public double value() { return val; } - public static void value(double newVal) { - val = newVal; + @Override public double price() { + return Price.CARDBOARD; + } + // Ignore for now; to be used later: + @Override public void accept(Visitor v) { + v.visit(this); } } diff --git a/patterns/trash/ClassToListOfTrashMap.java b/patterns/trash/ClassToListOfTrashMap.java new file mode 100644 index 000000000..2095cdd41 --- /dev/null +++ b/patterns/trash/ClassToListOfTrashMap.java @@ -0,0 +1,20 @@ +// patterns/trash/ClassToListOfTrashMap.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Display a Map>. +package patterns.trash; +import java.util.*; + +public class ClassToListOfTrashMap { + public static void + show(Map> map) { + map.values().forEach( bin -> { + String typeName = "Trash"; + if(!bin.isEmpty()) + typeName = + bin.get(0).getClass().getSimpleName(); + TrashValue.sum(bin, typeName); + }); + } +} diff --git a/patterns/trash/DynaFactory.java b/patterns/trash/DynaFactory.java new file mode 100644 index 000000000..1331e9ba2 --- /dev/null +++ b/patterns/trash/DynaFactory.java @@ -0,0 +1,44 @@ +// patterns/trash/DynaFactory.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Dynamic discovery of Trash types. +package patterns.trash; +import java.util.*; +import java.util.function.*; +import java.lang.reflect.*; + +public class DynaFactory { + private Map constructors = + new HashMap<>(); + private String packageName; + public DynaFactory(String packageName) { + this.packageName = packageName; + } + @SuppressWarnings("unchecked") + public + T create(TrashInfo info) { + try { + String typename = + "patterns." + packageName + "." + info.type; + return (T)constructors.computeIfAbsent( + typename, this::findConstructor + ).newInstance(info.data); + } catch(Exception e) { + throw new RuntimeException( + "Cannot create() Trash: " + info, e); + } + } + private + Constructor findConstructor(String typename) { + try { + System.out.println("Loading " + typename); + return Class.forName(typename) + .getConstructor(double.class); + } catch(Exception e) { + throw new RuntimeException( + "Trash(double) Constructor Not Found: " + + typename, e); + } + } +} diff --git a/patterns/trash/Fillable.java b/patterns/trash/Fillable.java index 9ac0da0de..329c92bdb 100644 --- a/patterns/trash/Fillable.java +++ b/patterns/trash/Fillable.java @@ -1,8 +1,8 @@ // patterns/trash/Fillable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Any object that can be filled with Trash +// Any object that can be filled with Trash. package patterns.trash; public interface Fillable { diff --git a/patterns/trash/FillableList.java b/patterns/trash/FillableList.java index d6e638c28..8a0bfa745 100644 --- a/patterns/trash/FillableList.java +++ b/patterns/trash/FillableList.java @@ -1,17 +1,18 @@ // patterns/trash/FillableList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Adapter that makes a List Fillable +// Adapter that makes a List Fillable. package patterns.trash; import java.util.*; public class FillableList implements Fillable { - private List v; - public FillableList(List vv) { - v = vv; + private List list; + public FillableList(List list) { + this.list = list; + } + @Override public void addTrash(T t) { + list.add(t); } - @Override - public void addTrash(T t) { v.add(t); } } diff --git a/patterns/trash/Glass.java b/patterns/trash/Glass.java index 83c4b3f87..df08c9963 100644 --- a/patterns/trash/Glass.java +++ b/patterns/trash/Glass.java @@ -1,15 +1,16 @@ // patterns/trash/Glass.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.trash; public class Glass extends Trash { - private static double val = 0.23f; public Glass(double wt) { super(wt); } - @Override - public double value() { return val; } - public static void value(double newVal) { - val = newVal; + @Override public double price() { + return Price.GLASS; + } + // Ignore for now; to be used later: + @Override public void accept(Visitor v) { + v.visit(this); } } diff --git a/patterns/trash/GroupingBy.java b/patterns/trash/GroupingBy.java new file mode 100644 index 000000000..6c8f8bc67 --- /dev/null +++ b/patterns/trash/GroupingBy.java @@ -0,0 +1,41 @@ +// patterns/trash/GroupingBy.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {java patterns.trash.GroupingBy} +package patterns.trash; +import java.util.*; +import java.util.stream.*; + +public class GroupingBy { + public static void main(String[] args) { + List bin = new ArrayList<>(); + ParseTrash.fillBin("trash", bin); + Map> m = + bin.stream().collect( + Collectors.groupingBy(Object::getClass)); + ClassToListOfTrashMap.show(m); + } +} +/* Output: +Loading patterns.trash.Cardboard +Loading patterns.trash.Paper +Loading patterns.trash.Aluminum +Loading patterns.trash.Glass +Glass weight: 5.40 * price: 0.23 = 1.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Glass value = 3.06 +Paper weight: 8.00 * price: 0.10 = 0.80 +Paper weight: 6.60 * price: 0.10 = 0.66 +Paper weight: 9.10 * price: 0.10 = 0.91 +Total Paper value = 2.37 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Total Cardboard value = 0.86 +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Total Aluminum value = 13.19 +*/ diff --git a/patterns/trash/Paper.java b/patterns/trash/Paper.java index 448383c72..5a47cea18 100644 --- a/patterns/trash/Paper.java +++ b/patterns/trash/Paper.java @@ -1,15 +1,16 @@ // patterns/trash/Paper.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package patterns.trash; public class Paper extends Trash { - private static double val = 0.10f; public Paper(double wt) { super(wt); } - @Override - public double value() { return val; } - public static void value(double newVal) { - val = newVal; + @Override public double price() { + return Price.PAPER; + } + // Ignore for now; to be used later: + @Override public void accept(Visitor v) { + v.visit(this); } } diff --git a/patterns/trash/ParseTrash.java b/patterns/trash/ParseTrash.java index 709ad1a85..0ea5df241 100644 --- a/patterns/trash/ParseTrash.java +++ b/patterns/trash/ParseTrash.java @@ -1,9 +1,9 @@ // patterns/trash/ParseTrash.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Open a file and parse its contents into -// Trash objects, placing each into a List +// Opens a file and parses its contents into +// Trash objects, placing each into a Fillable. // {java patterns.trash.ParseTrash} package patterns.trash; import java.util.*; @@ -13,79 +13,56 @@ import java.nio.file.Files; public class ParseTrash { + public static String source = "Trash.dat"; public static void - fillBin(String pckg, Fillable bin) { + fillBin(String packageName, Fillable bin) { + DynaFactory factory = + new DynaFactory(packageName); try { - Files.lines(Paths.get("trash", "Trash.dat")) - // Remove empty lines and comment lines: + Files.lines(Paths.get("trash", source)) + // Remove comments and empty lines: .filter(line -> line.trim().length() != 0) .filter(line -> !line.startsWith("//")) - .forEach( line -> { - String type = "patterns." + pckg + "." + - line.substring( + .forEach(line -> { + String type = line.substring( 0, line.indexOf(':')).trim(); double weight = Double.valueOf( line.substring(line.indexOf(':') + 1) .trim()); - bin.addTrash(Trash.factory( - new Trash.Info(type, weight))); + bin.addTrash(factory.create( + new TrashInfo(type, weight))); }); - } catch(IOException | - NumberFormatException | - Trash.TrashClassNotFoundException | - Trash.CannotCreateTrashException e) { + } catch(IOException | NumberFormatException e) { throw new RuntimeException(e); } } - // Special case to handle List: + // Special case to handle a List: public static void - fillBin(String pckg, List bin) { - fillBin(pckg, new FillableList<>(bin)); + fillBin(String packageName, List bin) { + fillBin(packageName, new FillableList<>(bin)); } // Basic test: public static void main(String[] args) { - List t = new ArrayList<>(); - fillBin("trash", t); - t.forEach(System.out::println); + List bin = new ArrayList<>(); + fillBin("trash", bin); + bin.forEach(System.out::println); } } /* Output: -Loading patterns.trash.Glass +Loading patterns.trash.Cardboard Loading patterns.trash.Paper Loading patterns.trash.Aluminum -Loading patterns.trash.Cardboard -patterns.trash.Glass w:54.0 v:0.23 -patterns.trash.Paper w:22.0 v:0.10 -patterns.trash.Paper w:11.0 v:0.10 -patterns.trash.Glass w:17.0 v:0.23 -patterns.trash.Aluminum w:89.0 v:1.67 -patterns.trash.Paper w:88.0 v:0.10 -patterns.trash.Aluminum w:76.0 v:1.67 -patterns.trash.Cardboard w:96.0 v:0.23 -patterns.trash.Aluminum w:25.0 v:1.67 -patterns.trash.Aluminum w:34.0 v:1.67 -patterns.trash.Glass w:11.0 v:0.23 -patterns.trash.Glass w:68.0 v:0.23 -patterns.trash.Glass w:43.0 v:0.23 -patterns.trash.Aluminum w:27.0 v:1.67 -patterns.trash.Cardboard w:44.0 v:0.23 -patterns.trash.Aluminum w:18.0 v:1.67 -patterns.trash.Paper w:91.0 v:0.10 -patterns.trash.Glass w:63.0 v:0.23 -patterns.trash.Glass w:50.0 v:0.23 -patterns.trash.Glass w:80.0 v:0.23 -patterns.trash.Aluminum w:81.0 v:1.67 -patterns.trash.Cardboard w:12.0 v:0.23 -patterns.trash.Glass w:12.0 v:0.23 -patterns.trash.Glass w:54.0 v:0.23 -patterns.trash.Aluminum w:36.0 v:1.67 -patterns.trash.Aluminum w:93.0 v:1.67 -patterns.trash.Glass w:93.0 v:0.23 -patterns.trash.Paper w:80.0 v:0.10 -patterns.trash.Glass w:36.0 v:0.23 -patterns.trash.Glass w:12.0 v:0.23 -patterns.trash.Glass w:60.0 v:0.23 -patterns.trash.Paper w:66.0 v:0.10 -patterns.trash.Aluminum w:36.0 v:1.67 -patterns.trash.Cardboard w:22.0 v:0.23 +Loading patterns.trash.Glass +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Paper weight: 8.00 * price: 0.10 = 0.80 +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Glass weight: 5.40 * price: 0.23 = 1.24 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Paper weight: 6.60 * price: 0.10 = 0.66 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Paper weight: 9.10 * price: 0.10 = 0.91 +Glass weight: 3.60 * price: 0.23 = 0.83 */ diff --git a/patterns/trash/Price.java b/patterns/trash/Price.java new file mode 100644 index 000000000..9aa071816 --- /dev/null +++ b/patterns/trash/Price.java @@ -0,0 +1,13 @@ +// patterns/trash/Price.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package patterns.trash; + +public interface Price { + double + ALUMINUM = 1.67, + PAPER = 0.10, + GLASS = 0.23, + CARDBOARD = 0.11; +} diff --git a/patterns/trash/Trash.dat b/patterns/trash/Trash.dat index 436a7a719..13bd6187a 100644 --- a/patterns/trash/Trash.dat +++ b/patterns/trash/Trash.dat @@ -1,35 +1,13 @@ // patterns/trash/Trash.dat -Glass:54 -Paper:22 -Paper:11 -Glass:17 -Aluminum:89 -Paper:88 -Aluminum:76 -Cardboard:96 -Aluminum:25 -Aluminum:34 -Glass:11 -Glass:68 -Glass:43 -Aluminum:27 -Cardboard:44 -Aluminum:18 -Paper:91 -Glass:63 -Glass:50 -Glass:80 -Aluminum:81 -Cardboard:12 -Glass:12 -Glass:54 -Aluminum:36 -Aluminum:93 -Glass:93 -Paper:80 -Glass:36 -Glass:12 -Glass:60 -Paper:66 -Aluminum:36 -Cardboard:22 +Cardboard:4.4 +Paper:8.0 +Aluminum:1.8 +Glass:5.4 +Aluminum:3.4 +Cardboard:2.2 +Glass:4.3 +Cardboard:1.2 +Paper:6.6 +Aluminum:2.7 +Paper:9.1 +Glass:3.6 diff --git a/patterns/trash/Trash.java b/patterns/trash/Trash.java index e8d9d3517..9f9feca89 100644 --- a/patterns/trash/Trash.java +++ b/patterns/trash/Trash.java @@ -1,91 +1,22 @@ // patterns/trash/Trash.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Base class for Trash recycling examples +// Base class for Trash recycling examples. package patterns.trash; -import java.util.*; -import java.lang.reflect.*; public abstract class Trash { - private double weight; - public Trash(double wt) { weight = wt; } - public Trash() {} - public abstract double value(); - public double weight() { return weight; } - // Sums the value of Trash in a bin: - static double val; - public static - void sumValue(List bin) { - val = 0.0f; - bin.forEach( t -> { - val += t.weight() * t.value(); - System.out.println("weight of " + - // RTTI gets type information - // about the class: - t.getClass().getName() + - " = " + t.weight()); - }); - System.out.println("Total value = " + val); + public final double weight; + public Trash(double weight) { + this.weight = weight; } - @Override - public String toString() { - // Print correct subclass name: - return getClass().getName() + - " w:" + weight() + " v:" + - String.format("%.2f", value()); - } - // Remainder of class supports dynamic creation: - public static class CannotCreateTrashException - extends RuntimeException { - public CannotCreateTrashException(Exception why) { - super(why); - } - } - public static class TrashClassNotFoundException - extends RuntimeException { - public TrashClassNotFoundException(Exception why) { - super(why); - } - } - public static class Info { - public String id; - public double data; - public Info(String name, double data) { - id = name; - this.data = data; - } - } - private static List trashTypes = - new ArrayList<>(); - @SuppressWarnings("unchecked") - public static T factory(Info info) { - for(Class trashType : trashTypes) { - // Determine the type and create one: - if(trashType.getName().contains(info.id)) { - try { - // Get the dynamic constructor method - // that takes a double argument: - Constructor ctor = - trashType.getConstructor(double.class); - // Call the constructor to create a - // new object: - return (T)ctor.newInstance(info.data); - } catch(Exception e) { - throw new CannotCreateTrashException(e); - } - } - } - // The necessary Class was not in the list. Try to - // load it, but it must be in your class path! - try { - System.out.println("Loading " + info.id); - trashTypes.add(Class.forName(info.id)); - } catch(Exception e) { - throw new TrashClassNotFoundException(e); - } - // Loaded successfully. Recursive call - // should work this time: - return factory(info); + public abstract double price(); + @Override public String toString() { + return String.format( + "%s weight: %.2f * price: %.2f = %.2f", + getClass().getSimpleName(), + weight, price(), weight * price()); } + // Ignore for now; to be used later: + public abstract void accept(Visitor v); } diff --git a/patterns/trash/TrashInfo.java b/patterns/trash/TrashInfo.java new file mode 100644 index 000000000..9adc67882 --- /dev/null +++ b/patterns/trash/TrashInfo.java @@ -0,0 +1,18 @@ +// patterns/trash/TrashInfo.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Messenger class carrying Trash creation data. +package patterns.trash; + +public class TrashInfo { + public final String type; + public final double data; + public TrashInfo(String type, double data) { + this.type = type; + this.data = data; + } + @Override public String toString() { + return "TrashInfo(" + type + ", " + data + ")"; + } +} diff --git a/patterns/trash/TrashValue.java b/patterns/trash/TrashValue.java new file mode 100644 index 000000000..0ca9caaf0 --- /dev/null +++ b/patterns/trash/TrashValue.java @@ -0,0 +1,21 @@ +// patterns/trash/TrashValue.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Sums the value of Trash in a bin. +package patterns.trash; +import java.util.*; + +public class TrashValue { + private static double total; + public static void + sum(List bin, String type) { + total = 0.0; + bin.forEach( t -> { + System.out.println(t); + total += t.weight * t.price(); + }); + System.out.printf( + "Total %s value = %.2f%n", type, total); + } +} diff --git a/patterns/trash/TrashVisitor.java b/patterns/trash/TrashVisitor.java new file mode 100644 index 000000000..3f8431e1b --- /dev/null +++ b/patterns/trash/TrashVisitor.java @@ -0,0 +1,104 @@ +// patterns/trash/TrashVisitor.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Related algorithms packaged in +// each implementation of Visitor. +// {java patterns.trash.TrashVisitor} +package patterns.trash; +import java.util.*; + +class PriceVisitor extends Visitor { + public PriceVisitor() { super("price"); } + @Override public void visit(Aluminum al) { + double price = al.weight * al.price(); + show("Aluminum", price); + alTotal += price; + } + @Override public void visit(Paper p) { + double price = p.weight * p.price(); + show("Paper", price); + pTotal += price; + } + @Override public void visit(Glass g) { + double price = g.weight * g.price(); + show("Glass", price); + gTotal += price; + } + @Override public void visit(Cardboard c) { + double price = c.weight * c.price(); + show("Cardboard", price); + cTotal += price; + } +} + +class WeightVisitor extends Visitor { + public WeightVisitor() { super("weight"); } + @Override public void visit(Aluminum al) { + show("Aluminum", al.weight); + alTotal += al.weight; + } + @Override public void visit(Paper p) { + show("Paper", p.weight); + pTotal += p.weight; + } + @Override public void visit(Glass g) { + show("Glass", g.weight); + gTotal += g.weight; + } + @Override public void visit(Cardboard c) { + show("Cardboard", c.weight); + cTotal += c.weight; + } +} + +public class TrashVisitor { + public static void main(String[] args) { + List bin = new ArrayList<>(); + ParseTrash.fillBin("trash", bin); + List visitors = Arrays.asList( + new PriceVisitor(), new WeightVisitor()); + bin.forEach( + trash -> visitors.forEach(trash::accept) + ); + visitors.forEach(Visitor::total); + } +} +/* Output: +Loading patterns.trash.Cardboard +Loading patterns.trash.Paper +Loading patterns.trash.Aluminum +Loading patterns.trash.Glass +Cardboard price: 0.48 +Cardboard weight: 4.40 +Paper price: 0.80 +Paper weight: 8.00 +Aluminum price: 3.01 +Aluminum weight: 1.80 +Glass price: 1.24 +Glass weight: 5.40 +Aluminum price: 5.68 +Aluminum weight: 3.40 +Cardboard price: 0.24 +Cardboard weight: 2.20 +Glass price: 0.99 +Glass weight: 4.30 +Cardboard price: 0.13 +Cardboard weight: 1.20 +Paper price: 0.66 +Paper weight: 6.60 +Aluminum price: 4.51 +Aluminum weight: 2.70 +Paper price: 0.91 +Paper weight: 9.10 +Glass price: 0.83 +Glass weight: 3.60 +Total Aluminum price: 13.19 +Total Paper price: 2.37 +Total Glass price: 3.06 +Total Cardboard price: 0.86 +Total Aluminum weight: 7.90 +Total Paper weight: 23.70 +Total Glass weight: 13.30 +Total Cardboard weight: 7.80 +*/ diff --git a/patterns/trash/TypeMapTrash.java b/patterns/trash/TypeMapTrash.java new file mode 100644 index 000000000..bd04ab1de --- /dev/null +++ b/patterns/trash/TypeMapTrash.java @@ -0,0 +1,52 @@ +// patterns/trash/TypeMapTrash.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using a Map of Lists and reflection to sort +// Trash into Lists. This is extensible, despite +// the use of reflection. +// {java patterns.trash.TypeMapTrash} +package patterns.trash; +import patterns.TypeMap; + +// Adapter class for ParseTrash.fillBin(): +class TypeMapAdapter implements Fillable { + private TypeMap map; + TypeMapAdapter(TypeMap map) { + this.map = map; + } + @Override + public void addTrash(Trash t) { map.add(t); } +} + +public class TypeMapTrash { + @SuppressWarnings("unchecked") + public static void main(String[] args) { + TypeMap bin = new TypeMap<>(); + ParseTrash.fillBin( + "trash", new TypeMapAdapter(bin)); + ClassToListOfTrashMap.show(bin.map); + } +} +/* Output: +Loading patterns.trash.Cardboard +Loading patterns.trash.Paper +Loading patterns.trash.Aluminum +Loading patterns.trash.Glass +Paper weight: 8.00 * price: 0.10 = 0.80 +Paper weight: 6.60 * price: 0.10 = 0.66 +Paper weight: 9.10 * price: 0.10 = 0.91 +Total Paper value = 2.37 +Glass weight: 5.40 * price: 0.23 = 1.24 +Glass weight: 4.30 * price: 0.23 = 0.99 +Glass weight: 3.60 * price: 0.23 = 0.83 +Total Glass value = 3.06 +Aluminum weight: 1.80 * price: 1.67 = 3.01 +Aluminum weight: 3.40 * price: 1.67 = 5.68 +Aluminum weight: 2.70 * price: 1.67 = 4.51 +Total Aluminum value = 13.19 +Cardboard weight: 4.40 * price: 0.11 = 0.48 +Cardboard weight: 2.20 * price: 0.11 = 0.24 +Cardboard weight: 1.20 * price: 0.11 = 0.13 +Total Cardboard value = 0.86 +*/ diff --git a/patterns/trash/Visitor.java b/patterns/trash/Visitor.java new file mode 100644 index 000000000..34f0fff83 --- /dev/null +++ b/patterns/trash/Visitor.java @@ -0,0 +1,31 @@ +// patterns/trash/Visitor.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// The base class for Visitors. +package patterns.trash; + +public abstract class Visitor { + protected double alTotal; // Aluminum + protected double pTotal; // Paper + protected double gTotal; // Glass + protected double cTotal; // Cardboard + protected String descriptor; + protected Visitor(String descriptor) { + this.descriptor = descriptor; + } + protected void show(String type, double value) { + System.out.printf( + "%s %s: %.2f%n", type, descriptor, value); + } + public void total() { + show("Total Aluminum", alTotal); + show("Total Paper", pTotal); + show("Total Glass", gTotal); + show("Total Cardboard", cTotal); + } + abstract void visit(Aluminum a); + abstract void visit(Paper p); + abstract void visit(Glass g); + abstract void visit(Cardboard c); +} diff --git a/patterns/trashvisitor/Aluminum.java b/patterns/trashvisitor/Aluminum.java deleted file mode 100644 index c89592c33..000000000 --- a/patterns/trashvisitor/Aluminum.java +++ /dev/null @@ -1,16 +0,0 @@ -// patterns/trashvisitor/Aluminum.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Aluminum for the visitor pattern -package patterns.trashvisitor; -import patterns.trash.*; - -public class Aluminum extends patterns.trash.Aluminum - implements Visitable { - public Aluminum(double wt) { super(wt); } - @Override - public void accept(Visitor v) { - v.visit(this); - } -} diff --git a/patterns/trashvisitor/Cardboard.java b/patterns/trashvisitor/Cardboard.java deleted file mode 100644 index 23fcb1a44..000000000 --- a/patterns/trashvisitor/Cardboard.java +++ /dev/null @@ -1,16 +0,0 @@ -// patterns/trashvisitor/Cardboard.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Cardboard for the visitor pattern -package patterns.trashvisitor; -import patterns.trash.*; - -public class Cardboard extends patterns.trash.Cardboard - implements Visitable { - public Cardboard(double wt) { super(wt); } - @Override - public void accept(Visitor v) { - v.visit(this); - } -} diff --git a/patterns/trashvisitor/Glass.java b/patterns/trashvisitor/Glass.java deleted file mode 100644 index 70e5d2105..000000000 --- a/patterns/trashvisitor/Glass.java +++ /dev/null @@ -1,16 +0,0 @@ -// patterns/trashvisitor/Glass.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Glass for the visitor pattern -package patterns.trashvisitor; -import patterns.trash.*; - -public class Glass extends patterns.trash.Glass - implements Visitable { - public Glass(double wt) { super(wt); } - @Override - public void accept(Visitor v) { - v.visit(this); - } -} diff --git a/patterns/trashvisitor/Paper.java b/patterns/trashvisitor/Paper.java deleted file mode 100644 index d42cb0610..000000000 --- a/patterns/trashvisitor/Paper.java +++ /dev/null @@ -1,16 +0,0 @@ -// patterns/trashvisitor/Paper.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Paper for the visitor pattern -package patterns.trashvisitor; -import patterns.trash.*; - -public class Paper extends patterns.trash.Paper - implements Visitable { - public Paper(double wt) { super(wt); } - @Override - public void accept(Visitor v) { - v.visit(this); - } -} diff --git a/patterns/trashvisitor/TrashVisitor.java b/patterns/trashvisitor/TrashVisitor.java deleted file mode 100644 index bb0eeec18..000000000 --- a/patterns/trashvisitor/TrashVisitor.java +++ /dev/null @@ -1,127 +0,0 @@ -// patterns/trashvisitor/TrashVisitor.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// {java patterns.trashvisitor.TrashVisitor} -package patterns.trashvisitor; -import patterns.trash.*; -import java.util.*; - -// Specific group of algorithms packaged -// in each implementation of Visitor: -class PriceVisitor implements Visitor { - private double alSum; // Aluminum - private double pSum; // Paper - private double gSum; // Glass - private double cSum; // Cardboard - public static void show(String s) { - System.out.println(s); - } - @Override - public void visit(Aluminum al) { - double v = al.weight() * al.value(); - show("value of Aluminum= " + v); - alSum += v; - } - @Override - public void visit(Paper p) { - double v = p.weight() * p.value(); - show("value of Paper= " + v); - pSum += v; - } - @Override - public void visit(Glass g) { - double v = g.weight() * g.value(); - show("value of Glass= " + v); - gSum += v; - } - @Override - public void visit(Cardboard c) { - double v = c.weight() * c.value(); - show("value of Cardboard = " + v); - cSum += v; - } - @Override - public void total() { - show( - "Total Aluminum: $" + alSum + "\n" + - "Total Paper: $" + pSum + "\n" + - "Total Glass: $" + gSum + "\n" + - "Total Cardboard: $" + cSum); - } -} - -class WeightVisitor implements Visitor { - private double alSum; // Aluminum - private double pSum; // Paper - private double gSum; // Glass - private double cSum; // Cardboard - public static void show(String s) { - System.out.println(s); - } - @Override - public void visit(Aluminum al) { - alSum += al.weight(); - show("Aluminum weight = " + al.weight()); - } - @Override - public void visit(Paper p) { - pSum += p.weight(); - show("Paper weight = " + p.weight()); - } - @Override - public void visit(Glass g) { - gSum += g.weight(); - show("Glass weight = " + g.weight()); - } - @Override - public void visit(Cardboard c) { - cSum += c.weight(); - show("Cardboard weight = " + c.weight()); - } - @Override - public void total() { - show("Total weight Aluminum:" + alSum); - show("Total weight Paper:" + pSum); - show("Total weight Glass:" + gSum); - show("Total weight Cardboard:" + cSum); - } -} - -public class TrashVisitor { - public static void main(String[] args) { - List bin = new ArrayList<>(); - // ParseTrash still works, without changes: - ParseTrash.fillBin("trashvisitor", bin); - List visitors = Arrays.asList( - new PriceVisitor(), new WeightVisitor()); - bin.forEach( t -> { - Visitable v = (Visitable) t; - visitors.forEach(visitor -> v.accept(visitor)); - }); - visitors.forEach(Visitor::total); - } -} -/* Output: (First and Last 10 Lines) -Loading patterns.trashvisitor.Glass -Loading patterns.trashvisitor.Paper -Loading patterns.trashvisitor.Aluminum -Loading patterns.trashvisitor.Cardboard -value of Glass= 12.420000225305557 -Glass weight = 54.0 -value of Paper= 2.2000000327825546 -Paper weight = 22.0 -value of Paper= 1.1000000163912773 -Paper weight = 11.0 -...________...________...________...________... -value of Cardboard = 5.060000091791153 -Cardboard weight = 22.0 -Total Aluminum: $860.0499778985977 -Total Paper: $35.80000053346157 -Total Glass: $150.1900027245283 -Total Cardboard: $40.02000072598457 -Total weight Aluminum:515.0 -Total weight Paper:358.0 -Total weight Glass:653.0 -Total weight Cardboard:174.0 -*/ diff --git a/patterns/trashvisitor/Visitable.java b/patterns/trashvisitor/Visitable.java deleted file mode 100644 index 7d736b3e9..000000000 --- a/patterns/trashvisitor/Visitable.java +++ /dev/null @@ -1,12 +0,0 @@ -// patterns/trashvisitor/Visitable.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// An interface to add visitor functionality to the -// Trash hierarchy without modifying the base class -package patterns.trashvisitor; - -public interface Visitable { - // The new method: - void accept(Visitor v); -} diff --git a/patterns/trashvisitor/Visitor.java b/patterns/trashvisitor/Visitor.java deleted file mode 100644 index 0a97e3a2d..000000000 --- a/patterns/trashvisitor/Visitor.java +++ /dev/null @@ -1,14 +0,0 @@ -// patterns/trashvisitor/Visitor.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// The base interface for visitors -package patterns.trashvisitor; - -public interface Visitor { - void visit(Aluminum a); - void visit(Paper p); - void visit(Glass g); - void visit(Cardboard c); - void total(); -} diff --git a/patterns/visitor/BeeAndFlowers.java b/patterns/visitor/BeeAndFlowers.java index 3f05cd5e0..395966190 100644 --- a/patterns/visitor/BeeAndFlowers.java +++ b/patterns/visitor/BeeAndFlowers.java @@ -1,8 +1,8 @@ // patterns/visitor/BeeAndFlowers.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Demonstration of "visitor" pattern +// Demonstration of the Visitor pattern. // {java patterns.visitor.BeeAndFlowers} package patterns.visitor; import java.util.*; @@ -11,7 +11,7 @@ interface Visitor { void visit(Gladiolus g); - void visit(Renuculus r); + void visit(Ranunculus r); void visit(Chrysanthemum c); } @@ -25,7 +25,7 @@ class Gladiolus implements Flower { public void accept(Visitor v) { v.visit(this);} } -class Renuculus implements Flower { +class Ranunculus implements Flower { @Override public void accept(Visitor v) { v.visit(this);} } @@ -37,35 +37,28 @@ class Chrysanthemum implements Flower { // Add the ability to produce a String: class StringVal implements Visitor { - String s; - @Override - public String toString() { return s; } - @Override - public void visit(Gladiolus g) { + private String s; + @Override public String toString() { return s; } + @Override public void visit(Gladiolus g) { s = "Gladiolus"; } - @Override - public void visit(Renuculus r) { - s = "Renuculus"; + @Override public void visit(Ranunculus r) { + s = "Ranunculus"; } - @Override - public void visit(Chrysanthemum c) { + @Override public void visit(Chrysanthemum c) { s = "Chrysanthemum"; } } // Add the ability to do "Bee" activities: class Bee implements Visitor { - @Override - public void visit(Gladiolus g) { + @Override public void visit(Gladiolus g) { System.out.println("Bee and Gladiolus"); } - @Override - public void visit(Renuculus r) { - System.out.println("Bee and Renuculus"); + @Override public void visit(Ranunculus r) { + System.out.println("Bee and Ranunculus"); } - @Override - public void visit(Chrysanthemum c) { + @Override public void visit(Chrysanthemum c) { System.out.println("Bee and Chrysanthemum"); } } @@ -73,7 +66,7 @@ public void visit(Chrysanthemum c) { class FlowerFactory { static List> flowers = Arrays.asList(Gladiolus::new, - Renuculus::new, Chrysanthemum::new); + Ranunculus::new, Chrysanthemum::new); static final int SZ = flowers.size(); private static SplittableRandom rand = new SplittableRandom(47); @@ -102,21 +95,21 @@ public static void main(String[] args) { Gladiolus Chrysanthemum Gladiolus -Renuculus +Ranunculus Chrysanthemum -Renuculus +Ranunculus Chrysanthemum Chrysanthemum Chrysanthemum -Renuculus +Ranunculus Bee and Gladiolus Bee and Chrysanthemum Bee and Gladiolus -Bee and Renuculus +Bee and Ranunculus Bee and Chrysanthemum -Bee and Renuculus +Bee and Ranunculus Bee and Chrysanthemum Bee and Chrysanthemum Bee and Chrysanthemum -Bee and Renuculus +Bee and Ranunculus */ diff --git a/polymorphism/CovariantReturn.java b/polymorphism/CovariantReturn.java index b30e0b640..5b46602aa 100644 --- a/polymorphism/CovariantReturn.java +++ b/polymorphism/CovariantReturn.java @@ -1,16 +1,18 @@ // polymorphism/CovariantReturn.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. class Grain { - @Override - public String toString() { return "Grain"; } + @Override public String toString() { + return "Grain"; + } } class Wheat extends Grain { - @Override - public String toString() { return "Wheat"; } + @Override public String toString() { + return "Wheat"; + } } class Mill { @@ -18,8 +20,9 @@ class Mill { } class WheatMill extends Mill { - @Override - Wheat process() { return new Wheat(); } + @Override Wheat process() { + return new Wheat(); + } } public class CovariantReturn { diff --git a/polymorphism/FieldAccess.java b/polymorphism/FieldAccess.java index 2ab7e02cb..e6b39229f 100644 --- a/polymorphism/FieldAccess.java +++ b/polymorphism/FieldAccess.java @@ -1,5 +1,5 @@ // polymorphism/FieldAccess.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Direct field access is determined at compile time @@ -11,8 +11,7 @@ class Super { class Sub extends Super { public int field = 1; - @Override - public int getField() { return field; } + @Override public int getField() { return field; } public int getSuperField() { return super.field; } } diff --git a/polymorphism/Frog.java b/polymorphism/Frog.java index c9231de38..eb0669f25 100644 --- a/polymorphism/Frog.java +++ b/polymorphism/Frog.java @@ -1,5 +1,5 @@ // polymorphism/Frog.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Cleanup and inheritance @@ -49,8 +49,7 @@ class Animal extends LivingCreature { private Description t = new Description("Animal not Vegetable"); Animal() { System.out.println("Animal()"); } - @Override - protected void dispose() { + @Override protected void dispose() { System.out.println("Animal dispose"); t.dispose(); p.dispose(); @@ -66,8 +65,7 @@ class Amphibian extends Animal { Amphibian() { System.out.println("Amphibian()"); } - @Override - protected void dispose() { + @Override protected void dispose() { System.out.println("Amphibian dispose"); t.dispose(); p.dispose(); @@ -80,8 +78,7 @@ public class Frog extends Amphibian { new Characteristic("Croaks"); private Description t = new Description("Eats Bugs"); public Frog() { System.out.println("Frog()"); } - @Override - protected void dispose() { + @Override protected void dispose() { System.out.println("Frog dispose"); t.dispose(); p.dispose(); diff --git a/polymorphism/PolyConstructors.java b/polymorphism/PolyConstructors.java index d217e4a08..8a6d6ed5c 100644 --- a/polymorphism/PolyConstructors.java +++ b/polymorphism/PolyConstructors.java @@ -1,5 +1,5 @@ // polymorphism/PolyConstructors.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Constructors and polymorphism @@ -21,8 +21,7 @@ class RoundGlyph extends Glyph { System.out.println( "RoundGlyph.RoundGlyph(), radius = " + radius); } - @Override - void draw() { + @Override void draw() { System.out.println( "RoundGlyph.draw(), radius = " + radius); } diff --git a/polymorphism/PrivateOverride.java b/polymorphism/PrivateOverride.java index a072095e1..59aba4ed2 100644 --- a/polymorphism/PrivateOverride.java +++ b/polymorphism/PrivateOverride.java @@ -1,5 +1,5 @@ // polymorphism/PrivateOverride.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Trying to override a private method diff --git a/polymorphism/PrivateOverride2.java b/polymorphism/PrivateOverride2.java index 1d0c07c81..d53d9a256 100644 --- a/polymorphism/PrivateOverride2.java +++ b/polymorphism/PrivateOverride2.java @@ -1,5 +1,5 @@ // polymorphism/PrivateOverride2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Detecting a mistaken override using @Override @@ -17,6 +17,7 @@ public static void main(String[] args) { } class Derived2 extends PrivateOverride2 { - @Override - public void f() { System.out.println("public f()"); } + @Override public void f() { + System.out.println("public f()"); + } } diff --git a/polymorphism/ReferenceCounting.java b/polymorphism/ReferenceCounting.java index a175fcade..634cd8c6c 100644 --- a/polymorphism/ReferenceCounting.java +++ b/polymorphism/ReferenceCounting.java @@ -1,5 +1,5 @@ // polymorphism/ReferenceCounting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Cleaning up shared member objects @@ -16,8 +16,7 @@ protected void dispose() { if(--refcount == 0) System.out.println("Disposing " + this); } - @Override - public String toString() { + @Override public String toString() { return "Shared " + id; } } @@ -35,8 +34,7 @@ protected void dispose() { System.out.println("disposing " + this); shared.dispose(); } - @Override - public String toString() { + @Override public String toString() { return "Composing " + id; } } diff --git a/polymorphism/RTTI.java b/polymorphism/Reflect.java similarity index 70% rename from polymorphism/RTTI.java rename to polymorphism/Reflect.java index 5ddfa82f5..341e86f68 100644 --- a/polymorphism/RTTI.java +++ b/polymorphism/Reflect.java @@ -1,8 +1,7 @@ -// polymorphism/RTTI.java -// (c)2017 MindView LLC: see Copyright.txt +// polymorphism/Reflect.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Downcasting & Runtime type information (RTTI) // {ThrowsException} class Useful { @@ -11,16 +10,14 @@ public void g() {} } class MoreUseful extends Useful { - @Override - public void f() {} - @Override - public void g() {} + @Override public void f() {} + @Override public void g() {} public void u() {} public void v() {} public void w() {} } -public class RTTI { +public class Reflect { public static void main(String[] args) { Useful[] x = { new Useful(), @@ -30,7 +27,7 @@ public static void main(String[] args) { x[1].g(); // Compile time: method not found in Useful: //- x[1].u(); - ((MoreUseful)x[1]).u(); // Downcast/RTTI + ((MoreUseful)x[1]).u(); // Downcast/Reflect ((MoreUseful)x[0]).u(); // Exception thrown } } @@ -39,5 +36,5 @@ public static void main(String[] args) { Exception in thread "main" java.lang.ClassCastException: Useful cannot be cast to MoreUseful - at RTTI.main(RTTI.java:31) + at Reflect.main(Reflect.java:28) */ diff --git a/polymorphism/Sandwich.java b/polymorphism/Sandwich.java index a13a61929..ef39bcbae 100644 --- a/polymorphism/Sandwich.java +++ b/polymorphism/Sandwich.java @@ -1,5 +1,5 @@ // polymorphism/Sandwich.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Order of constructor calls diff --git a/polymorphism/Shapes.java b/polymorphism/Shapes.java index 42e13f112..17d82061e 100644 --- a/polymorphism/Shapes.java +++ b/polymorphism/Shapes.java @@ -1,5 +1,5 @@ // polymorphism/Shapes.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Polymorphism in Java diff --git a/polymorphism/StaticPolymorphism.java b/polymorphism/StaticPolymorphism.java index 40e4f794d..2a7309f7e 100644 --- a/polymorphism/StaticPolymorphism.java +++ b/polymorphism/StaticPolymorphism.java @@ -1,5 +1,5 @@ // polymorphism/StaticPolymorphism.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Static methods are not polymorphic @@ -17,8 +17,7 @@ class StaticSub extends StaticSuper { public static String staticGet() { return "Derived staticGet()"; } - @Override - public String dynamicGet() { + @Override public String dynamicGet() { return "Derived dynamicGet()"; } } diff --git a/polymorphism/Transmogrify.java b/polymorphism/Transmogrify.java index dd45b9bd4..4dbcdeb4b 100644 --- a/polymorphism/Transmogrify.java +++ b/polymorphism/Transmogrify.java @@ -1,5 +1,5 @@ // polymorphism/Transmogrify.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Dynamically changing the behavior of an object @@ -10,15 +10,13 @@ public void act() {} } class HappyActor extends Actor { - @Override - public void act() { + @Override public void act() { System.out.println("HappyActor"); } } class SadActor extends Actor { - @Override - public void act() { + @Override public void act() { System.out.println("SadActor"); } } diff --git a/polymorphism/music/Instrument.java b/polymorphism/music/Instrument.java index 959c2dd3d..907b3566f 100644 --- a/polymorphism/music/Instrument.java +++ b/polymorphism/music/Instrument.java @@ -1,5 +1,5 @@ // polymorphism/music/Instrument.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package polymorphism.music; diff --git a/polymorphism/music/Music.java b/polymorphism/music/Music.java index 2338543b2..fb92e0099 100644 --- a/polymorphism/music/Music.java +++ b/polymorphism/music/Music.java @@ -1,5 +1,5 @@ // polymorphism/music/Music.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Inheritance & upcasting diff --git a/polymorphism/music/Music2.java b/polymorphism/music/Music2.java index e16eb1799..790adcf5d 100644 --- a/polymorphism/music/Music2.java +++ b/polymorphism/music/Music2.java @@ -1,5 +1,5 @@ // polymorphism/music/Music2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Overloading instead of upcasting @@ -7,15 +7,13 @@ package polymorphism.music; class Stringed extends Instrument { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Stringed.play() " + n); } } class Brass extends Instrument { - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Brass.play() " + n); } } diff --git a/polymorphism/music/Note.java b/polymorphism/music/Note.java index 34f55bd8e..6963bc15a 100644 --- a/polymorphism/music/Note.java +++ b/polymorphism/music/Note.java @@ -1,5 +1,5 @@ // polymorphism/music/Note.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Notes to play on musical instruments diff --git a/polymorphism/music/Wind.java b/polymorphism/music/Wind.java index fcec34ae4..6e48f513b 100644 --- a/polymorphism/music/Wind.java +++ b/polymorphism/music/Wind.java @@ -1,5 +1,5 @@ // polymorphism/music/Wind.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package polymorphism.music; @@ -8,8 +8,7 @@ // because they have the same interface: public class Wind extends Instrument { // Redefine interface method: - @Override - public void play(Note n) { + @Override public void play(Note n) { System.out.println("Wind.play() " + n); } } diff --git a/polymorphism/music3/Music3.java b/polymorphism/music3/Music3.java index 4c7c70f84..97938dd01 100644 --- a/polymorphism/music3/Music3.java +++ b/polymorphism/music3/Music3.java @@ -1,5 +1,5 @@ // polymorphism/music3/Music3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // An extensible program @@ -18,62 +18,49 @@ void adjust() { } class Wind extends Instrument { - @Override - void play(Note n) { + @Override void play(Note n) { System.out.println("Wind.play() " + n); } - @Override - String what() { return "Wind"; } - @Override - void adjust() { + @Override String what() { return "Wind"; } + @Override void adjust() { System.out.println("Adjusting Wind"); } } class Percussion extends Instrument { - @Override - void play(Note n) { + @Override void play(Note n) { System.out.println("Percussion.play() " + n); } - @Override - String what() { return "Percussion"; } - @Override - void adjust() { + @Override String what() { return "Percussion"; } + @Override void adjust() { System.out.println("Adjusting Percussion"); } } class Stringed extends Instrument { - @Override - void play(Note n) { + @Override void play(Note n) { System.out.println("Stringed.play() " + n); } - @Override - String what() { return "Stringed"; } - @Override - void adjust() { + @Override String what() { return "Stringed"; } + @Override void adjust() { System.out.println("Adjusting Stringed"); } } class Brass extends Wind { - @Override - void play(Note n) { + @Override void play(Note n) { System.out.println("Brass.play() " + n); } - @Override - void adjust() { + @Override void adjust() { System.out.println("Adjusting Brass"); } } class Woodwind extends Wind { - @Override - void play(Note n) { + @Override void play(Note n) { System.out.println("Woodwind.play() " + n); } - @Override - String what() { return "Woodwind"; } + @Override String what() { return "Woodwind"; } } public class Music3 { diff --git a/polymorphism/shape/Circle.java b/polymorphism/shape/Circle.java index 305d0411b..9b97edaed 100644 --- a/polymorphism/shape/Circle.java +++ b/polymorphism/shape/Circle.java @@ -1,16 +1,14 @@ // polymorphism/shape/Circle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package polymorphism.shape; public class Circle extends Shape { - @Override - public void draw() { + @Override public void draw() { System.out.println("Circle.draw()"); } - @Override - public void erase() { + @Override public void erase() { System.out.println("Circle.erase()"); } } diff --git a/polymorphism/shape/RandomShapes.java b/polymorphism/shape/RandomShapes.java index 3a5fa9063..03120f5ea 100644 --- a/polymorphism/shape/RandomShapes.java +++ b/polymorphism/shape/RandomShapes.java @@ -1,5 +1,5 @@ // polymorphism/shape/RandomShapes.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A "factory" that randomly creates shapes diff --git a/polymorphism/shape/Shape.java b/polymorphism/shape/Shape.java index 3d42f1218..d78c6dd9e 100644 --- a/polymorphism/shape/Shape.java +++ b/polymorphism/shape/Shape.java @@ -1,5 +1,5 @@ // polymorphism/shape/Shape.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package polymorphism.shape; diff --git a/polymorphism/shape/Square.java b/polymorphism/shape/Square.java index c04d68320..fb4802b10 100644 --- a/polymorphism/shape/Square.java +++ b/polymorphism/shape/Square.java @@ -1,16 +1,14 @@ // polymorphism/shape/Square.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package polymorphism.shape; public class Square extends Shape { - @Override - public void draw() { + @Override public void draw() { System.out.println("Square.draw()"); } - @Override - public void erase() { + @Override public void erase() { System.out.println("Square.erase()"); } } diff --git a/polymorphism/shape/Triangle.java b/polymorphism/shape/Triangle.java index 7bc9a961a..baebbf870 100644 --- a/polymorphism/shape/Triangle.java +++ b/polymorphism/shape/Triangle.java @@ -1,16 +1,14 @@ // polymorphism/shape/Triangle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package polymorphism.shape; public class Triangle extends Shape { - @Override - public void draw() { + @Override public void draw() { System.out.println("Triangle.draw()"); } - @Override - public void erase() { + @Override public void erase() { System.out.println("Triangle.erase()"); } } diff --git a/references/AddingClone.java b/references/AddingClone.java index d8b1106fb..298b78bf3 100644 --- a/references/AddingClone.java +++ b/references/AddingClone.java @@ -1,5 +1,5 @@ // references/AddingClone.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // You must go through a few gyrations @@ -11,12 +11,10 @@ class Int2 implements Cloneable { private int i; Int2(int ii) { i = ii; } public void increment() { i++; } - @Override - public String toString() { + @Override public String toString() { return Integer.toString(i); } - @Override - public Int2 clone() { + @Override public Int2 clone() { try { return (Int2)super.clone(); } catch(CloneNotSupportedException e) { diff --git a/references/Alias1.java b/references/Alias1.java index a40966355..e3cd047b7 100644 --- a/references/Alias1.java +++ b/references/Alias1.java @@ -1,5 +1,5 @@ // references/Alias1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Aliasing two references to one object @@ -9,11 +9,11 @@ public class Alias1 { public Alias1(int ii) { i = ii; } public static void main(String[] args) { Alias1 x = new Alias1(7); - Alias1 y = x; // Assign the reference (1) + Alias1 y = x; // Assign the reference // [1] System.out.println("x: " + x.i); System.out.println("y: " + y.i); System.out.println("Incrementing x"); - x.i++; // [2] + x.i++; // [2] System.out.println("x: " + x.i); System.out.println("y: " + y.i); } diff --git a/references/Alias2.java b/references/Alias2.java index 928d9c7bf..789724697 100644 --- a/references/Alias2.java +++ b/references/Alias2.java @@ -1,5 +1,5 @@ // references/Alias2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Method calls implicitly alias their arguments diff --git a/references/CheckCloneable.java b/references/CheckCloneable.java index b9e7eb078..0293b5cef 100644 --- a/references/CheckCloneable.java +++ b/references/CheckCloneable.java @@ -1,5 +1,5 @@ // references/CheckCloneable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Check to see if a reference can be cloned @@ -46,8 +46,7 @@ private BackOn duplicate(BackOn b) { // copy. A dummy copy, just to make a point: return new BackOn(); } - @Override - public Object clone() { + @Override public Object clone() { // Doesn't call NoMore.clone(): return duplicate(this); } diff --git a/references/CloneArrayList.java b/references/CloneArrayList.java index 13bc77951..811dd419c 100644 --- a/references/CloneArrayList.java +++ b/references/CloneArrayList.java @@ -1,5 +1,5 @@ // references/CloneArrayList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The clone() operation works for only a few @@ -11,8 +11,7 @@ class Int { private int i; Int(int ii) { i = ii; } public void increment() { i++; } - @Override - public String toString() { + @Override public String toString() { return Integer.toString(i); } } diff --git a/references/Compete.java b/references/Compete.java index 3c825d387..9a37c00af 100644 --- a/references/Compete.java +++ b/references/Compete.java @@ -1,5 +1,5 @@ // references/Compete.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; @@ -11,8 +11,7 @@ class Thing2 implements Serializable { } class Thing3 implements Cloneable { - @Override - public Thing3 clone() { + @Override public Thing3 clone() { try { return (Thing3)super.clone(); } catch(CloneNotSupportedException e) { @@ -23,8 +22,7 @@ public Thing3 clone() { class Thing4 implements Cloneable { private Thing3 t3 = new Thing3(); - @Override - public Thing4 clone() { + @Override public Thing4 clone() { Thing4 t4 = null; try { t4 = (Thing4)super.clone(); @@ -84,6 +82,6 @@ public class Compete { } } /* Output: -Duplication via serialization: 516 Milliseconds -Duplication via cloning: 71 Milliseconds +Duplication via serialization: 385 Milliseconds +Duplication via cloning: 38 Milliseconds */ diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java index 46e1ee212..fe16259fa 100644 --- a/references/CopyConstructor.java +++ b/references/CopyConstructor.java @@ -1,5 +1,5 @@ // references/CopyConstructor.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A constructor to copy an object of the same @@ -13,7 +13,7 @@ class FruitQualities { private int ripeness; private int smell; // etc. - // No-arg constructor: + // Zero-argument constructor: FruitQualities() { // Do something meaningful... } @@ -32,7 +32,7 @@ class FruitQualities { class Seed { // Members... - Seed() { /* No-arg constructor */ } + Seed() { /* Zero-argument constructor */ } Seed(Seed s) { /* Copy constructor */ } } @@ -81,7 +81,7 @@ class Tomato extends Fruit { class ZebraQualities extends FruitQualities { private int stripedness; - // No-arg constructor: + // Zero-argument constructor: ZebraQualities() { super(); // do something meaningful... @@ -112,12 +112,12 @@ public void evaluate() { public class CopyConstructor { public static void ripen(Tomato t) { // Use the "copy constructor": - t = new Tomato(t); // [1] + t = new Tomato(t); // [1] System.out.println("In ripen, t is a " + t.getClass().getName()); } public static void slice(Fruit f) { - f = new Fruit(f); // [2] Hmmm... will this work? + f = new Fruit(f); // Hmm... will this work? // [2] System.out.println("In slice, f is a " + f.getClass().getName()); } diff --git a/references/DepthReading.java b/references/DepthReading.java index d9f3f1ae6..46c14fd69 100644 --- a/references/DepthReading.java +++ b/references/DepthReading.java @@ -1,5 +1,5 @@ // references/DepthReading.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Cloning a composed object @@ -10,8 +10,7 @@ public class DepthReading implements Cloneable { public DepthReading(double depth) { this.depth = depth; } - @Override - public DepthReading clone() { + @Override public DepthReading clone() { try { return (DepthReading)super.clone(); } catch(CloneNotSupportedException e) { @@ -22,8 +21,7 @@ public DepthReading clone() { public void setDepth(double depth) { this.depth = depth; } - @Override - public String toString() { + @Override public String toString() { return String.valueOf(depth); } } diff --git a/references/HorrorFlick.java b/references/HorrorFlick.java index ea310ca4f..e4a8656d9 100644 --- a/references/HorrorFlick.java +++ b/references/HorrorFlick.java @@ -1,5 +1,5 @@ // references/HorrorFlick.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Insert Cloneability at any level of inheritance @@ -9,8 +9,7 @@ class Person {} class Hero extends Person {} class Scientist extends Person implements Cloneable { - @Override - public Scientist clone() { + @Override public Scientist clone() { try { return (Scientist)super.clone(); } catch(CloneNotSupportedException e) { diff --git a/references/Immutable1.java b/references/Immutable1.java index c4f538916..8c2240ab5 100644 --- a/references/Immutable1.java +++ b/references/Immutable1.java @@ -1,5 +1,5 @@ // references/Immutable1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Immutable objects are immune to aliasing diff --git a/references/Immutable2.java b/references/Immutable2.java index 8f35edaa6..aa23cadad 100644 --- a/references/Immutable2.java +++ b/references/Immutable2.java @@ -1,5 +1,5 @@ // references/Immutable2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A companion class to modify immutable objects diff --git a/references/ImmutableInteger.java b/references/ImmutableInteger.java index 3dc86a28a..a42ddf1ef 100644 --- a/references/ImmutableInteger.java +++ b/references/ImmutableInteger.java @@ -1,5 +1,5 @@ // references/ImmutableInteger.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The Integer class cannot be changed @@ -8,6 +8,7 @@ public class ImmutableInteger { public static void main(String[] args) { + @SuppressWarnings("deprecation") List v = IntStream.range(0, 10) .mapToObj(Integer::new) .collect(Collectors.toList()); diff --git a/references/ImmutableStrings.java b/references/ImmutableStrings.java deleted file mode 100644 index 538ab6efc..000000000 --- a/references/ImmutableStrings.java +++ /dev/null @@ -1,25 +0,0 @@ -// references/ImmutableStrings.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Demonstrating StringBuilder - -public class ImmutableStrings { - public static void main(String[] args) { - String foo = "foo"; - String s = "abc" + foo + "def" - + Integer.toString(47); - System.out.println(s); - // The "equivalent" using StringBuilder: - StringBuilder sb = - new StringBuilder("abc"); // Creates String - sb.append(foo); - sb.append("def"); // Creates String - sb.append(Integer.toString(47)); - System.out.println(sb); - } -} -/* Output: -abcfoodef47 -abcfoodef47 -*/ diff --git a/references/LocalCopy.java b/references/LocalCopy.java index d7462981a..f19f63a62 100644 --- a/references/LocalCopy.java +++ b/references/LocalCopy.java @@ -1,5 +1,5 @@ // references/LocalCopy.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Creating local copies with clone() @@ -7,8 +7,7 @@ class Duplo implements Cloneable { private int n; Duplo(int n) { this.n = n; } - @Override - public Duplo clone() { // [1] + @Override public Duplo clone() { // [1] try { return (Duplo)super.clone(); } catch(CloneNotSupportedException e) { @@ -18,8 +17,7 @@ public Duplo clone() { // [1] public int getValue() { return n; } public void setValue(int n) { this.n = n; } public void increment() { n++; } - @Override - public String toString() { + @Override public String toString() { return Integer.toString(n); } } @@ -31,7 +29,7 @@ public static Duplo g(Duplo v) { return v; } public static Duplo f(Duplo v) { - v = v.clone(); // [2] Local copy + v = v.clone(); // Local copy // [2] v.increment(); return v; } diff --git a/references/MutableInteger.java b/references/MutableInteger.java index 7f6e47d21..9642777e6 100644 --- a/references/MutableInteger.java +++ b/references/MutableInteger.java @@ -1,5 +1,5 @@ // references/MutableInteger.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A changeable wrapper class @@ -12,8 +12,7 @@ class IntValue { public int getValue() { return n; } public void setValue(int n) { this.n = n; } public void increment() { n++; } - @Override - public String toString() { + @Override public String toString() { return Integer.toString(n); } } diff --git a/references/OceanReading.java b/references/OceanReading.java index b8466fa04..754a13b8d 100644 --- a/references/OceanReading.java +++ b/references/OceanReading.java @@ -1,5 +1,5 @@ // references/OceanReading.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Cloning a composed object @@ -13,8 +13,7 @@ public class OceanReading implements Cloneable { temperature = new TemperatureReading(tdata); depth = new DepthReading(ddata); } - @Override - public OceanReading clone() { + @Override public OceanReading clone() { OceanReading or = null; try { or = (OceanReading)super.clone(); @@ -40,8 +39,7 @@ public DepthReading getDepthReading() { public void setDepthReading(DepthReading dr) { this.depth = dr; } - @Override - public String toString() { + @Override public String toString() { return "temperature: " + temperature + ", depth: " + depth; } diff --git a/references/PassReferences.java b/references/PassReferences.java index effa9ca69..1bd397438 100644 --- a/references/PassReferences.java +++ b/references/PassReferences.java @@ -1,5 +1,5 @@ // references/PassReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -14,6 +14,6 @@ public static void main(String[] args) { } } /* Output: -p inside main(): PassReferences@15db9742 -h inside f(): PassReferences@15db9742 +p inside main(): PassReferences@19e0bfd +h inside f(): PassReferences@19e0bfd */ diff --git a/references/SimplerMutableInteger.java b/references/SimplerMutableInteger.java index c49ceb5eb..1da86b7be 100644 --- a/references/SimplerMutableInteger.java +++ b/references/SimplerMutableInteger.java @@ -1,5 +1,5 @@ // references/SimplerMutableInteger.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A trivial wrapper class diff --git a/references/Snake.java b/references/Snake.java index 624855490..f45ec7950 100644 --- a/references/Snake.java +++ b/references/Snake.java @@ -1,5 +1,5 @@ // references/Snake.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Tests cloning to see if reference @@ -19,15 +19,13 @@ public void increment() { if(next != null) next.increment(); } - @Override - public String toString() { + @Override public String toString() { String s = ":" + c; if(next != null) s += next.toString(); return s; } - @Override - public Snake clone() { + @Override public Snake clone() { try { return (Snake)super.clone(); } catch(CloneNotSupportedException e) { diff --git a/references/Stringer.java b/references/Stringer.java deleted file mode 100644 index 89ceff1e6..000000000 --- a/references/Stringer.java +++ /dev/null @@ -1,22 +0,0 @@ -// references/Stringer.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. - -public class Stringer { - public static String upcase(String s) { - return s.toUpperCase(); - } - public static void main(String[] args) { - String q = new String("howdy"); - System.out.println(q); // howdy - String qq = upcase(q); - System.out.println(qq); // HOWDY - System.out.println(q); // howdy - } -} -/* Output: -howdy -HOWDY -howdy -*/ diff --git a/references/TemperatureReading.java b/references/TemperatureReading.java index 8ca47e90f..8f9afff6d 100644 --- a/references/TemperatureReading.java +++ b/references/TemperatureReading.java @@ -1,5 +1,5 @@ // references/TemperatureReading.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Cloning a composed object @@ -12,8 +12,7 @@ public TemperatureReading(double temperature) { time = System.currentTimeMillis(); this.temperature = temperature; } - @Override - public TemperatureReading clone() { + @Override public TemperatureReading clone() { try { return (TemperatureReading)super.clone(); } catch(CloneNotSupportedException e) { @@ -26,8 +25,7 @@ public double getTemperature() { public void setTemperature(double temp) { this.temperature = temp; } - @Override - public String toString() { + @Override public String toString() { return String.valueOf(temperature); } } diff --git a/references/tests/DeepCopyTest.java b/references/tests/DeepCopyTest.java index 977376520..5a7fcb6d5 100644 --- a/references/tests/DeepCopyTest.java +++ b/references/tests/DeepCopyTest.java @@ -1,5 +1,5 @@ // references/tests/DeepCopyTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package references; diff --git a/typeinfo/AnonymousImplementation.java b/reflection/AnonymousImplementation.java similarity index 88% rename from typeinfo/AnonymousImplementation.java rename to reflection/AnonymousImplementation.java index 5c4a2518c..290798bbf 100644 --- a/typeinfo/AnonymousImplementation.java +++ b/reflection/AnonymousImplementation.java @@ -1,14 +1,14 @@ -// typeinfo/AnonymousImplementation.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/AnonymousImplementation.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Anonymous inner classes can't hide from reflection -import typeinfo.interfacea.*; +import reflection.interfacea.*; class AnonymousA { public static A makeA() { return new A() { - public void f() { + @Override public void f() { System.out.println("public C.f()"); } public void g() { diff --git a/typeinfo/BoundedClassReferences.java b/reflection/BoundedClassReferences.java similarity index 80% rename from typeinfo/BoundedClassReferences.java rename to reflection/BoundedClassReferences.java index ace4a4691..6d2960591 100644 --- a/typeinfo/BoundedClassReferences.java +++ b/reflection/BoundedClassReferences.java @@ -1,5 +1,5 @@ -// typeinfo/BoundedClassReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/BoundedClassReferences.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/typeinfo/ClassCasts.java b/reflection/ClassCasts.java similarity index 84% rename from typeinfo/ClassCasts.java rename to reflection/ClassCasts.java index a44573d5e..3efd64c39 100644 --- a/typeinfo/ClassCasts.java +++ b/reflection/ClassCasts.java @@ -1,5 +1,5 @@ -// typeinfo/ClassCasts.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/ClassCasts.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/typeinfo/ClassInitialization.java b/reflection/ClassInitialization.java similarity index 89% rename from typeinfo/ClassInitialization.java rename to reflection/ClassInitialization.java index 262649372..21b711338 100644 --- a/typeinfo/ClassInitialization.java +++ b/reflection/ClassInitialization.java @@ -1,5 +1,5 @@ -// typeinfo/ClassInitialization.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/ClassInitialization.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -35,9 +35,9 @@ public class ClassInitialization { System.out.println("After creating Initable ref"); // Does not trigger initialization: System.out.println(Initable.STATIC_FINAL); - // Does trigger initialization: + // Triggers initialization: System.out.println(Initable.STATIC_FINAL2); - // Does trigger initialization: + // Triggers initialization: System.out.println(Initable2.staticNonFinal); Class initable3 = Class.forName("Initable3"); System.out.println("After creating Initable3 ref"); diff --git a/typeinfo/DynamicSupplier.java b/reflection/DynamicSupplier.java similarity index 59% rename from typeinfo/DynamicSupplier.java rename to reflection/DynamicSupplier.java index 86e47ddf1..910d12154 100644 --- a/typeinfo/DynamicSupplier.java +++ b/reflection/DynamicSupplier.java @@ -1,16 +1,19 @@ -// typeinfo/DynamicSupplier.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/DynamicSupplier.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; import java.util.stream.*; - -class CountedInteger { +class ID { private static long counter; private final long id = counter++; - @Override - public String toString() { return Long.toString(id); } + @Override public String toString() { + return Long.toString(id); + } + // A public default constructor is required + // to call getConstructor().newInstance(): + public ID() {} } public class DynamicSupplier implements Supplier { @@ -18,17 +21,16 @@ public class DynamicSupplier implements Supplier { public DynamicSupplier(Class type) { this.type = type; } - public T get() { + @Override public T get() { try { - return type.newInstance(); - } catch(InstantiationException | - IllegalAccessException e) { + return type.getConstructor().newInstance(); + } catch(Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { Stream.generate( - new DynamicSupplier<>(CountedInteger.class)) + new DynamicSupplier<>(ID.class)) .skip(10) .limit(5) .forEach(System.out::println); diff --git a/typeinfo/FamilyVsExactType.java b/reflection/FamilyVsExactType.java similarity index 88% rename from typeinfo/FamilyVsExactType.java rename to reflection/FamilyVsExactType.java index 9fdfd25e2..db2bc9daf 100644 --- a/typeinfo/FamilyVsExactType.java +++ b/reflection/FamilyVsExactType.java @@ -1,10 +1,10 @@ -// typeinfo/FamilyVsExactType.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/FamilyVsExactType.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The difference between instanceof and class -// {java typeinfo.FamilyVsExactType} -package typeinfo; +// {java reflection.FamilyVsExactType} +package reflection; class Base {} class Derived extends Base {} @@ -41,7 +41,7 @@ public static void main(String[] args) { } } /* Output: -Testing x of type class typeinfo.Base +Testing x of type class reflection.Base x instanceof Base true x instanceof Derived false Base.isInstance(x) true @@ -50,7 +50,7 @@ public static void main(String[] args) { x.getClass() == Derived.class false x.getClass().equals(Base.class)) true x.getClass().equals(Derived.class)) false -Testing x of type class typeinfo.Derived +Testing x of type class reflection.Derived x instanceof Base true x instanceof Derived true Base.isInstance(x) true diff --git a/typeinfo/GenericClassReferences.java b/reflection/GenericClassReferences.java similarity index 83% rename from typeinfo/GenericClassReferences.java rename to reflection/GenericClassReferences.java index b75f853f8..66601f93c 100644 --- a/typeinfo/GenericClassReferences.java +++ b/reflection/GenericClassReferences.java @@ -1,14 +1,14 @@ -// typeinfo/GenericClassReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/GenericClassReferences.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. public class GenericClassReferences { public static void main(String[] args) { Class intClass = int.class; + intClass = double.class; Class genericIntClass = int.class; genericIntClass = Integer.class; // Same thing - intClass = double.class; // genericIntClass = double.class; // Illegal } } diff --git a/typeinfo/HiddenImplementation.java b/reflection/HiddenImplementation.java similarity index 84% rename from typeinfo/HiddenImplementation.java rename to reflection/HiddenImplementation.java index 8b23d97d7..1d536d309 100644 --- a/typeinfo/HiddenImplementation.java +++ b/reflection/HiddenImplementation.java @@ -1,10 +1,10 @@ -// typeinfo/HiddenImplementation.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/HiddenImplementation.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Sneaking around package hiding -import typeinfo.interfacea.*; -import typeinfo.packageaccess.*; +import reflection.interfacea.*; +import reflection.packageaccess.*; import java.lang.reflect.*; public class HiddenImplementation { @@ -36,7 +36,7 @@ public class HiddenImplementation { } /* Output: public C.f() -typeinfo.packageaccess.C +reflection.packageaccess.C public C.g() package C.u() protected C.v() diff --git a/reflection/ID2.java b/reflection/ID2.java new file mode 100644 index 000000000..6ff472af1 --- /dev/null +++ b/reflection/ID2.java @@ -0,0 +1,27 @@ +// reflection/ID2.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.stream.*; + +public class ID2 { + private static long counter; + private final long id = counter++; + @Override public String toString() { + return Long.toString(id); + } + public static void main(String[] args) { + Stream.generate( + new DynamicSupplier<>(ID2.class)) + .skip(10) + .limit(5) + .forEach(System.out::println); + } +} +/* Output: +10 +11 +12 +13 +14 +*/ diff --git a/typeinfo/InnerImplementation.java b/reflection/InnerImplementation.java similarity index 84% rename from typeinfo/InnerImplementation.java rename to reflection/InnerImplementation.java index d9b9202c2..248049c27 100644 --- a/typeinfo/InnerImplementation.java +++ b/reflection/InnerImplementation.java @@ -1,13 +1,13 @@ -// typeinfo/InnerImplementation.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/InnerImplementation.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// Private inner classes can't hide from reflection -import typeinfo.interfacea.*; +// Private inner classes can't hide from reflection. +import reflection.interfacea.*; class InnerA { private static class C implements A { - public void f() { + @Override public void f() { System.out.println("public C.f()"); } public void g() { diff --git a/typeinfo/InterfaceViolation.java b/reflection/InterfaceViolation.java similarity index 76% rename from typeinfo/InterfaceViolation.java rename to reflection/InterfaceViolation.java index 0adfba652..ef8bfc954 100644 --- a/typeinfo/InterfaceViolation.java +++ b/reflection/InterfaceViolation.java @@ -1,12 +1,12 @@ -// typeinfo/InterfaceViolation.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/InterfaceViolation.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Sneaking around an interface -import typeinfo.interfacea.*; +import reflection.interfacea.*; class B implements A { - public void f() {} + @Override public void f() {} public void g() {} } diff --git a/typeinfo/ModifyingPrivateFields.java b/reflection/ModifyingPrivateFields.java similarity index 91% rename from typeinfo/ModifyingPrivateFields.java rename to reflection/ModifyingPrivateFields.java index 5f1baf11c..99b929531 100644 --- a/typeinfo/ModifyingPrivateFields.java +++ b/reflection/ModifyingPrivateFields.java @@ -1,5 +1,5 @@ -// typeinfo/ModifyingPrivateFields.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/ModifyingPrivateFields.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.reflect.*; @@ -8,8 +8,7 @@ class WithPrivateFinalField { private int i = 1; private final String s = "I'm totally safe"; private String s2 = "Am I safe?"; - @Override - public String toString() { + @Override public String toString() { return "i = " + i + ", " + s + ", " + s2; } } diff --git a/typeinfo/NullRobot.java b/reflection/NullRobot.java similarity index 81% rename from typeinfo/NullRobot.java rename to reflection/NullRobot.java index 45380aa59..c3e19659f 100644 --- a/typeinfo/NullRobot.java +++ b/reflection/NullRobot.java @@ -1,5 +1,5 @@ -// typeinfo/NullRobot.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/NullRobot.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using a dynamic proxy to create an Optional @@ -20,13 +20,11 @@ private class NRobot implements Null, Robot { public String name() { return nullName; } @Override public String model() { return nullName; } - @Override - public List operations() { + @Override public List operations() { return Collections.emptyList(); } } - @Override - public Object + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(proxied, args); @@ -43,8 +41,8 @@ public class NullRobot { } public static void main(String[] args) { Stream.of( - new SnowRemovalRobot("SnowBee"), - newNullRobot(SnowRemovalRobot.class) + new SnowRobot("SnowBee"), + newNullRobot(SnowRobot.class) ).forEach(Robot::test); } } @@ -58,6 +56,6 @@ public static void main(String[] args) { SnowBee can clear the roof SnowBee clearing roof [Null Robot] -Robot name: SnowRemovalRobot NullRobot -Robot model: SnowRemovalRobot NullRobot +Robot name: SnowRobot NullRobot +Robot model: SnowRobot NullRobot */ diff --git a/typeinfo/Operation.java b/reflection/Operation.java similarity index 83% rename from typeinfo/Operation.java rename to reflection/Operation.java index 2393d2365..4b749e7d1 100644 --- a/typeinfo/Operation.java +++ b/reflection/Operation.java @@ -1,5 +1,5 @@ -// typeinfo/Operation.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/Operation.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; diff --git a/typeinfo/Person.java b/reflection/Person.java similarity index 92% rename from typeinfo/Person.java rename to reflection/Person.java index 9c6a9657b..070a2490f 100644 --- a/typeinfo/Person.java +++ b/reflection/Person.java @@ -1,5 +1,5 @@ -// typeinfo/Person.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/Person.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using Optional with regular classes @@ -25,8 +25,7 @@ class Person { } Person(String last) { this(null, last, null); } Person() { this(null, null, null); } - @Override - public String toString() { + @Override public String toString() { if(empty) return ""; return (first.orElse("") + diff --git a/reflection/PetCounter.java b/reflection/PetCounter.java new file mode 100644 index 000000000..974880620 --- /dev/null +++ b/reflection/PetCounter.java @@ -0,0 +1,64 @@ +// reflection/PetCounter.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using instanceof +import reflection.pets.*; +import java.util.*; + +public class PetCounter { + static class Counter extends HashMap { + public void count(String type) { + Integer quantity = get(type); + if(quantity == null) + put(type, 1); + else + put(type, quantity + 1); + } + } + private Counter counter = new Counter(); + private void countPet(Pet pet) { + System.out.print( + pet.getClass().getSimpleName() + " "); + if(pet instanceof Pet) + counter.count("Pet"); + if(pet instanceof Dog) + counter.count("Dog"); + if(pet instanceof Mutt) + counter.count("Mutt"); + if(pet instanceof Pug) + counter.count("Pug"); + if(pet instanceof Cat) + counter.count("Cat"); + if(pet instanceof EgyptianMau) + counter.count("EgyptianMau"); + if(pet instanceof Manx) + counter.count("Manx"); + if(pet instanceof Cymric) + counter.count("Cymric"); + if(pet instanceof Rodent) + counter.count("Rodent"); + if(pet instanceof Rat) + counter.count("Rat"); + if(pet instanceof Mouse) + counter.count("Mouse"); + if(pet instanceof Hamster) + counter.count("Hamster"); + } + public void count(Creator creator) { + creator.stream().limit(20) + .forEach(pet -> countPet(pet)); + System.out.println(); + System.out.println(counter); + } + public static void main(String[] args) { + new PetCounter().count(new ForNamePetCreator()); + } +} +/* Output: +Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, +Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} +*/ diff --git a/typeinfo/PetCount2.java b/reflection/PetCounter2.java similarity index 70% rename from typeinfo/PetCount2.java rename to reflection/PetCounter2.java index 1e5ef4d70..ccac0b57f 100644 --- a/typeinfo/PetCount2.java +++ b/reflection/PetCounter2.java @@ -1,12 +1,12 @@ -// typeinfo/PetCount2.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/PetCounter2.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; -public class PetCount2 { +public class PetCounter2 { public static void main(String[] args) { - PetCount.countPets(Pets.CREATOR); + new PetCounter().count(new PetCreator()); } } /* Output: diff --git a/typeinfo/PetCount3.java b/reflection/PetCounter3.java similarity index 73% rename from typeinfo/PetCount3.java rename to reflection/PetCounter3.java index 87635bb08..aec88ef0b 100644 --- a/typeinfo/PetCount3.java +++ b/reflection/PetCounter3.java @@ -1,19 +1,19 @@ -// typeinfo/PetCount3.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/PetCounter3.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using isInstance() import java.util.*; import java.util.stream.*; import onjava.*; -import typeinfo.pets.*; +import reflection.pets.*; -public class PetCount3 { +public class PetCounter3 { static class Counter extends - LinkedHashMap, Integer> { + HashMap, Integer> { Counter() { - super(LiteralPetCreator.ALL_TYPES.stream() - .map(lpc -> Pair.make(lpc, 0)) + super(PetCreator.ALL_TYPES.stream() + .map(type -> Pair.make(type, 0)) .collect( Collectors.toMap(Pair::key, Pair::value))); } @@ -24,8 +24,7 @@ public void count(Pet pet) { .forEach(pair -> put(pair.getKey(), pair.getValue() + 1)); } - @Override - public String toString() { + @Override public String toString() { String result = entrySet().stream() .map(pair -> String.format("%s=%s", pair.getKey().getSimpleName(), @@ -36,7 +35,7 @@ public String toString() { } public static void main(String[] args) { Counter petCount = new Counter(); - Pets.stream() + new PetCreator().stream() .limit(20) .peek(petCount::count) .forEach(p -> System.out.print( @@ -48,6 +47,7 @@ public static void main(String[] args) { Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric -{Rat=2, Pug=3, Mutt=3, Mouse=2, Cat=9, Dog=6, Cymric=5, -EgyptianMau=2, Rodent=5, Hamster=1, Manx=7, Pet=20} +{EgyptianMau=2, Mouse=2, Pet=20, Cymric=5, Rat=2, +Dog=6, Mutt=3, Hamster=1, Cat=9, Manx=7, Rodent=5, +Pug=3} */ diff --git a/typeinfo/PetCount4.java b/reflection/PetCounter4.java similarity index 67% rename from typeinfo/PetCount4.java rename to reflection/PetCounter4.java index ab18aee05..9015e66c7 100644 --- a/typeinfo/PetCount4.java +++ b/reflection/PetCounter4.java @@ -1,14 +1,14 @@ -// typeinfo/PetCount4.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/PetCounter4.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import reflection.pets.*; import onjava.*; -public class PetCount4 { +public class PetCounter4 { public static void main(String[] args) { TypeCounter counter = new TypeCounter(Pet.class); - Pets.stream() + new PetCreator().stream() .limit(20) .peek(counter::count) .forEach(p -> System.out.print( @@ -20,7 +20,7 @@ public static void main(String[] args) { Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric -{Dog=6, Manx=7, Cat=9, Rodent=5, Hamster=1, Rat=2, -Pug=3, Mutt=3, Cymric=5, EgyptianMau=2, Pet=20, -Mouse=2} +{Rodent=5, Mouse=2, Hamster=1, Cymric=5, Dog=6, +EgyptianMau=2, Pet=20, Rat=2, Pug=3, Manx=7, Cat=9, +Mutt=3} */ diff --git a/typeinfo/Position.java b/reflection/Position.java similarity index 92% rename from typeinfo/Position.java rename to reflection/Position.java index 1912bb956..ea07ca78f 100644 --- a/typeinfo/Position.java +++ b/reflection/Position.java @@ -1,5 +1,5 @@ -// typeinfo/Position.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/Position.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -28,8 +28,7 @@ public void setPerson(Person newPerson) { person = Optional.ofNullable(newPerson) .orElse(new Person()); } - @Override - public String toString() { + @Override public String toString() { return "Position: " + title + ", Employee: " + person; } diff --git a/typeinfo/RegisteredFactories.java b/reflection/RegisteredFactories.java similarity index 86% rename from typeinfo/RegisteredFactories.java rename to reflection/RegisteredFactories.java index 358bba1a7..04267c425 100644 --- a/typeinfo/RegisteredFactories.java +++ b/reflection/RegisteredFactories.java @@ -1,5 +1,5 @@ -// typeinfo/RegisteredFactories.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/RegisteredFactories.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Registering Factories in the base class @@ -8,8 +8,7 @@ import java.util.stream.*; class Part implements Supplier { - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName(); } static List> prototypes = @@ -23,7 +22,7 @@ public String toString() { new GeneratorBelt() ); private static Random rand = new Random(47); - public Part get() { + @Override public Part get() { int n = rand.nextInt(prototypes.size()); return prototypes.get(n).get(); } @@ -42,8 +41,7 @@ class AirFilter extends Filter { } class CabinAirFilter extends Filter { - @Override - public CabinAirFilter get() { + @Override public CabinAirFilter get() { return new CabinAirFilter(); } } @@ -61,15 +59,13 @@ class FanBelt extends Belt { } class GeneratorBelt extends Belt { - @Override - public GeneratorBelt get() { + @Override public GeneratorBelt get() { return new GeneratorBelt(); } } class PowerSteeringBelt extends Belt { - @Override - public PowerSteeringBelt get() { + @Override public PowerSteeringBelt get() { return new PowerSteeringBelt(); } } diff --git a/typeinfo/Robot.java b/reflection/Robot.java similarity index 89% rename from typeinfo/Robot.java rename to reflection/Robot.java index f3c8d0534..00818d378 100644 --- a/typeinfo/Robot.java +++ b/reflection/Robot.java @@ -1,5 +1,5 @@ -// typeinfo/Robot.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/Robot.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import onjava.*; diff --git a/typeinfo/SelectingMethods.java b/reflection/SelectingMethods.java similarity index 83% rename from typeinfo/SelectingMethods.java rename to reflection/SelectingMethods.java index 14c8058ab..9002cf356 100644 --- a/typeinfo/SelectingMethods.java +++ b/reflection/SelectingMethods.java @@ -1,5 +1,5 @@ -// typeinfo/SelectingMethods.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/SelectingMethods.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Looking for particular methods in a dynamic proxy @@ -10,8 +10,7 @@ class MethodSelector implements InvocationHandler { MethodSelector(Object proxied) { this.proxied = proxied; } - @Override - public Object + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("interesting")) @@ -29,20 +28,16 @@ interface SomeMethods { } class Implementation implements SomeMethods { - @Override - public void boring1() { + @Override public void boring1() { System.out.println("boring1"); } - @Override - public void boring2() { + @Override public void boring2() { System.out.println("boring2"); } - @Override - public void interesting(String arg) { + @Override public void interesting(String arg) { System.out.println("interesting " + arg); } - @Override - public void boring3() { + @Override public void boring3() { System.out.println("boring3"); } } diff --git a/typeinfo/Shapes.java b/reflection/Shapes.java similarity index 57% rename from typeinfo/Shapes.java rename to reflection/Shapes.java index 9af68532d..05d15df5c 100644 --- a/typeinfo/Shapes.java +++ b/reflection/Shapes.java @@ -1,28 +1,32 @@ -// typeinfo/Shapes.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/Shapes.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; abstract class Shape { - void draw() { System.out.println(this + ".draw()"); } - @Override - public abstract String toString(); + void draw() { + System.out.println(this + ".draw()"); + } + @Override public abstract String toString(); } class Circle extends Shape { - @Override - public String toString() { return "Circle"; } + @Override public String toString() { + return "Circle"; + } } class Square extends Shape { - @Override - public String toString() { return "Square"; } + @Override public String toString() { + return "Square"; + } } class Triangle extends Shape { - @Override - public String toString() { return "Triangle"; } + @Override public String toString() { + return "Triangle"; + } } public class Shapes { diff --git a/typeinfo/ShowMethods.java b/reflection/ShowMethods.java similarity index 96% rename from typeinfo/ShowMethods.java rename to reflection/ShowMethods.java index 91aef15a8..48024cdc4 100644 --- a/typeinfo/ShowMethods.java +++ b/reflection/ShowMethods.java @@ -1,5 +1,5 @@ -// typeinfo/ShowMethods.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/ShowMethods.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using reflection to show all the methods of a class, @@ -56,11 +56,11 @@ public static void main(String[] args) { } /* Output: public static void main(String[]) -public final void wait() throws InterruptedException public final void wait(long,int) throws InterruptedException public final native void wait(long) throws InterruptedException +public final void wait() throws InterruptedException public boolean equals(Object) public String toString() public native int hashCode() diff --git a/typeinfo/SimpleDynamicProxy.java b/reflection/SimpleDynamicProxy.java similarity index 91% rename from typeinfo/SimpleDynamicProxy.java rename to reflection/SimpleDynamicProxy.java index 041c13806..9eeb02926 100644 --- a/typeinfo/SimpleDynamicProxy.java +++ b/reflection/SimpleDynamicProxy.java @@ -1,5 +1,5 @@ -// typeinfo/SimpleDynamicProxy.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/SimpleDynamicProxy.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.lang.reflect.*; @@ -9,8 +9,7 @@ class DynamicProxyHandler implements InvocationHandler { DynamicProxyHandler(Object proxied) { this.proxied = proxied; } - @Override - public Object + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println( @@ -47,7 +46,7 @@ public static void main(String[] args) { doSomething **** proxy: class $Proxy0, method: public abstract void Interface.somethingElse(java.lang.String), args: -[Ljava.lang.Object;@6bc7c054 +[Ljava.lang.Object;@1b84c92 bonobo somethingElse bonobo */ diff --git a/typeinfo/SimpleProxyDemo.java b/reflection/SimpleProxyDemo.java similarity index 79% rename from typeinfo/SimpleProxyDemo.java rename to reflection/SimpleProxyDemo.java index 4ea8fea3d..24f7b0166 100644 --- a/typeinfo/SimpleProxyDemo.java +++ b/reflection/SimpleProxyDemo.java @@ -1,5 +1,5 @@ -// typeinfo/SimpleProxyDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/SimpleProxyDemo.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,12 +9,10 @@ interface Interface { } class RealObject implements Interface { - @Override - public void doSomething() { + @Override public void doSomething() { System.out.println("doSomething"); } - @Override - public void somethingElse(String arg) { + @Override public void somethingElse(String arg) { System.out.println("somethingElse " + arg); } } @@ -24,13 +22,11 @@ class SimpleProxy implements Interface { SimpleProxy(Interface proxied) { this.proxied = proxied; } - @Override - public void doSomething() { + @Override public void doSomething() { System.out.println("SimpleProxy doSomething"); proxied.doSomething(); } - @Override - public void somethingElse(String arg) { + @Override public void somethingElse(String arg) { System.out.println( "SimpleProxy somethingElse " + arg); proxied.somethingElse(arg); diff --git a/typeinfo/SnowRemovalRobot.java b/reflection/SnowRobot.java similarity index 73% rename from typeinfo/SnowRemovalRobot.java rename to reflection/SnowRobot.java index 0f3b4c0bf..227dcb49d 100644 --- a/typeinfo/SnowRemovalRobot.java +++ b/reflection/SnowRobot.java @@ -1,18 +1,18 @@ -// typeinfo/SnowRemovalRobot.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/SnowRobot.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; -public class SnowRemovalRobot implements Robot { +public class SnowRobot implements Robot { private String name; - public SnowRemovalRobot(String name) { + public SnowRobot(String name) { this.name = name; } - @Override - public String name() { return name; } - @Override - public String model() { return "SnowBot Series 11"; } + @Override public String name() { return name; } + @Override public String model() { + return "SnowBot Series 11"; + } private List ops = Arrays.asList( new Operation( () -> name + " can shovel snow", @@ -25,9 +25,10 @@ public SnowRemovalRobot(String name) { () -> name + " can clear the roof", () -> System.out.println( name + " clearing roof"))); + @Override public List operations() { return ops; } public static void main(String[] args) { - Robot.test(new SnowRemovalRobot("Slusher")); + Robot.test(new SnowRobot("Slusher")); } } /* Output: diff --git a/typeinfo/Staff.java b/reflection/Staff.java similarity index 97% rename from typeinfo/Staff.java rename to reflection/Staff.java index 4d864e1df..8c3bb76e8 100644 --- a/typeinfo/Staff.java +++ b/reflection/Staff.java @@ -1,5 +1,5 @@ -// typeinfo/Staff.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/Staff.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/typeinfo/SweetShop.java b/reflection/SweetShop.java similarity index 92% rename from typeinfo/SweetShop.java rename to reflection/SweetShop.java index a1000ea3f..d5f964f0a 100644 --- a/typeinfo/SweetShop.java +++ b/reflection/SweetShop.java @@ -1,5 +1,5 @@ -// typeinfo/SweetShop.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/SweetShop.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Examination of the way the class loader works diff --git a/typeinfo/WildcardClassReferences.java b/reflection/WildcardClassReferences.java similarity index 75% rename from typeinfo/WildcardClassReferences.java rename to reflection/WildcardClassReferences.java index 9a35b6e54..d7266f732 100644 --- a/typeinfo/WildcardClassReferences.java +++ b/reflection/WildcardClassReferences.java @@ -1,5 +1,5 @@ -// typeinfo/WildcardClassReferences.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/WildcardClassReferences.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/typeinfo/interfacea/A.java b/reflection/interfacea/A.java similarity index 59% rename from typeinfo/interfacea/A.java rename to reflection/interfacea/A.java index 565a4a74d..2b4c33ec9 100644 --- a/typeinfo/interfacea/A.java +++ b/reflection/interfacea/A.java @@ -1,8 +1,8 @@ -// typeinfo/interfacea/A.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/interfacea/A.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.interfacea; +package reflection.interfacea; public interface A { void f(); diff --git a/typeinfo/packageaccess/HiddenC.java b/reflection/packageaccess/HiddenC.java similarity index 74% rename from typeinfo/packageaccess/HiddenC.java rename to reflection/packageaccess/HiddenC.java index 80938a066..24fb20d4b 100644 --- a/typeinfo/packageaccess/HiddenC.java +++ b/reflection/packageaccess/HiddenC.java @@ -1,13 +1,12 @@ -// typeinfo/packageaccess/HiddenC.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/packageaccess/HiddenC.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.packageaccess; -import typeinfo.interfacea.*; +package reflection.packageaccess; +import reflection.interfacea.*; class C implements A { - @Override - public void f() { + @Override public void f() { System.out.println("public C.f()"); } public void g() { diff --git a/typeinfo/pets/Cat.java b/reflection/pets/Cat.java similarity index 70% rename from typeinfo/pets/Cat.java rename to reflection/pets/Cat.java index f1bfdc0ea..2ed2aba94 100644 --- a/typeinfo/pets/Cat.java +++ b/reflection/pets/Cat.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Cat.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Cat.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Cat extends Pet { public Cat(String name) { super(name); } diff --git a/reflection/pets/Creator.java b/reflection/pets/Creator.java new file mode 100644 index 000000000..f5f152fe8 --- /dev/null +++ b/reflection/pets/Creator.java @@ -0,0 +1,38 @@ +// reflection/pets/Creator.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Creates random Pets +package reflection.pets; +import java.util.*; +import java.util.function.*; +import java.util.stream.*; +import java.lang.reflect.InvocationTargetException; + +public abstract class Creator implements Supplier { + private Random rand = new Random(47); + // The different types of Pet to create: + public abstract List> types(); + @Override public Pet get() { // Create one random Pet + int n = rand.nextInt(types().size()); + try { + return types().get(n) + .getConstructor().newInstance(); + } catch(InstantiationException | + NoSuchMethodException | + InvocationTargetException | + IllegalAccessException e) { + throw new RuntimeException(e); + } + } + public Stream stream() { + return Stream.generate(this); + } + public Pet[] array(int size) { + return stream().limit(size).toArray(Pet[]::new); + } + public List list(int size) { + return stream().limit(size) + .collect(Collectors.toCollection(ArrayList::new)); + } +} diff --git a/typeinfo/pets/Cymric.java b/reflection/pets/Cymric.java similarity index 70% rename from typeinfo/pets/Cymric.java rename to reflection/pets/Cymric.java index c6f0a59ca..11521fe85 100644 --- a/typeinfo/pets/Cymric.java +++ b/reflection/pets/Cymric.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Cymric.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Cymric.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Cymric extends Manx { public Cymric(String name) { super(name); } diff --git a/typeinfo/pets/Dog.java b/reflection/pets/Dog.java similarity index 70% rename from typeinfo/pets/Dog.java rename to reflection/pets/Dog.java index 0f1144a08..abd370ff2 100644 --- a/typeinfo/pets/Dog.java +++ b/reflection/pets/Dog.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Dog.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Dog.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Dog extends Pet { public Dog(String name) { super(name); } diff --git a/typeinfo/pets/EgyptianMau.java b/reflection/pets/EgyptianMau.java similarity index 70% rename from typeinfo/pets/EgyptianMau.java rename to reflection/pets/EgyptianMau.java index 243294678..4e314fb63 100644 --- a/typeinfo/pets/EgyptianMau.java +++ b/reflection/pets/EgyptianMau.java @@ -1,8 +1,8 @@ -// typeinfo/pets/EgyptianMau.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/EgyptianMau.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class EgyptianMau extends Cat { public EgyptianMau(String name) { super(name); } diff --git a/typeinfo/pets/ForNameCreator.java b/reflection/pets/ForNamePetCreator.java similarity index 57% rename from typeinfo/pets/ForNameCreator.java rename to reflection/pets/ForNamePetCreator.java index e3bb51c77..92648db5d 100644 --- a/typeinfo/pets/ForNameCreator.java +++ b/reflection/pets/ForNamePetCreator.java @@ -1,23 +1,23 @@ -// typeinfo/pets/ForNameCreator.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/ForNamePetCreator.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; import java.util.*; -public class ForNameCreator extends PetCreator { +public class ForNamePetCreator extends Creator { private static List> types = new ArrayList<>(); // Types you want randomly created: private static String[] typeNames = { - "typeinfo.pets.Mutt", - "typeinfo.pets.Pug", - "typeinfo.pets.EgyptianMau", - "typeinfo.pets.Manx", - "typeinfo.pets.Cymric", - "typeinfo.pets.Rat", - "typeinfo.pets.Mouse", - "typeinfo.pets.Hamster" + "reflection.pets.Mutt", + "reflection.pets.Pug", + "reflection.pets.EgyptianMau", + "reflection.pets.Manx", + "reflection.pets.Cymric", + "reflection.pets.Rat", + "reflection.pets.Mouse", + "reflection.pets.Hamster" }; @SuppressWarnings("unchecked") private static void loader() { @@ -30,8 +30,7 @@ private static void loader() { } } static { loader(); } - @Override - public List> types() { + @Override public List> types() { return types; } } diff --git a/typeinfo/pets/Hamster.java b/reflection/pets/Hamster.java similarity index 70% rename from typeinfo/pets/Hamster.java rename to reflection/pets/Hamster.java index f2cc83799..fb09f3ab8 100644 --- a/typeinfo/pets/Hamster.java +++ b/reflection/pets/Hamster.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Hamster.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Hamster.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Hamster extends Rodent { public Hamster(String name) { super(name); } diff --git a/typeinfo/pets/Individual.java b/reflection/pets/Individual.java similarity index 79% rename from typeinfo/pets/Individual.java rename to reflection/pets/Individual.java index f7e7d204b..524fba6e4 100644 --- a/typeinfo/pets/Individual.java +++ b/reflection/pets/Individual.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Individual.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Individual.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; import java.util.*; public class @@ -13,23 +13,19 @@ public Individual(String name) { this.name = name; } // 'name' is optional: public Individual() {} - @Override - public String toString() { + @Override public String toString() { return getClass().getSimpleName() + (name == null ? "" : " " + name); } public long id() { return id; } - @Override - public boolean equals(Object o) { + @Override public boolean equals(Object o) { return o instanceof Individual && Objects.equals(id, ((Individual)o).id); } - @Override - public int hashCode() { + @Override public int hashCode() { return Objects.hash(name, id); } - @Override - public int compareTo(Individual arg) { + @Override public int compareTo(Individual arg) { // Compare by class name first: String first = getClass().getSimpleName(); String argFirst = arg.getClass().getSimpleName(); diff --git a/typeinfo/pets/Manx.java b/reflection/pets/Manx.java similarity index 70% rename from typeinfo/pets/Manx.java rename to reflection/pets/Manx.java index b7771c7cc..a5c6bea91 100644 --- a/typeinfo/pets/Manx.java +++ b/reflection/pets/Manx.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Manx.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Manx.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Manx extends Cat { public Manx(String name) { super(name); } diff --git a/typeinfo/pets/Mouse.java b/reflection/pets/Mouse.java similarity index 70% rename from typeinfo/pets/Mouse.java rename to reflection/pets/Mouse.java index 6d267cdbb..9ad9b290d 100644 --- a/typeinfo/pets/Mouse.java +++ b/reflection/pets/Mouse.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Mouse.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Mouse.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Mouse extends Rodent { public Mouse(String name) { super(name); } diff --git a/typeinfo/pets/Mutt.java b/reflection/pets/Mutt.java similarity index 70% rename from typeinfo/pets/Mutt.java rename to reflection/pets/Mutt.java index 7c41712bc..f50ba64de 100644 --- a/typeinfo/pets/Mutt.java +++ b/reflection/pets/Mutt.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Mutt.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Mutt.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Mutt extends Dog { public Mutt(String name) { super(name); } diff --git a/typeinfo/pets/Person.java b/reflection/pets/Person.java similarity index 67% rename from typeinfo/pets/Person.java rename to reflection/pets/Person.java index 1a6532667..bfe61ca3b 100644 --- a/typeinfo/pets/Person.java +++ b/reflection/pets/Person.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Person.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Person.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Person extends Individual { public Person(String name) { super(name); } diff --git a/typeinfo/pets/Pet.java b/reflection/pets/Pet.java similarity index 70% rename from typeinfo/pets/Pet.java rename to reflection/pets/Pet.java index 282418f8c..a3a0cf2ed 100644 --- a/typeinfo/pets/Pet.java +++ b/reflection/pets/Pet.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Pet.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Pet.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Pet extends Individual { public Pet(String name) { super(name); } diff --git a/typeinfo/pets/LiteralPetCreator.java b/reflection/pets/PetCreator.java similarity index 51% rename from typeinfo/pets/LiteralPetCreator.java rename to reflection/pets/PetCreator.java index dd32d7ea3..1f01ceed3 100644 --- a/typeinfo/pets/LiteralPetCreator.java +++ b/reflection/pets/PetCreator.java @@ -1,17 +1,16 @@ -// typeinfo/pets/LiteralPetCreator.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/PetCreator.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using class literals -// {java typeinfo.pets.LiteralPetCreator} -package typeinfo.pets; +// {java reflection.pets.PetCreator} +package reflection.pets; import java.util.*; -public class LiteralPetCreator extends PetCreator { +public class PetCreator extends Creator { // No try block needed. - @SuppressWarnings("unchecked") - public static - final List> ALL_TYPES = + public static final + List> ALL_TYPES = Collections.unmodifiableList(Arrays.asList( Pet.class, Dog.class, Cat.class, Rodent.class, Mutt.class, Pug.class, EgyptianMau.class, @@ -20,7 +19,8 @@ public class LiteralPetCreator extends PetCreator { // Types for random creation: private static final List> TYPES = - ALL_TYPES.subList(ALL_TYPES.indexOf(Mutt.class), + ALL_TYPES.subList( + ALL_TYPES.indexOf(Mutt.class), ALL_TYPES.size()); @Override public List> types() { @@ -28,12 +28,15 @@ public List> types() { } public static void main(String[] args) { System.out.println(TYPES); + List pets = new PetCreator().list(7); + System.out.println(pets); } } /* Output: -[class typeinfo.pets.Mutt, class typeinfo.pets.Pug, -class typeinfo.pets.EgyptianMau, class -typeinfo.pets.Manx, class typeinfo.pets.Cymric, class -typeinfo.pets.Rat, class typeinfo.pets.Mouse, class -typeinfo.pets.Hamster] +[class reflection.pets.Mutt, class reflection.pets.Pug, +class reflection.pets.EgyptianMau, class +reflection.pets.Manx, class reflection.pets.Cymric, class +reflection.pets.Rat, class reflection.pets.Mouse, class +reflection.pets.Hamster] +[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug] */ diff --git a/typeinfo/pets/Pug.java b/reflection/pets/Pug.java similarity index 70% rename from typeinfo/pets/Pug.java rename to reflection/pets/Pug.java index 9be1d2e9a..1a150b865 100644 --- a/typeinfo/pets/Pug.java +++ b/reflection/pets/Pug.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Pug.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Pug.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Pug extends Dog { public Pug(String name) { super(name); } diff --git a/typeinfo/pets/Rat.java b/reflection/pets/Rat.java similarity index 70% rename from typeinfo/pets/Rat.java rename to reflection/pets/Rat.java index 099127e01..cd006426d 100644 --- a/typeinfo/pets/Rat.java +++ b/reflection/pets/Rat.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Rat.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Rat.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Rat extends Rodent { public Rat(String name) { super(name); } diff --git a/typeinfo/pets/Rodent.java b/reflection/pets/Rodent.java similarity index 70% rename from typeinfo/pets/Rodent.java rename to reflection/pets/Rodent.java index 32483bc00..3c9063ba3 100644 --- a/typeinfo/pets/Rodent.java +++ b/reflection/pets/Rodent.java @@ -1,8 +1,8 @@ -// typeinfo/pets/Rodent.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/pets/Rodent.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package typeinfo.pets; +package reflection.pets; public class Rodent extends Pet { public Rodent(String name) { super(name); } diff --git a/reflection/toys/GenericToyTest.java b/reflection/toys/GenericToyTest.java new file mode 100644 index 000000000..3332bcd64 --- /dev/null +++ b/reflection/toys/GenericToyTest.java @@ -0,0 +1,22 @@ +// reflection/toys/GenericToyTest.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Testing class Class +// {java reflection.toys.GenericToyTest} +package reflection.toys; + +public class GenericToyTest { + public static void + main(String[] args) throws Exception { + Class ftc = FancyToy.class; + // Produces exact type: + FancyToy fancyToy = + ftc.getConstructor().newInstance(); + Class up = ftc.getSuperclass(); + // This won't compile: + // Class up2 = ftc.getSuperclass(); + // Only produces Object: + Object obj = up.getConstructor().newInstance(); + } +} diff --git a/typeinfo/toys/ToyTest.java b/reflection/toys/ToyTest.java similarity index 54% rename from typeinfo/toys/ToyTest.java rename to reflection/toys/ToyTest.java index b1ff8ba90..e81e64b7e 100644 --- a/typeinfo/toys/ToyTest.java +++ b/reflection/toys/ToyTest.java @@ -1,25 +1,26 @@ -// typeinfo/toys/ToyTest.java -// (c)2017 MindView LLC: see Copyright.txt +// reflection/toys/ToyTest.java +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Testing class Class -// {java typeinfo.toys.ToyTest} -package typeinfo.toys; +// {java reflection.toys.ToyTest} +package reflection.toys; +import java.lang.reflect.InvocationTargetException; interface HasBatteries {} interface Waterproof {} interface Shoots {} class Toy { - // Comment out the following no-arg + // Comment out the following zero-argument // constructor to see NoSuchMethodError - Toy() {} - Toy(int i) {} + public Toy() {} + public Toy(int i) {} } class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots { - FancyToy() { super(1); } + public FancyToy() { super(1); } } public class ToyTest { @@ -31,10 +32,11 @@ static void printInfo(Class cc) { System.out.println( "Canonical name : " + cc.getCanonicalName()); } + @SuppressWarnings("deprecation") public static void main(String[] args) { Class c = null; try { - c = Class.forName("typeinfo.toys.FancyToy"); + c = Class.forName("reflection.toys.FancyToy"); } catch(ClassNotFoundException e) { System.out.println("Can't find FancyToy"); System.exit(1); @@ -45,35 +47,32 @@ public static void main(String[] args) { Class up = c.getSuperclass(); Object obj = null; try { - // Requires no-arg constructor: + // Requires public zero-argument constructor: obj = up.newInstance(); - } catch(InstantiationException e) { - System.out.println("Cannot instantiate"); - System.exit(1); - } catch(IllegalAccessException e) { - System.out.println("Cannot access"); - System.exit(1); + } catch(Exception e) { + throw new + RuntimeException("Cannot instantiate"); } printInfo(obj.getClass()); } } /* Output: -Class name: typeinfo.toys.FancyToy is interface? +Class name: reflection.toys.FancyToy is interface? [false] Simple name: FancyToy -Canonical name : typeinfo.toys.FancyToy -Class name: typeinfo.toys.HasBatteries is interface? +Canonical name : reflection.toys.FancyToy +Class name: reflection.toys.HasBatteries is interface? [true] Simple name: HasBatteries -Canonical name : typeinfo.toys.HasBatteries -Class name: typeinfo.toys.Waterproof is interface? +Canonical name : reflection.toys.HasBatteries +Class name: reflection.toys.Waterproof is interface? [true] Simple name: Waterproof -Canonical name : typeinfo.toys.Waterproof -Class name: typeinfo.toys.Shoots is interface? [true] +Canonical name : reflection.toys.Waterproof +Class name: reflection.toys.Shoots is interface? [true] Simple name: Shoots -Canonical name : typeinfo.toys.Shoots -Class name: typeinfo.toys.Toy is interface? [false] +Canonical name : reflection.toys.Shoots +Class name: reflection.toys.Toy is interface? [false] Simple name: Toy -Canonical name : typeinfo.toys.Toy +Canonical name : reflection.toys.Toy */ diff --git a/reuse/Bath.java b/reuse/Bath.java index 31a70e8b9..f31a1490d 100644 --- a/reuse/Bath.java +++ b/reuse/Bath.java @@ -1,5 +1,5 @@ // reuse/Bath.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Constructor initialization with composition @@ -10,8 +10,7 @@ class Soap { System.out.println("Soap()"); s = "Constructed"; } - @Override - public String toString() { return s; } + @Override public String toString() { return s; } } public class Bath { @@ -19,19 +18,18 @@ public class Bath { s1 = "Happy", s2 = "Happy", s3, s4; - private Soap castille; + private Soap castile; private int i; private float toy; public Bath() { System.out.println("Inside Bath()"); s3 = "Joy"; toy = 3.14f; - castille = new Soap(); + castile = new Soap(); } // Instance initialization: { i = 47; } - @Override - public String toString() { + @Override public String toString() { if(s4 == null) // Delayed initialization: s4 = "Joy"; return @@ -41,7 +39,7 @@ public String toString() { "s4 = " + s4 + "\n" + "i = " + i + "\n" + "toy = " + toy + "\n" + - "castille = " + castille; + "castile = " + castile; } public static void main(String[] args) { Bath b = new Bath(); @@ -57,5 +55,5 @@ Inside Bath() s4 = Joy i = 47 toy = 3.14 -castille = Constructed +castile = Constructed */ diff --git a/reuse/Beetle.java b/reuse/Beetle.java index c73419540..089f85e07 100644 --- a/reuse/Beetle.java +++ b/reuse/Beetle.java @@ -1,5 +1,5 @@ // reuse/Beetle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The full process of initialization diff --git a/reuse/BlankFinal.java b/reuse/BlankFinal.java index 9a45fe6b3..fd96fe9b8 100644 --- a/reuse/BlankFinal.java +++ b/reuse/BlankFinal.java @@ -1,5 +1,5 @@ // reuse/BlankFinal.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // "Blank" final fields diff --git a/reuse/CADSystem.java b/reuse/CADSystem.java index 530e0de1d..c2af7deac 100644 --- a/reuse/CADSystem.java +++ b/reuse/CADSystem.java @@ -1,5 +1,5 @@ // reuse/CADSystem.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Ensuring proper cleanup @@ -20,8 +20,7 @@ class Circle extends Shape { super(i); System.out.println("Drawing Circle"); } - @Override - void dispose() { + @Override void dispose() { System.out.println("Erasing Circle"); super.dispose(); } @@ -32,8 +31,7 @@ class Triangle extends Shape { super(i); System.out.println("Drawing Triangle"); } - @Override - void dispose() { + @Override void dispose() { System.out.println("Erasing Triangle"); super.dispose(); } @@ -48,8 +46,7 @@ class Line extends Shape { System.out.println( "Drawing Line: " + start + ", " + end); } - @Override - void dispose() { + @Override void dispose() { System.out.println( "Erasing Line: " + start + ", " + end); super.dispose(); @@ -68,8 +65,7 @@ public CADSystem(int i) { t = new Triangle(1); System.out.println("Combined constructor"); } - @Override - public void dispose() { + @Override public void dispose() { System.out.println("CADSystem.dispose()"); // The order of cleanup is the reverse // of the order of initialization: diff --git a/reuse/Car.java b/reuse/Car.java index 4e3fe86cc..46021e7ad 100644 --- a/reuse/Car.java +++ b/reuse/Car.java @@ -1,5 +1,5 @@ // reuse/Car.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Composition with public objects diff --git a/reuse/Cartoon.java b/reuse/Cartoon.java index 51d6f4a5d..4b2634570 100644 --- a/reuse/Cartoon.java +++ b/reuse/Cartoon.java @@ -1,5 +1,5 @@ // reuse/Cartoon.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Constructor calls during inheritance diff --git a/reuse/Chess.java b/reuse/Chess.java index 55a1cc9c9..2bd41b001 100644 --- a/reuse/Chess.java +++ b/reuse/Chess.java @@ -1,5 +1,5 @@ // reuse/Chess.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Inheritance, constructors and arguments diff --git a/reuse/DerivedSpaceShip.java b/reuse/DerivedSpaceShip.java index 737e23e16..5df55f543 100644 --- a/reuse/DerivedSpaceShip.java +++ b/reuse/DerivedSpaceShip.java @@ -1,5 +1,5 @@ // reuse/DerivedSpaceShip.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. @@ -9,8 +9,9 @@ public DerivedSpaceShip(String name) { this.name = name; } - @Override - public String toString() { return name; } + @Override public String toString() { + return name; + } public static void main(String[] args) { DerivedSpaceShip protector = new DerivedSpaceShip("NSEA Protector"); diff --git a/reuse/Detergent.java b/reuse/Detergent.java index 6f1c08520..2f25309d1 100644 --- a/reuse/Detergent.java +++ b/reuse/Detergent.java @@ -1,5 +1,5 @@ // reuse/Detergent.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Inheritance syntax & properties @@ -10,8 +10,7 @@ class Cleanser { public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } - @Override - public String toString() { return s; } + @Override public String toString() { return s; } public static void main(String[] args) { Cleanser x = new Cleanser(); x.dilute(); x.apply(); x.scrub(); @@ -21,8 +20,7 @@ public static void main(String[] args) { public class Detergent extends Cleanser { // Change a method: - @Override - public void scrub() { + @Override public void scrub() { append(" Detergent.scrub()"); super.scrub(); // Call base-class version } diff --git a/reuse/FinalArguments.java b/reuse/FinalArguments.java index 9942a2104..2c8e649d7 100644 --- a/reuse/FinalArguments.java +++ b/reuse/FinalArguments.java @@ -1,5 +1,5 @@ // reuse/FinalArguments.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using "final" with method arguments diff --git a/reuse/FinalData.java b/reuse/FinalData.java index b233c408b..97539e636 100644 --- a/reuse/FinalData.java +++ b/reuse/FinalData.java @@ -1,5 +1,5 @@ // reuse/FinalData.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The effect of final on fields @@ -27,8 +27,7 @@ public class FinalData { private static final Value VAL_3 = new Value(33); // Arrays: private final int[] a = { 1, 2, 3, 4, 5, 6 }; - @Override - public String toString() { + @Override public String toString() { return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5; } diff --git a/reuse/FinalOverridingIllusion.java b/reuse/FinalOverridingIllusion.java index 1b475194a..a74df7bef 100644 --- a/reuse/FinalOverridingIllusion.java +++ b/reuse/FinalOverridingIllusion.java @@ -1,5 +1,5 @@ // reuse/FinalOverridingIllusion.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // It only looks like you can override diff --git a/reuse/Hide.java b/reuse/Hide.java index 882da64d9..e4122091b 100644 --- a/reuse/Hide.java +++ b/reuse/Hide.java @@ -1,5 +1,5 @@ // reuse/Hide.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Overloading a base-class method name in a derived diff --git a/reuse/Jurassic.java b/reuse/Jurassic.java index af63bea9a..7d85e4fb7 100644 --- a/reuse/Jurassic.java +++ b/reuse/Jurassic.java @@ -1,5 +1,5 @@ // reuse/Jurassic.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Making an entire class final diff --git a/reuse/Lisa.java b/reuse/Lisa.java index 6d175fe5d..68cccf0a7 100644 --- a/reuse/Lisa.java +++ b/reuse/Lisa.java @@ -1,5 +1,5 @@ // reuse/Lisa.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} diff --git a/reuse/Orc.java b/reuse/Orc.java index 9974c685b..c1f984208 100644 --- a/reuse/Orc.java +++ b/reuse/Orc.java @@ -1,5 +1,5 @@ // reuse/Orc.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The protected keyword @@ -8,8 +8,7 @@ class Villain { private String name; protected void set(String nm) { name = nm; } Villain(String name) { this.name = name; } - @Override - public String toString() { + @Override public String toString() { return "I'm a Villain and my name is " + name; } } @@ -24,8 +23,7 @@ public void change(String name, int orcNumber) { set(name); // Available because it's protected this.orcNumber = orcNumber; } - @Override - public String toString() { + @Override public String toString() { return "Orc " + orcNumber + ": " + super.toString(); } public static void main(String[] args) { diff --git a/reuse/PlaceSetting.java b/reuse/PlaceSetting.java index 5723a1100..ec2486a80 100644 --- a/reuse/PlaceSetting.java +++ b/reuse/PlaceSetting.java @@ -1,5 +1,5 @@ // reuse/PlaceSetting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Combining composition & inheritance diff --git a/reuse/SpaceShipControls.java b/reuse/SpaceShipControls.java index 2272713d8..fba9aaff5 100644 --- a/reuse/SpaceShipControls.java +++ b/reuse/SpaceShipControls.java @@ -1,5 +1,5 @@ // reuse/SpaceShipControls.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/reuse/SpaceShipDelegation.java b/reuse/SpaceShipDelegation.java index 9046a4a48..aeeca9fc2 100644 --- a/reuse/SpaceShipDelegation.java +++ b/reuse/SpaceShipDelegation.java @@ -1,5 +1,5 @@ // reuse/SpaceShipDelegation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/reuse/SprinklerSystem.java b/reuse/SprinklerSystem.java index 77a175184..6cc174ff7 100644 --- a/reuse/SprinklerSystem.java +++ b/reuse/SprinklerSystem.java @@ -1,5 +1,5 @@ // reuse/SprinklerSystem.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Composition for code reuse @@ -10,8 +10,7 @@ class WaterSource { System.out.println("WaterSource()"); s = "Constructed"; } - @Override - public String toString() { return s; } + @Override public String toString() { return s; } } public class SprinklerSystem { @@ -19,15 +18,14 @@ public class SprinklerSystem { private WaterSource source = new WaterSource(); private int i; private float f; - @Override - public String toString() { + @Override public String toString() { return "valve1 = " + valve1 + " " + "valve2 = " + valve2 + " " + "valve3 = " + valve3 + " " + "valve4 = " + valve4 + "\n" + "i = " + i + " " + "f = " + f + " " + - "source = " + source; // [1] + "source = " + source; // [1] } public static void main(String[] args) { SprinklerSystem sprinklers = new SprinklerSystem(); diff --git a/reuse/Wind.java b/reuse/Wind.java index 46fc3e948..ef1c79d17 100644 --- a/reuse/Wind.java +++ b/reuse/Wind.java @@ -1,5 +1,5 @@ // reuse/Wind.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Inheritance & upcasting diff --git a/serialization/APerson.java b/serialization/APerson.java index fa9f2b951..6eb667ae9 100644 --- a/serialization/APerson.java +++ b/serialization/APerson.java @@ -1,5 +1,5 @@ // serialization/APerson.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Use the XOM library to write and read XML @@ -32,8 +32,7 @@ public APerson(Element person) { last = person .getFirstChildElement("last").getValue(); } - @Override - public String toString() { + @Override public String toString() { return first + " " + last; } // Make it human-readable: diff --git a/serialization/AStoreCADState.java b/serialization/AStoreCADState.java index 46fca27bc..ef496b808 100644 --- a/serialization/AStoreCADState.java +++ b/serialization/AStoreCADState.java @@ -1,5 +1,5 @@ // serialization/AStoreCADState.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Saving the state of a fictitious CAD system @@ -11,85 +11,74 @@ enum Color { RED, BLUE, GREEN } abstract class Shape implements Serializable { private int xPos, yPos, dimension; - private static Random rand = new Random(47); - private static int counter = 0; - public abstract void setColor(Color newColor); - public abstract Color getColor(); Shape(int xVal, int yVal, int dim) { xPos = xVal; yPos = yVal; dimension = dim; } - public String toString() { - return getClass() + "color[" + getColor() + - "] xPos[" + xPos + "] yPos[" + yPos + - "] dim[" + dimension + "]\n"; + public abstract void setColor(Color newColor); + public abstract Color getColor(); + @Override public String toString() { + return "\n" + getClass() + " " + getColor() + + " xPos[" + xPos + "] yPos[" + yPos + + "] dim[" + dimension + "]"; } + private static Random rand = new Random(47); + private static int counter = 0; public static Shape randomFactory() { int xVal = rand.nextInt(100); int yVal = rand.nextInt(100); int dim = rand.nextInt(100); - switch(counter++ % 3) { + switch(counter++ % 2) { default: case 0: return new Circle(xVal, yVal, dim); - case 1: return new Square(xVal, yVal, dim); - case 2: return new Line(xVal, yVal, dim); + case 1: return new Line(xVal, yVal, dim); } } } class Circle extends Shape { - private static Color color = Color.RED; Circle(int xVal, int yVal, int dim) { super(xVal, yVal, dim); } - public void setColor(Color newColor) { + private static Color color = Color.RED; + @Override public void setColor(Color newColor) { color = newColor; } - public Color getColor() { return color; } + @Override public Color getColor() { return color; } } -class Square extends Shape { - private static Color color = Color.RED; - Square(int xVal, int yVal, int dim) { +class Line extends Shape { + Line(int xVal, int yVal, int dim) { super(xVal, yVal, dim); } - public void setColor(Color newColor) { + private static Color color = Color.RED; + @Override public void setColor(Color newColor) { color = newColor; } - public Color getColor() { return color; } -} - -class Line extends Shape { - private static Color color = Color.RED; + @Override public Color getColor() { return color; } public static void serializeStaticState(ObjectOutputStream os) - throws IOException { os.writeObject(color); } + throws IOException { + os.writeObject(color); + } public static void deserializeStaticState(ObjectInputStream os) throws IOException, ClassNotFoundException { color = (Color)os.readObject(); } - Line(int xVal, int yVal, int dim) { - super(xVal, yVal, dim); - } - public void setColor(Color newColor) { - color = newColor; - } - public Color getColor() { return color; } } public class AStoreCADState { public static void main(String[] args) { List> shapeTypes = - Arrays.asList( - Circle.class, Square.class, Line.class); - List shapes = IntStream.range(0, 10) + Arrays.asList(Circle.class, Line.class); + List shapes = IntStream.range(0, 5) .mapToObj(i -> Shape.randomFactory()) .collect(Collectors.toList()); // Set all the static colors to GREEN: shapes.forEach(s -> s.setColor(Color.GREEN)); - // Save the state vector: + // Serialize everything to CADState.dat: try( ObjectOutputStream out = new ObjectOutputStream( @@ -106,15 +95,10 @@ public static void main(String[] args) { } } /* Output: -[class Circlecolor[GREEN] xPos[58] yPos[55] dim[93] -, class Squarecolor[GREEN] xPos[61] yPos[61] dim[29] -, class Linecolor[GREEN] xPos[68] yPos[0] dim[22] -, class Circlecolor[GREEN] xPos[7] yPos[88] dim[28] -, class Squarecolor[GREEN] xPos[51] yPos[89] dim[9] -, class Linecolor[GREEN] xPos[78] yPos[98] dim[61] -, class Circlecolor[GREEN] xPos[20] yPos[58] dim[16] -, class Squarecolor[GREEN] xPos[40] yPos[11] dim[22] -, class Linecolor[GREEN] xPos[4] yPos[83] dim[6] -, class Circlecolor[GREEN] xPos[75] yPos[10] dim[42] -] +[ +class Circle GREEN xPos[58] yPos[55] dim[93], +class Line GREEN xPos[61] yPos[61] dim[29], +class Circle GREEN xPos[68] yPos[0] dim[22], +class Line GREEN xPos[7] yPos[88] dim[28], +class Circle GREEN xPos[51] yPos[89] dim[9]] */ diff --git a/serialization/Alien.java b/serialization/Alien.java index b7db23f2e..b0ba09a4e 100644 --- a/serialization/Alien.java +++ b/serialization/Alien.java @@ -1,5 +1,5 @@ // serialization/Alien.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A serializable class diff --git a/serialization/Blip3.java b/serialization/Blip3.java index 4c141def2..0e6907375 100644 --- a/serialization/Blip3.java +++ b/serialization/Blip3.java @@ -1,5 +1,5 @@ // serialization/Blip3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Reconstructing an externalizable object @@ -16,20 +16,17 @@ public Blip3(String x, int a) { System.out.println("Blip3(String x, int a)"); s = x; i = a; - // s & i initialized only in non-no-arg constructor. + // s & i initialized only in non-zero-argument constructor. } - @Override - public String toString() { return s + i; } - @Override - public void writeExternal(ObjectOutput out) + @Override public String toString() { return s + i; } + @Override public void writeExternal(ObjectOutput out) throws IOException { System.out.println("Blip3.writeExternal"); // You must do this: out.writeObject(s); out.writeInt(i); } - @Override - public void readExternal(ObjectInput in) + @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { System.out.println("Blip3.readExternal"); // You must do this: diff --git a/serialization/Blips.java b/serialization/Blips.java index 4a98f1237..0ae46686f 100644 --- a/serialization/Blips.java +++ b/serialization/Blips.java @@ -1,5 +1,5 @@ // serialization/Blips.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple use of Externalizable & a pitfall diff --git a/serialization/FreezeAlien.java b/serialization/FreezeAlien.java index ec046d8b8..3ff390b88 100644 --- a/serialization/FreezeAlien.java +++ b/serialization/FreezeAlien.java @@ -1,5 +1,5 @@ // serialization/FreezeAlien.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Create a serialized output file diff --git a/serialization/Logon.java b/serialization/Logon.java index 7d27e4d15..c8f6d9c58 100644 --- a/serialization/Logon.java +++ b/serialization/Logon.java @@ -1,5 +1,5 @@ // serialization/Logon.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates the "transient" keyword @@ -16,8 +16,7 @@ public Logon(String name, String pwd) { username = name; password = pwd; } - @Override - public String toString() { + @Override public String toString() { return "logon info: \n username: " + username + "\n date: " + date + "\n password: " + password; @@ -52,11 +51,11 @@ public static void main(String[] args) { /* Output: logon a = logon info: username: Hulk - date: Tue May 09 06:07:47 MDT 2017 + date: Sun Jan 24 08:49:30 MST 2021 password: myLittlePony -Recovering object at Tue May 09 06:07:49 MDT 2017 +Recovering object at Sun Jan 24 08:49:31 MST 2021 logon a = logon info: username: Hulk - date: Tue May 09 06:07:47 MDT 2017 + date: Sun Jan 24 08:49:30 MST 2021 password: null */ diff --git a/serialization/MyWorld.java b/serialization/MyWorld.java index 5cdf5778d..f642530fa 100644 --- a/serialization/MyWorld.java +++ b/serialization/MyWorld.java @@ -1,5 +1,5 @@ // serialization/MyWorld.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; @@ -14,8 +14,7 @@ class Animal implements Serializable { name = nm; preferredHouse = h; } - @Override - public String toString() { + @Override public String toString() { return name + "[" + super.toString() + "], " + preferredHouse + "\n"; } @@ -77,24 +76,20 @@ public static void main(String[] args) { } } /* Output: -animals: [Bosco the dog[Animal@15db9742], -House@6d06d69c -, Ralph the hamster[Animal@7852e922], House@6d06d69c -, Molly the cat[Animal@4e25154f], House@6d06d69c +animals: [Bosco the dog[Animal@19e0bfd], House@139a55 +, Ralph the hamster[Animal@1db9742], House@139a55 +, Molly the cat[Animal@106d69c], House@139a55 ] -animals1: [Bosco the dog[Animal@7ba4f24f], -House@3b9a45b3 -, Ralph the hamster[Animal@7699a589], House@3b9a45b3 -, Molly the cat[Animal@58372a00], House@3b9a45b3 +animals1: [Bosco the dog[Animal@1ee12a7], House@10bedb4 +, Ralph the hamster[Animal@103dbd3], House@10bedb4 +, Molly the cat[Animal@167cf4d], House@10bedb4 ] -animals2: [Bosco the dog[Animal@7ba4f24f], -House@3b9a45b3 -, Ralph the hamster[Animal@7699a589], House@3b9a45b3 -, Molly the cat[Animal@58372a00], House@3b9a45b3 +animals2: [Bosco the dog[Animal@1ee12a7], House@10bedb4 +, Ralph the hamster[Animal@103dbd3], House@10bedb4 +, Molly the cat[Animal@167cf4d], House@10bedb4 ] -animals3: [Bosco the dog[Animal@4dd8dc3], -House@6d03e736 -, Ralph the hamster[Animal@568db2f2], House@6d03e736 -, Molly the cat[Animal@378bf509], House@6d03e736 +animals3: [Bosco the dog[Animal@a987ac], House@a3a380 +, Ralph the hamster[Animal@1453f44], House@a3a380 +, Molly the cat[Animal@ad8086], House@a3a380 ] */ diff --git a/serialization/People.java b/serialization/People.java index 6205bfabd..b30456669 100644 --- a/serialization/People.java +++ b/serialization/People.java @@ -1,5 +1,5 @@ // serialization/People.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // nu.xom.Node comes from http://www.xom.nu diff --git a/serialization/RecoverCADState.java b/serialization/RecoverCADState.java index 6f3b50670..3c4bec35d 100644 --- a/serialization/RecoverCADState.java +++ b/serialization/RecoverCADState.java @@ -1,5 +1,5 @@ // serialization/RecoverCADState.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Restoring the state of the fictitious CAD system @@ -19,8 +19,7 @@ public static void main(String[] args) { List> shapeTypes = (List>)in.readObject(); Line.deserializeStaticState(in); - List shapes = - (List)in.readObject(); + List shapes = (List)in.readObject(); System.out.println(shapes); } catch(IOException | ClassNotFoundException e) { throw new RuntimeException(e); @@ -28,15 +27,10 @@ public static void main(String[] args) { } } /* Output: -[class Circlecolor[RED] xPos[58] yPos[55] dim[93] -, class Squarecolor[RED] xPos[61] yPos[61] dim[29] -, class Linecolor[GREEN] xPos[68] yPos[0] dim[22] -, class Circlecolor[RED] xPos[7] yPos[88] dim[28] -, class Squarecolor[RED] xPos[51] yPos[89] dim[9] -, class Linecolor[GREEN] xPos[78] yPos[98] dim[61] -, class Circlecolor[RED] xPos[20] yPos[58] dim[16] -, class Squarecolor[RED] xPos[40] yPos[11] dim[22] -, class Linecolor[GREEN] xPos[4] yPos[83] dim[6] -, class Circlecolor[RED] xPos[75] yPos[10] dim[42] -] +[ +class Circle RED xPos[58] yPos[55] dim[93], +class Line GREEN xPos[61] yPos[61] dim[29], +class Circle RED xPos[68] yPos[0] dim[22], +class Line GREEN xPos[7] yPos[88] dim[28], +class Circle RED xPos[51] yPos[89] dim[9]] */ diff --git a/serialization/SerialCtl.java b/serialization/SerialCtl.java index 56add3431..dd1d41a1f 100644 --- a/serialization/SerialCtl.java +++ b/serialization/SerialCtl.java @@ -1,5 +1,5 @@ // serialization/SerialCtl.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Controlling serialization by adding your own @@ -13,8 +13,9 @@ public SerialCtl(String aa, String bb) { a = "Not Transient: " + aa; b = "Transient: " + bb; } - @Override - public String toString() { return a + "\n" + b; } + @Override public String toString() { + return a + "\n" + b; + } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); diff --git a/serialization/Worm.java b/serialization/Worm.java index 261988863..7959be098 100644 --- a/serialization/Worm.java +++ b/serialization/Worm.java @@ -1,5 +1,5 @@ // serialization/Worm.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates object serialization @@ -9,8 +9,7 @@ class Data implements Serializable { private int n; Data(int n) { this.n = n; } - @Override - public String toString() { + @Override public String toString() { return Integer.toString(n); } } @@ -32,10 +31,9 @@ public Worm(int i, char x) { next = new Worm(i, (char)(x + 1)); } public Worm() { - System.out.println("No-arg constructor"); + System.out.println("Zero-argument constructor"); } - @Override - public String toString() { + @Override public String toString() { StringBuilder result = new StringBuilder(":"); result.append(c); result.append("("); diff --git a/serialization/xfiles/ThawAlien.java b/serialization/xfiles/ThawAlien.java index d60d6f375..850abd40d 100644 --- a/serialization/xfiles/ThawAlien.java +++ b/serialization/xfiles/ThawAlien.java @@ -1,5 +1,5 @@ // serialization/xfiles/ThawAlien.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Recover a serialized file diff --git a/settings.gradle b/settings.gradle index 376ca1053..9ab61dfbe 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,8 +1,6 @@ def isSubproject = { File file -> file.isDirectory() && - !file.name.contains('.git') && - !file.name.contains('.gradle') && - !file.name.contains('.idea') && + !file.name.startsWith('.') && !file.name.contains('build') && !file.name.contains('gradle') && !file.name.contains('test') diff --git a/standardio/ChangeSystemOut.java b/standardio/ChangeSystemOut.java index def290419..e0a06bb7a 100644 --- a/standardio/ChangeSystemOut.java +++ b/standardio/ChangeSystemOut.java @@ -1,5 +1,5 @@ // standardio/ChangeSystemOut.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Turn System.out into a PrintWriter diff --git a/standardio/Echo.java b/standardio/Echo.java index 3a222c93c..1119d6ce6 100644 --- a/standardio/Echo.java +++ b/standardio/Echo.java @@ -1,5 +1,5 @@ // standardio/Echo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // How to read from standard input diff --git a/standardio/OSExecuteDemo.java b/standardio/OSExecuteDemo.java index 57ec2468a..608efe81b 100644 --- a/standardio/OSExecuteDemo.java +++ b/standardio/OSExecuteDemo.java @@ -1,9 +1,10 @@ // standardio/OSExecuteDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates standard I/O redirection -// {javap -cp build/classes/main OSExecuteDemo} +// javap -cp build/classes/java/main OSExecuteDemo +// {ExcludeFromGradle} import onjava.*; public class OSExecuteDemo {} diff --git a/standardio/Redirecting.java b/standardio/Redirecting.java index 72abc4ae2..c89ef6303 100644 --- a/standardio/Redirecting.java +++ b/standardio/Redirecting.java @@ -1,5 +1,5 @@ // standardio/Redirecting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates standard I/O redirection diff --git a/staticchecking/DogsAndRobots.cpp b/staticchecking/DogsAndRobots.cpp index b4f2a1f12..e7c1cbbc7 100644 --- a/staticchecking/DogsAndRobots.cpp +++ b/staticchecking/DogsAndRobots.cpp @@ -1,5 +1,5 @@ // staticchecking/DogsAndRobots.cpp -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. #include diff --git a/staticchecking/DogsAndRobots.py b/staticchecking/DogsAndRobots.py index 6327222cb..df423de0b 100644 --- a/staticchecking/DogsAndRobots.py +++ b/staticchecking/DogsAndRobots.py @@ -1,5 +1,5 @@ # staticchecking/DogsAndRobots.py -# (c)2017 MindView LLC: see Copyright.txt +# (c)2021 MindView LLC: see Copyright.txt # We make no guarantees that this code is fit for any purpose. # Visit http://OnJava8.com for more book information. diff --git a/staticchecking/NoBasePetSpeak.py b/staticchecking/NoBasePetSpeak.py index e148614d6..13590f221 100644 --- a/staticchecking/NoBasePetSpeak.py +++ b/staticchecking/NoBasePetSpeak.py @@ -1,8 +1,8 @@ # staticchecking/NoBasePetSpeak.py -# (c)2017 MindView LLC: see Copyright.txt +# (c)2021 MindView LLC: see Copyright.txt # We make no guarantees that this code is fit for any purpose. # Visit http://OnJava8.com for more book information. -# Speaking pets without base classes +#- Speaking pets without base classes class Cat: def speak(self): diff --git a/staticchecking/PetSpeak.py b/staticchecking/PetSpeak.py index 57a05bd6b..8699a6c83 100644 --- a/staticchecking/PetSpeak.py +++ b/staticchecking/PetSpeak.py @@ -1,8 +1,8 @@ # staticchecking/PetSpeak.py -# (c)2017 MindView LLC: see Copyright.txt +# (c)2021 MindView LLC: see Copyright.txt # We make no guarantees that this code is fit for any purpose. # Visit http://OnJava8.com for more book information. -# Speaking pets in Python +#- Speaking pets in Python class Pet: def speak(self): pass diff --git a/staticchecking/dogsandrobots.go b/staticchecking/dogsandrobots.go index a352865e4..6f353bd83 100644 --- a/staticchecking/dogsandrobots.go +++ b/staticchecking/dogsandrobots.go @@ -1,5 +1,5 @@ // staticchecking/dogsandrobots.go -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package main diff --git a/staticchecking/dr/DogsAndRobots.java b/staticchecking/dr/DogsAndRobots.java index c5afa6f98..3297a663a 100644 --- a/staticchecking/dr/DogsAndRobots.java +++ b/staticchecking/dr/DogsAndRobots.java @@ -1,5 +1,5 @@ // staticchecking/dr/DogsAndRobots.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java staticchecking.dr.DogsAndRobots} @@ -8,14 +8,14 @@ interface Speaks { void talk(); } class Dog implements Speaks { - public void talk() { + @Override public void talk() { System.out.println("Woof!"); } public void reproduce() { } } class Robot implements Speaks { - public void talk() { + @Override public void talk() { System.out.println("Click!"); } public void oilChange() { } diff --git a/staticchecking/drc/DogAndRobotCollections.java b/staticchecking/drc/DogAndRobotCollections.java index bf48ee023..fdcbed71e 100644 --- a/staticchecking/drc/DogAndRobotCollections.java +++ b/staticchecking/drc/DogAndRobotCollections.java @@ -1,5 +1,5 @@ // staticchecking/drc/DogAndRobotCollections.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java staticchecking.drc.DogAndRobotCollections} diff --git a/staticchecking/latent/Latent.java b/staticchecking/latent/Latent.java index f8766f41b..04a374fb2 100644 --- a/staticchecking/latent/Latent.java +++ b/staticchecking/latent/Latent.java @@ -1,5 +1,5 @@ // staticchecking/latent/Latent.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java staticchecking.latent.Latent} @@ -22,6 +22,7 @@ public void oilChange() {} class Mime { public void walkAgainstTheWind() {} + @Override public String toString() { return "Mime"; } } diff --git a/staticchecking/petspeak.go b/staticchecking/petspeak.go index 308e0c1f9..497178a4a 100644 --- a/staticchecking/petspeak.go +++ b/staticchecking/petspeak.go @@ -1,5 +1,5 @@ // staticchecking/petspeak.go -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package main diff --git a/staticchecking/petspeak/PetSpeak.java b/staticchecking/petspeak/PetSpeak.java index 6b1014976..86a3db3d7 100644 --- a/staticchecking/petspeak/PetSpeak.java +++ b/staticchecking/petspeak/PetSpeak.java @@ -1,5 +1,5 @@ // staticchecking/petspeak/PetSpeak.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Speaking pets in Java @@ -11,13 +11,13 @@ interface Pet { } class Cat implements Pet { - public void speak() { + @Override public void speak() { System.out.println("meow!"); } } class Dog implements Pet { - public void speak() { + @Override public void speak() { System.out.println("woof!"); } } diff --git a/streams/ArrayStreams.java b/streams/ArrayStreams.java index 8bcdbb8af..74c164606 100644 --- a/streams/ArrayStreams.java +++ b/streams/ArrayStreams.java @@ -1,5 +1,5 @@ // streams/ArrayStreams.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Bubble.java b/streams/Bubble.java index c07afa588..86c99297d 100644 --- a/streams/Bubble.java +++ b/streams/Bubble.java @@ -1,5 +1,5 @@ // streams/Bubble.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.function.*; @@ -7,8 +7,7 @@ public class Bubble { public final int i; public Bubble(int n) { i = n; } - @Override - public String toString() { + @Override public String toString() { return "Bubble(" + i + ")"; } private static int count = 0; diff --git a/streams/Bubbles.java b/streams/Bubbles.java index 66177f024..21efc8a44 100644 --- a/streams/Bubbles.java +++ b/streams/Bubbles.java @@ -1,5 +1,5 @@ // streams/Bubbles.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/CollectionToStream.java b/streams/CollectionToStream.java index 12efabe39..7b7c69cea 100644 --- a/streams/CollectionToStream.java +++ b/streams/CollectionToStream.java @@ -1,5 +1,5 @@ // streams/CollectionToStream.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/CreatingOptionals.java b/streams/CreatingOptionals.java index fd3f64548..4f30cf52c 100644 --- a/streams/CreatingOptionals.java +++ b/streams/CreatingOptionals.java @@ -1,5 +1,5 @@ // streams/CreatingOptionals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Duplicator.java b/streams/Duplicator.java index 78a83e2a7..9e9f87eec 100644 --- a/streams/Duplicator.java +++ b/streams/Duplicator.java @@ -1,5 +1,5 @@ // streams/Duplicator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/Fibonacci.java b/streams/Fibonacci.java index 3c76ca68d..0fb47d3f3 100644 --- a/streams/Fibonacci.java +++ b/streams/Fibonacci.java @@ -1,5 +1,5 @@ // streams/Fibonacci.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/FileToWords.java b/streams/FileToWords.java index 3fc61ca5f..1e90d7a4b 100644 --- a/streams/FileToWords.java +++ b/streams/FileToWords.java @@ -1,5 +1,5 @@ // streams/FileToWords.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.nio.file.*; diff --git a/streams/FileToWordsBuilder.java b/streams/FileToWordsBuilder.java index d51c86630..5e830b8bb 100644 --- a/streams/FileToWordsBuilder.java +++ b/streams/FileToWordsBuilder.java @@ -1,5 +1,5 @@ // streams/FileToWordsBuilder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/streams/FileToWordsRegexp.java b/streams/FileToWordsRegexp.java index 3132cd671..f01c853aa 100644 --- a/streams/FileToWordsRegexp.java +++ b/streams/FileToWordsRegexp.java @@ -1,5 +1,5 @@ // streams/FileToWordsRegexp.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/streams/FileToWordsTest.java b/streams/FileToWordsTest.java index b94c39fd4..7c95bebd5 100644 --- a/streams/FileToWordsTest.java +++ b/streams/FileToWordsTest.java @@ -1,5 +1,5 @@ // streams/FileToWordsTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/FlatMap.java b/streams/FlatMap.java index 50ed7ed9a..8e5fe8d69 100644 --- a/streams/FlatMap.java +++ b/streams/FlatMap.java @@ -1,5 +1,5 @@ // streams/FlatMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/ForEach.java b/streams/ForEach.java index 37b537182..a8ed8edea 100644 --- a/streams/ForEach.java +++ b/streams/ForEach.java @@ -1,5 +1,5 @@ // streams/ForEach.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -23,6 +23,6 @@ public static void main(String[] args) { } /* Output: 258 555 693 861 961 429 868 200 522 207 288 128 551 589 -551 861 429 589 200 522 555 693 258 128 868 288 961 207 +551 589 861 555 288 128 429 207 693 200 258 522 868 961 258 555 693 861 961 429 868 200 522 207 288 128 551 589 */ diff --git a/streams/FunctionMap.java b/streams/FunctionMap.java index 7176b2e3b..9b2fc4744 100644 --- a/streams/FunctionMap.java +++ b/streams/FunctionMap.java @@ -1,5 +1,5 @@ // streams/FunctionMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/FunctionMap2.java b/streams/FunctionMap2.java index 809cb4702..130cd7292 100644 --- a/streams/FunctionMap2.java +++ b/streams/FunctionMap2.java @@ -1,5 +1,5 @@ // streams/FunctionMap2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Different input and output types @@ -9,8 +9,7 @@ class Numbered { final int n; Numbered(int n) { this.n = n; } - @Override - public String toString() { + @Override public String toString() { return "Numbered(" + n + ")"; } } diff --git a/streams/FunctionMap3.java b/streams/FunctionMap3.java index ebb9e3b0e..6214fa327 100644 --- a/streams/FunctionMap3.java +++ b/streams/FunctionMap3.java @@ -1,5 +1,5 @@ // streams/FunctionMap3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Producing numeric output streams diff --git a/streams/Generator.java b/streams/Generator.java index dc3ac1762..f83741216 100644 --- a/streams/Generator.java +++ b/streams/Generator.java @@ -1,5 +1,5 @@ // streams/Generator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -10,7 +10,7 @@ public class Generator implements Supplier { Random rand = new Random(47); char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); - public String get() { + @Override public String get() { return "" + letters[rand.nextInt(letters.length)]; } public static void main(String[] args) { diff --git a/streams/ImperativeRandoms.java b/streams/ImperativeRandoms.java index 9dad499a4..a11a072e4 100644 --- a/streams/ImperativeRandoms.java +++ b/streams/ImperativeRandoms.java @@ -1,5 +1,5 @@ // streams/ImperativeRandoms.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Informational.java b/streams/Informational.java index 421455120..bc33ca4d3 100644 --- a/streams/Informational.java +++ b/streams/Informational.java @@ -1,5 +1,5 @@ // streams/Informational.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/LastElement.java b/streams/LastElement.java index e5fa30c1e..74a745526 100644 --- a/streams/LastElement.java +++ b/streams/LastElement.java @@ -1,5 +1,5 @@ // streams/LastElement.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Looping.java b/streams/Looping.java index 75a30ef70..bfb49d031 100644 --- a/streams/Looping.java +++ b/streams/Looping.java @@ -1,5 +1,5 @@ // streams/Looping.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import static onjava.Repeat.*; diff --git a/streams/Machine2.java b/streams/Machine2.java deleted file mode 100644 index a72369660..000000000 --- a/streams/Machine2.java +++ /dev/null @@ -1,23 +0,0 @@ -// streams/Machine2.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -import java.util.*; -import onjava.Operations; - -public class Machine2 { - public static void main(String[] args) { - Arrays.stream(new Operations[] { - () -> Operations.show("Bing"), - () -> Operations.show("Crack"), - () -> Operations.show("Twist"), - () -> Operations.show("Pop") - }).forEach(Operations::execute); - } -} -/* Output: -Bing -Crack -Twist -Pop -*/ diff --git a/streams/MapCollector.java b/streams/MapCollector.java index 01f71d0ef..5ab66f715 100644 --- a/streams/MapCollector.java +++ b/streams/MapCollector.java @@ -1,5 +1,5 @@ // streams/MapCollector.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -14,8 +14,7 @@ class Pair { } public Character getC() { return c; } public Integer getI() { return i; } - @Override - public String toString() { + @Override public String toString() { return "Pair(" + c + ", " + i + ")"; } } diff --git a/streams/Matching.java b/streams/Matching.java index b5aff16b8..4aa6280f5 100644 --- a/streams/Matching.java +++ b/streams/Matching.java @@ -1,5 +1,5 @@ // streams/Matching.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates short-circuiting of *Match() operations diff --git a/streams/MetalWork2.java b/streams/MetalWork2.java new file mode 100644 index 000000000..0bf74152f --- /dev/null +++ b/streams/MetalWork2.java @@ -0,0 +1,23 @@ +// streams/MetalWork2.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.*; +import onjava.Operation; + +public class MetalWork2 { + public static void main(String[] args) { + Arrays.stream(new Operation[] { + () -> Operation.show("Heat"), + () -> Operation.show("Hammer"), + () -> Operation.show("Twist"), + () -> Operation.show("Anneal") + }).forEach(Operation::execute); + } +} +/* Output: +Heat +Hammer +Twist +Anneal +*/ diff --git a/streams/NumericStreamInfo.java b/streams/NumericStreamInfo.java index 592263b58..3cc6c88e3 100644 --- a/streams/NumericStreamInfo.java +++ b/streams/NumericStreamInfo.java @@ -1,5 +1,5 @@ // streams/NumericStreamInfo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/OptionalBasics.java b/streams/OptionalBasics.java index 24aa0dcfd..525611d21 100644 --- a/streams/OptionalBasics.java +++ b/streams/OptionalBasics.java @@ -1,5 +1,5 @@ // streams/OptionalBasics.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/OptionalFilter.java b/streams/OptionalFilter.java index a15df5da1..72e2011c0 100644 --- a/streams/OptionalFilter.java +++ b/streams/OptionalFilter.java @@ -1,5 +1,5 @@ // streams/OptionalFilter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/OptionalFlatMap.java b/streams/OptionalFlatMap.java index ce71c3f0b..fe5bcdddf 100644 --- a/streams/OptionalFlatMap.java +++ b/streams/OptionalFlatMap.java @@ -1,5 +1,5 @@ // streams/OptionalFlatMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/OptionalMap.java b/streams/OptionalMap.java index 06d1bf3c8..50a385ed1 100644 --- a/streams/OptionalMap.java +++ b/streams/OptionalMap.java @@ -1,5 +1,5 @@ // streams/OptionalMap.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Optionals.java b/streams/Optionals.java index 19331d06f..c4512b4bf 100644 --- a/streams/Optionals.java +++ b/streams/Optionals.java @@ -1,5 +1,5 @@ // streams/Optionals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/OptionalsFromEmptyStreams.java b/streams/OptionalsFromEmptyStreams.java index 5a8240ac9..be206bf8d 100644 --- a/streams/OptionalsFromEmptyStreams.java +++ b/streams/OptionalsFromEmptyStreams.java @@ -1,5 +1,5 @@ // streams/OptionalsFromEmptyStreams.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Peeking.java b/streams/Peeking.java index d3eea20ff..75dcb3467 100644 --- a/streams/Peeking.java +++ b/streams/Peeking.java @@ -1,5 +1,5 @@ // streams/Peeking.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/streams/Prime.java b/streams/Prime.java index 6c72b5189..34e802294 100644 --- a/streams/Prime.java +++ b/streams/Prime.java @@ -1,5 +1,5 @@ // streams/Prime.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/RandInts.java b/streams/RandInts.java index 12416ecc5..8e6c2bb2d 100644 --- a/streams/RandInts.java +++ b/streams/RandInts.java @@ -1,5 +1,5 @@ // streams/RandInts.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package streams; diff --git a/streams/RandomGenerators.java b/streams/RandomGenerators.java index e9d75fefa..286368f3f 100644 --- a/streams/RandomGenerators.java +++ b/streams/RandomGenerators.java @@ -1,5 +1,5 @@ // streams/RandomGenerators.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -7,10 +7,10 @@ public class RandomGenerators { public static void show(Stream stream) { - stream - .limit(4) - .forEach(System.out::println); - System.out.println("++++++++"); + stream + .limit(4) + .forEach(System.out::println); + System.out.println("++++++++"); } public static void main(String[] args) { Random rand = new Random(47); diff --git a/streams/RandomWords.java b/streams/RandomWords.java index ee3f83633..6f2df4edc 100644 --- a/streams/RandomWords.java +++ b/streams/RandomWords.java @@ -1,5 +1,5 @@ // streams/RandomWords.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -20,11 +20,10 @@ public class RandomWords implements Supplier { words.add(word.toLowerCase()); } } - public String get() { + @Override public String get() { return words.get(rand.nextInt(words.size())); } - @Override - public String toString() { + @Override public String toString() { return words.stream() .collect(Collectors.joining(" ")); } diff --git a/streams/Randoms.java b/streams/Randoms.java index bf91ae8d6..52e05df05 100644 --- a/streams/Randoms.java +++ b/streams/Randoms.java @@ -1,5 +1,5 @@ // streams/Randoms.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Ranges.java b/streams/Ranges.java index e0aec59c4..1a4da9018 100644 --- a/streams/Ranges.java +++ b/streams/Ranges.java @@ -1,5 +1,5 @@ // streams/Ranges.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import static java.util.stream.IntStream.*; diff --git a/streams/Reduce.java b/streams/Reduce.java index 48ba59938..9d513f496 100644 --- a/streams/Reduce.java +++ b/streams/Reduce.java @@ -1,5 +1,5 @@ // streams/Reduce.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -8,8 +8,7 @@ class Frobnitz { int size; Frobnitz(int sz) { size = sz; } - @Override - public String toString() { + @Override public String toString() { return "Frobnitz(" + size + ")"; } // Generator: diff --git a/streams/SelectElement.java b/streams/SelectElement.java index 83a9f5e61..a6b504498 100644 --- a/streams/SelectElement.java +++ b/streams/SelectElement.java @@ -1,5 +1,5 @@ // streams/SelectElement.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/Signal.java b/streams/Signal.java index cde125371..4b14200f4 100644 --- a/streams/Signal.java +++ b/streams/Signal.java @@ -1,5 +1,5 @@ // streams/Signal.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -10,8 +10,7 @@ public class Signal { private final String msg; public Signal(String msg) { this.msg = msg; } public String getMsg() { return msg; } - @Override - public String toString() { + @Override public String toString() { return "Signal(" + msg + ")"; } static Random rand = new Random(47); diff --git a/streams/SortedComparator.java b/streams/SortedComparator.java index f0fad0906..4d60a6486 100644 --- a/streams/SortedComparator.java +++ b/streams/SortedComparator.java @@ -1,5 +1,5 @@ // streams/SortedComparator.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/SpecialCollector.java b/streams/SpecialCollector.java index 9261ba0c5..36068bf7b 100644 --- a/streams/SpecialCollector.java +++ b/streams/SpecialCollector.java @@ -1,5 +1,5 @@ // streams/SpecialCollector.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/StreamOf.java b/streams/StreamOf.java index eb38bd8af..7ae3adefc 100644 --- a/streams/StreamOf.java +++ b/streams/StreamOf.java @@ -1,5 +1,5 @@ // streams/StreamOf.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/StreamOfOptionals.java b/streams/StreamOfOptionals.java index 643145aab..4b0b048b0 100644 --- a/streams/StreamOfOptionals.java +++ b/streams/StreamOfOptionals.java @@ -1,5 +1,5 @@ // streams/StreamOfOptionals.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/streams/StreamOfRandoms.java b/streams/StreamOfRandoms.java index 7f0f353de..07efa25e0 100644 --- a/streams/StreamOfRandoms.java +++ b/streams/StreamOfRandoms.java @@ -1,5 +1,5 @@ // streams/StreamOfRandoms.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; @@ -15,6 +15,5 @@ public static void main(String[] args) { } } /* Output: -58 -1 55 93 -1 61 61 29 -1 68 0 22 7 -1 88 28 51 89 9 --1 +58 -1 55 93 -1 61 61 29 -1 68 0 22 7 -1 88 28 51 89 9 -1 */ diff --git a/streams/StreamOfStreams.java b/streams/StreamOfStreams.java index daa15806e..d282a6724 100644 --- a/streams/StreamOfStreams.java +++ b/streams/StreamOfStreams.java @@ -1,5 +1,5 @@ // streams/StreamOfStreams.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.stream.*; diff --git a/streams/TreeSetOfWords.java b/streams/TreeSetOfWords.java index 43cb63bd9..93405f74e 100644 --- a/streams/TreeSetOfWords.java +++ b/streams/TreeSetOfWords.java @@ -1,5 +1,5 @@ // streams/TreeSetOfWords.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/ArrayListDisplay.java b/strings/ArrayListDisplay.java index cdbab7708..586f013a2 100644 --- a/strings/ArrayListDisplay.java +++ b/strings/ArrayListDisplay.java @@ -1,5 +1,5 @@ // strings/ArrayListDisplay.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/BackSlashes.java b/strings/BackSlashes.java new file mode 100644 index 000000000..6363defcc --- /dev/null +++ b/strings/BackSlashes.java @@ -0,0 +1,26 @@ +// strings/BackSlashes.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class BackSlashes { + public static void main(String[] args) { + String one = "\\"; + String two = "\\\\"; + String three = "\\\\\\"; + System.out.println(one); + System.out.println(two); + System.out.println(three); + System.out.println(one.matches("\\\\")); + System.out.println(two.matches("\\\\\\\\")); + System.out.println(three.matches("\\\\\\\\\\\\")); + } +} +/* Output: +\ +\\ +\\\ +true +true +true +*/ diff --git a/strings/BetterRead.java b/strings/BetterRead.java index a6a5b2c48..02c55c397 100644 --- a/strings/BetterRead.java +++ b/strings/BetterRead.java @@ -1,5 +1,5 @@ // strings/BetterRead.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/Concatenation.java b/strings/Concatenation.java index b6c01386b..33e703a85 100644 --- a/strings/Concatenation.java +++ b/strings/Concatenation.java @@ -1,5 +1,5 @@ // strings/Concatenation.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/strings/Conversion.java b/strings/Conversion.java index 3b4f723b8..c417c875c 100644 --- a/strings/Conversion.java +++ b/strings/Conversion.java @@ -1,5 +1,5 @@ // strings/Conversion.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.math.*; @@ -104,8 +104,8 @@ public static void main(String[] args) { h: 1ef462c y = new Conversion() b: true -s: Conversion@15db9742 -h: 15db9742 +s: Conversion@19e0bfd +h: 19e0bfd z = false b: false s: false diff --git a/strings/DataPoint.java b/strings/DataPoint.java new file mode 100644 index 000000000..719e0959d --- /dev/null +++ b/strings/DataPoint.java @@ -0,0 +1,32 @@ +// strings/DataPoint.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 15 + +public class DataPoint { + private String location; + private Double temperature; + public DataPoint(String loc, Double temp) { + location = loc; + temperature = temp; + } + @Override public String toString() { + return """ + Location: %s + Temperature: %.2f + """.formatted(location, temperature); + } + public static void main(String[] args) { + var hill = new DataPoint("Hill", 45.2); + var dale = new DataPoint("Dale", 65.2); + System.out.print(hill); + System.out.print(dale); + } +} +/* Output: +Location: Hill +Temperature: 45.20 +Location: Dale +Temperature: 65.20 +*/ diff --git a/strings/DatabaseException.java b/strings/DatabaseException.java index 136e4188c..5a7a9bd98 100644 --- a/strings/DatabaseException.java +++ b/strings/DatabaseException.java @@ -1,5 +1,5 @@ // strings/DatabaseException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/strings/Finding.java b/strings/Finding.java index 52dc5c99f..096b080d4 100644 --- a/strings/Finding.java +++ b/strings/Finding.java @@ -1,5 +1,5 @@ // strings/Finding.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/Groups.java b/strings/Groups.java index 22ff08678..b98fcddcc 100644 --- a/strings/Groups.java +++ b/strings/Groups.java @@ -1,5 +1,5 @@ // strings/Groups.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/Hex.java b/strings/Hex.java index 9257d87f5..47f05b80f 100644 --- a/strings/Hex.java +++ b/strings/Hex.java @@ -1,5 +1,5 @@ // strings/Hex.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.Hex} @@ -27,7 +27,7 @@ public static String format(byte[] data) { // Test by displaying this class file: System.out.println(format( Files.readAllBytes(Paths.get( - "build/classes/main/onjava/Hex.class")))); + "build/classes/java/main/onjava/Hex.class")))); else System.out.println(format( Files.readAllBytes(Paths.get(args[0])))); diff --git a/strings/Immutable.java b/strings/Immutable.java index 5a7d2a0a1..365c3ebe3 100644 --- a/strings/Immutable.java +++ b/strings/Immutable.java @@ -1,5 +1,5 @@ // strings/Immutable.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/strings/Indentation.java b/strings/Indentation.java new file mode 100644 index 000000000..71a88365f --- /dev/null +++ b/strings/Indentation.java @@ -0,0 +1,33 @@ +// strings/Indentation.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 15 + +public class Indentation { + public static final String NONE = """ + XXX + YYY + """; // No indentation + public static final String TWO = """ + XXX + YYY + """; // Produces indent of 2 + public static final String EIGHT = """ + XXX + YYY + """; // Produces indent of 8 + public static void main(String[] args) { + System.out.print(NONE); + System.out.print(TWO); + System.out.print(EIGHT); + } +} +/* Output: +XXX +YYY + XXX + YYY + XXX + YYY +*/ diff --git a/strings/InfiniteRecursion.java b/strings/InfiniteRecursion.java index 0be8e3843..cc523ec88 100644 --- a/strings/InfiniteRecursion.java +++ b/strings/InfiniteRecursion.java @@ -1,5 +1,5 @@ // strings/InfiniteRecursion.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Accidental recursion @@ -9,8 +9,7 @@ import java.util.stream.*; public class InfiniteRecursion { - @Override - public String toString() { + @Override public String toString() { return " InfiniteRecursion address: " + this + "\n"; } diff --git a/strings/IntegerMatch.java b/strings/IntegerMatch.java index 635339ea6..822c5d4c6 100644 --- a/strings/IntegerMatch.java +++ b/strings/IntegerMatch.java @@ -1,14 +1,18 @@ // strings/IntegerMatch.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. +import java.util.stream.*; public class IntegerMatch { public static void main(String[] args) { - System.out.println("-1234".matches("-?\\d+")); - System.out.println("5678".matches("-?\\d+")); - System.out.println("+911".matches("-?\\d+")); - System.out.println("+911".matches("(-|\\+)?\\d+")); + String possiblyMinus = "-?\\d+"; + Stream.of( + "-1234".matches(possiblyMinus), + "5678".matches(possiblyMinus), + "+911".matches(possiblyMinus), + "+911".matches("(-|\\+)?\\d+") + ).forEach(System.out::println); } } /* Output: diff --git a/strings/JGrep.java b/strings/JGrep.java index 3581edbcb..368fd13ef 100644 --- a/strings/JGrep.java +++ b/strings/JGrep.java @@ -1,10 +1,10 @@ // strings/JGrep.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A very simple version of the "grep" program // {java JGrep -// WhitherStringBuilder.java 'return|for|String'} +// WhitherStringBuilder.java "return|for|String"} import java.util.regex.*; import java.nio.file.*; import java.util.stream.*; @@ -18,19 +18,33 @@ public class JGrep { System.exit(0); } Pattern p = Pattern.compile(args[1]); - // Iterate through the lines of the input file: - int index = 0; Matcher m = p.matcher(""); - for(String line : - Files.readAllLines(Paths.get(args[0]))) { - m.reset(line); - while(m.find()) - System.out.println(index++ + ": " + - m.group() + ": " + m.start()); - } + // Iterate through the lines of the input file: + Files.readAllLines(Paths.get(args[0])).forEach( + line -> { + m.reset(line); + while(m.find()) + System.out.println( + m.group() + ": " + m.start()); + } + ); } } /* Output: -0: for: 4 -1: for: 4 +String: 18 +String: 20 +String: 9 +String: 25 +String: 4 +for: 4 +String: 8 +return: 4 +String: 9 +String: 25 +String: 4 +String: 31 +for: 4 +String: 8 +return: 4 +String: 20 */ diff --git a/strings/ReFlags.java b/strings/ReFlags.java index 7c7123caf..a407b6c97 100644 --- a/strings/ReFlags.java +++ b/strings/ReFlags.java @@ -1,5 +1,5 @@ // strings/ReFlags.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/ReceiptBuilder.java b/strings/ReceiptBuilder.java index cc782fac8..e58e8bb64 100644 --- a/strings/ReceiptBuilder.java +++ b/strings/ReceiptBuilder.java @@ -1,5 +1,5 @@ // strings/ReceiptBuilder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/Replacing.java b/strings/Replacing.java index b0e73c980..90394c32e 100644 --- a/strings/Replacing.java +++ b/strings/Replacing.java @@ -1,5 +1,5 @@ // strings/Replacing.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/strings/ReplacingStringTokenizer.java b/strings/ReplacingStringTokenizer.java index c6a168db0..9c2bee8ad 100644 --- a/strings/ReplacingStringTokenizer.java +++ b/strings/ReplacingStringTokenizer.java @@ -1,5 +1,5 @@ // strings/ReplacingStringTokenizer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/Resetting.java b/strings/Resetting.java index fc79a0381..67c4c8cd5 100644 --- a/strings/Resetting.java +++ b/strings/Resetting.java @@ -1,5 +1,5 @@ // strings/Resetting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/Rudolph.java b/strings/Rudolph.java index 22504fba8..b90813c7d 100644 --- a/strings/Rudolph.java +++ b/strings/Rudolph.java @@ -1,5 +1,5 @@ // strings/Rudolph.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/strings/ScannerDelimiter.java b/strings/ScannerDelimiter.java index 7ba644c79..7ac41a4c3 100644 --- a/strings/ScannerDelimiter.java +++ b/strings/ScannerDelimiter.java @@ -1,5 +1,5 @@ // strings/ScannerDelimiter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/SimpleFormat.java b/strings/SimpleFormat.java index 0a6bafdba..106f92572 100644 --- a/strings/SimpleFormat.java +++ b/strings/SimpleFormat.java @@ -1,5 +1,5 @@ // strings/SimpleFormat.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/strings/SimpleRead.java b/strings/SimpleRead.java index ee3e277fb..15533b973 100644 --- a/strings/SimpleRead.java +++ b/strings/SimpleRead.java @@ -1,5 +1,5 @@ // strings/SimpleRead.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/strings/SplitDemo.java b/strings/SplitDemo.java index 3f6788ea8..3d5eb6719 100644 --- a/strings/SplitDemo.java +++ b/strings/SplitDemo.java @@ -1,5 +1,5 @@ // strings/SplitDemo.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/Splitting.java b/strings/Splitting.java index e81bbc8c2..f22ea1a37 100644 --- a/strings/Splitting.java +++ b/strings/Splitting.java @@ -1,5 +1,5 @@ // strings/Splitting.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/StartEnd.java b/strings/StartEnd.java index ebf985ee4..072dde8de 100644 --- a/strings/StartEnd.java +++ b/strings/StartEnd.java @@ -1,5 +1,5 @@ // strings/StartEnd.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/TestRegularExpression.java b/strings/TestRegularExpression.java index a7adafbc1..d20af088f 100644 --- a/strings/TestRegularExpression.java +++ b/strings/TestRegularExpression.java @@ -1,5 +1,5 @@ // strings/TestRegularExpression.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple regular expression demonstration diff --git a/strings/TextBlocks.java b/strings/TextBlocks.java new file mode 100644 index 000000000..0e634001d --- /dev/null +++ b/strings/TextBlocks.java @@ -0,0 +1,37 @@ +// strings/TextBlocks.java +// (c)2021 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// {NewFeature} Since JDK 15 +// Poem: Antigonish by Hughes Mearns + +public class TextBlocks { + public static final String OLD = + "Yesterday, upon the stair,\n" + + "I met a man who wasn't there\n" + + "He wasn't there again today\n" + + "I wish, I wish he'd go away...\n" + + "\n" + + "When I came home last night at three\n" + + "The man was waiting there for me\n" + + "But when I looked around the hall\n" + + "I couldn't see him there at all!\n"; + + public static final String NEW = """ + Yesterday, upon the stair, + I met a man who wasn't there + He wasn't there again today + I wish, I wish he'd go away... + + When I came home last night at three + The man was waiting there for me + But when I looked around the hall + I couldn't see him there at all! + """; + public static void main(String[] args) { + System.out.println(OLD.equals(NEW)); + } +} +/* Output: +true +*/ diff --git a/strings/TheReplacements.java b/strings/TheReplacements.java index c3be94b65..cd543ab59 100644 --- a/strings/TheReplacements.java +++ b/strings/TheReplacements.java @@ -1,5 +1,5 @@ // strings/TheReplacements.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/ThreatAnalyzer.java b/strings/ThreatAnalyzer.java index 11712f5e4..28c500054 100644 --- a/strings/ThreatAnalyzer.java +++ b/strings/ThreatAnalyzer.java @@ -1,5 +1,5 @@ // strings/ThreatAnalyzer.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.regex.*; diff --git a/strings/Turtle.java b/strings/Turtle.java index edbebfeb4..f3121b755 100644 --- a/strings/Turtle.java +++ b/strings/Turtle.java @@ -1,5 +1,5 @@ // strings/Turtle.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.io.*; diff --git a/strings/UsingStringBuilder.java b/strings/UsingStringBuilder.java index 342c6426f..a5511ff63 100644 --- a/strings/UsingStringBuilder.java +++ b/strings/UsingStringBuilder.java @@ -1,5 +1,5 @@ // strings/UsingStringBuilder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; diff --git a/strings/WhitherStringBuilder.java b/strings/WhitherStringBuilder.java index 59cf3952f..f39d3f11f 100644 --- a/strings/WhitherStringBuilder.java +++ b/strings/WhitherStringBuilder.java @@ -1,5 +1,5 @@ // strings/WhitherStringBuilder.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. diff --git a/typeinfo/PetCount.java b/typeinfo/PetCount.java deleted file mode 100644 index 1f43267f4..000000000 --- a/typeinfo/PetCount.java +++ /dev/null @@ -1,65 +0,0 @@ -// typeinfo/PetCount.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Using instanceof -import typeinfo.pets.*; -import java.util.*; - -public class PetCount { - static class Counter extends HashMap { - public void count(String type) { - Integer quantity = get(type); - if(quantity == null) - put(type, 1); - else - put(type, quantity + 1); - } - } - public static void - countPets(PetCreator creator) { - Counter counter = new Counter(); - for(Pet pet : Pets.array(20)) { - // List each individual pet: - System.out.print( - pet.getClass().getSimpleName() + " "); - if(pet instanceof Pet) - counter.count("Pet"); - if(pet instanceof Dog) - counter.count("Dog"); - if(pet instanceof Mutt) - counter.count("Mutt"); - if(pet instanceof Pug) - counter.count("Pug"); - if(pet instanceof Cat) - counter.count("Cat"); - if(pet instanceof EgyptianMau) - counter.count("EgyptianMau"); - if(pet instanceof Manx) - counter.count("Manx"); - if(pet instanceof Cymric) - counter.count("Cymric"); - if(pet instanceof Rodent) - counter.count("Rodent"); - if(pet instanceof Rat) - counter.count("Rat"); - if(pet instanceof Mouse) - counter.count("Mouse"); - if(pet instanceof Hamster) - counter.count("Hamster"); - } - // Show the counts: - System.out.println(); - System.out.println(counter); - } - public static void main(String[] args) { - countPets(new ForNameCreator()); - } -} -/* Output: -Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat -EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse -Pug Mouse Cymric -{EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, -Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} -*/ diff --git a/typeinfo/pets/PetCreator.java b/typeinfo/pets/PetCreator.java deleted file mode 100644 index 99431c3cd..000000000 --- a/typeinfo/pets/PetCreator.java +++ /dev/null @@ -1,24 +0,0 @@ -// typeinfo/pets/PetCreator.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Creates random sequences of Pets -package typeinfo.pets; -import java.util.*; -import java.util.function.*; - -public abstract -class PetCreator implements Supplier { - private Random rand = new Random(47); - // The List of the different types of Pet to create: - public abstract List> types(); - public Pet get() { // Create one random Pet - int n = rand.nextInt(types().size()); - try { - return types().get(n).newInstance(); - } catch(InstantiationException | - IllegalAccessException e) { - throw new RuntimeException(e); - } - } -} diff --git a/typeinfo/pets/Pets.java b/typeinfo/pets/Pets.java deleted file mode 100644 index f99847b16..000000000 --- a/typeinfo/pets/Pets.java +++ /dev/null @@ -1,30 +0,0 @@ -// typeinfo/pets/Pets.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Facade to produce a default PetCreator -package typeinfo.pets; -import java.util.*; -import java.util.stream.*; - -public class Pets { - public static final PetCreator CREATOR = - new LiteralPetCreator(); - public static Pet get() { - return CREATOR.get(); - } - public static Pet[] array(int size) { - Pet[] result = new Pet[size]; - for(int i = 0; i < size; i++) - result[i] = CREATOR.get(); - return result; - } - public static List list(int size) { - List result = new ArrayList<>(); - Collections.addAll(result, array(size)); - return result; - } - public static Stream stream() { - return Stream.generate(CREATOR); - } -} diff --git a/typeinfo/toys/GenericToyTest.java b/typeinfo/toys/GenericToyTest.java deleted file mode 100644 index c0ae10669..000000000 --- a/typeinfo/toys/GenericToyTest.java +++ /dev/null @@ -1,22 +0,0 @@ -// typeinfo/toys/GenericToyTest.java -// (c)2017 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://OnJava8.com for more book information. -// Testing class Class -// {java typeinfo.toys.GenericToyTest} -package typeinfo.toys; - -public class GenericToyTest { - public static void - main(String[] args) throws Exception { - Class ftClass = FancyToy.class; - // Produces exact type: - FancyToy fancyToy = ftClass.newInstance(); - Class up = - ftClass.getSuperclass(); - // This won't compile: - // Class up2 = ftClass.getSuperclass(); - // Only produces Object: - Object obj = up.newInstance(); - } -} diff --git a/validating/Assert1.java b/validating/Assert1.java index 5527225e7..53dbfda30 100644 --- a/validating/Assert1.java +++ b/validating/Assert1.java @@ -1,5 +1,5 @@ // validating/Assert1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Non-informative style of assert diff --git a/validating/Assert2.java b/validating/Assert2.java index 684f97b22..cdc9f89dd 100644 --- a/validating/Assert2.java +++ b/validating/Assert2.java @@ -1,5 +1,5 @@ // validating/Assert2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Assert with an information-expression diff --git a/validating/BadMicroBenchmark.java b/validating/BadMicroBenchmark.java index ecc774ada..5e1ddbd7c 100644 --- a/validating/BadMicroBenchmark.java +++ b/validating/BadMicroBenchmark.java @@ -1,5 +1,5 @@ // validating/BadMicroBenchmark.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromTravisCI} @@ -24,6 +24,5 @@ public static void main(String[] args) { } } /* Output: -setAll: 272 -parallelSetAll: 301 +Insufficient memory */ diff --git a/validating/BadMicroBenchmark2.java b/validating/BadMicroBenchmark2.java index fd840ddaf..aab204bfb 100644 --- a/validating/BadMicroBenchmark2.java +++ b/validating/BadMicroBenchmark2.java @@ -1,5 +1,5 @@ // validating/BadMicroBenchmark2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Relying on a common resource @@ -28,8 +28,8 @@ public static void main(String[] args) { } } /* Output: -parallelSetAll: 1147 -setAll: 174 -parallelSetAll: 86 -setAll: 39 +parallelSetAll: 1008 +setAll: 294 +parallelSetAll: 78 +setAll: 88 */ diff --git a/validating/CircularQueue.java b/validating/CircularQueue.java index bd5166ad1..b42509cf9 100644 --- a/validating/CircularQueue.java +++ b/validating/CircularQueue.java @@ -1,5 +1,5 @@ // validating/CircularQueue.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstration of Design by Contract (DbC) diff --git a/validating/CircularQueueException.java b/validating/CircularQueueException.java index 056123442..c30710df0 100644 --- a/validating/CircularQueueException.java +++ b/validating/CircularQueueException.java @@ -1,5 +1,5 @@ // validating/CircularQueueException.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; diff --git a/validating/CountedList.java b/validating/CountedList.java index e33e13b03..30de1acc5 100644 --- a/validating/CountedList.java +++ b/validating/CountedList.java @@ -1,5 +1,5 @@ // validating/CountedList.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Keeps track of how many of itself are created. diff --git a/validating/GuavaAssertions.java b/validating/GuavaAssertions.java index 38fcb444d..85c724f6f 100644 --- a/validating/GuavaAssertions.java +++ b/validating/GuavaAssertions.java @@ -1,5 +1,5 @@ // validating/GuavaAssertions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Assertions that are always enabled. diff --git a/validating/GuavaPreconditions.java b/validating/GuavaPreconditions.java index 752fe6af7..f8f9c702a 100644 --- a/validating/GuavaPreconditions.java +++ b/validating/GuavaPreconditions.java @@ -1,5 +1,5 @@ // validating/GuavaPreconditions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrating Guava Preconditions diff --git a/validating/Inverter1.java b/validating/Inverter1.java index 9c8a54630..78ec38dc1 100644 --- a/validating/Inverter1.java +++ b/validating/Inverter1.java @@ -1,9 +1,10 @@ // validating/Inverter1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; public class Inverter1 implements StringInverter { + @Override public String invert(String str) { return str; } } diff --git a/validating/Inverter2.java b/validating/Inverter2.java index b1ae74835..5ea22f6fd 100644 --- a/validating/Inverter2.java +++ b/validating/Inverter2.java @@ -1,12 +1,12 @@ // validating/Inverter2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; import static java.lang.Character.*; public class Inverter2 implements StringInverter { - public String invert(String str) { + @Override public String invert(String str) { String result = ""; for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); diff --git a/validating/Inverter3.java b/validating/Inverter3.java index f7c4bd14e..eecf815e3 100644 --- a/validating/Inverter3.java +++ b/validating/Inverter3.java @@ -1,12 +1,12 @@ // validating/Inverter3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; import static java.lang.Character.*; public class Inverter3 implements StringInverter { - public String invert(String str) { + @Override public String invert(String str) { if(str.length() > 30) throw new RuntimeException("argument too long!"); String result = ""; diff --git a/validating/Inverter4.java b/validating/Inverter4.java index ffd24b8f9..4bb15f12f 100644 --- a/validating/Inverter4.java +++ b/validating/Inverter4.java @@ -1,5 +1,5 @@ // validating/Inverter4.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; @@ -9,7 +9,7 @@ public class Inverter4 implements StringInverter { static final String ALLOWED = "abcdefghijklmnopqrstuvwxyz ,." + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - public String invert(String str) { + @Override public String invert(String str) { if(str.length() > 30) throw new RuntimeException("argument too long!"); String result = ""; diff --git a/validating/LoaderAssertions.java b/validating/LoaderAssertions.java index c15ac97e3..aa150ad7e 100644 --- a/validating/LoaderAssertions.java +++ b/validating/LoaderAssertions.java @@ -1,5 +1,5 @@ // validating/LoaderAssertions.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using the class loader to enable assertions diff --git a/validating/NonNullConstruction.java b/validating/NonNullConstruction.java index b75ef2433..4caa3de54 100644 --- a/validating/NonNullConstruction.java +++ b/validating/NonNullConstruction.java @@ -1,5 +1,5 @@ // validating/NonNullConstruction.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import static com.google.common.base.Preconditions.*; diff --git a/validating/SLF4JLevels.java b/validating/SLF4JLevels.java index 8100bd6d6..d56821a52 100644 --- a/validating/SLF4JLevels.java +++ b/validating/SLF4JLevels.java @@ -1,5 +1,5 @@ // validating/SLF4JLevels.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import org.slf4j.*; @@ -16,14 +16,14 @@ public static void main(String[] args) { } } /* Output: -2017-05-09T06:07:52.846 +2021-01-24T08:49:37.658 [main] TRACE SLF4JLevels - Hello -2017-05-09T06:07:52.849 +2021-01-24T08:49:37.661 [main] DEBUG SLF4JLevels - Logging -2017-05-09T06:07:52.849 +2021-01-24T08:49:37.661 [main] INFO SLF4JLevels - Using -2017-05-09T06:07:52.850 +2021-01-24T08:49:37.661 [main] WARN SLF4JLevels - the SLF4J -2017-05-09T06:07:52.851 +2021-01-24T08:49:37.661 [main] ERROR SLF4JLevels - Facade */ diff --git a/validating/SLF4JLogging.java b/validating/SLF4JLogging.java index 1c124a136..f8eeb696c 100644 --- a/validating/SLF4JLogging.java +++ b/validating/SLF4JLogging.java @@ -1,5 +1,5 @@ // validating/SLF4JLogging.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import org.slf4j.*; @@ -12,6 +12,6 @@ public static void main(String[] args) { } } /* Output: -2017-05-09T06:07:53.418 +2021-01-24T08:49:38.496 [main] INFO SLF4JLogging - hello logging */ diff --git a/validating/SimpleDebugging.java b/validating/SimpleDebugging.java index 62766283f..609e8e7d5 100644 --- a/validating/SimpleDebugging.java +++ b/validating/SimpleDebugging.java @@ -1,5 +1,5 @@ // validating/SimpleDebugging.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ThrowsException} @@ -23,18 +23,3 @@ public static void main(String[] args) { foo1(); } } -/* Output: -In foo1 -In foo2 -In foo3 -___[ Error Output ]___ -Exception in thread "main" -java.lang.ArithmeticException: / by zero - at -SimpleDebugging.foo3(SimpleDebugging.java:17) - at -SimpleDebugging.foo2(SimpleDebugging.java:11) - at SimpleDebugging.foo1(SimpleDebugging.java:7) - at -SimpleDebugging.main(SimpleDebugging.java:20) -*/ diff --git a/validating/StringInverter.java b/validating/StringInverter.java index 3ef11e8ca..542788935 100644 --- a/validating/StringInverter.java +++ b/validating/StringInverter.java @@ -1,5 +1,5 @@ // validating/StringInverter.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; diff --git a/validating/jmh/JMH1.java b/validating/jmh/JMH1.java index b1767a77b..63657c3fa 100644 --- a/validating/jmh/JMH1.java +++ b/validating/jmh/JMH1.java @@ -1,5 +1,5 @@ // validating/jmh/JMH1.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating.jmh; diff --git a/validating/jmh/JMH2.java b/validating/jmh/JMH2.java index e119f1b51..5010b00ed 100644 --- a/validating/jmh/JMH2.java +++ b/validating/jmh/JMH2.java @@ -1,5 +1,5 @@ // validating/jmh/JMH2.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating.jmh; diff --git a/validating/jmh/JMH3.java b/validating/jmh/JMH3.java index ffb46ffe0..7bf22de11 100644 --- a/validating/jmh/JMH3.java +++ b/validating/jmh/JMH3.java @@ -1,5 +1,5 @@ // validating/jmh/JMH3.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating.jmh; diff --git a/validating/tests/CircularQueueTest.java b/validating/tests/CircularQueueTest.java index 37c45fa35..920b459be 100644 --- a/validating/tests/CircularQueueTest.java +++ b/validating/tests/CircularQueueTest.java @@ -1,5 +1,5 @@ // validating/tests/CircularQueueTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; diff --git a/validating/tests/CountedListTest.java b/validating/tests/CountedListTest.java index d852485ca..74a29b376 100644 --- a/validating/tests/CountedListTest.java +++ b/validating/tests/CountedListTest.java @@ -1,5 +1,5 @@ // validating/tests/CountedListTest.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple use of JUnit to test CountedList. diff --git a/validating/tests/DynamicStringInverterTests.java b/validating/tests/DynamicStringInverterTests.java index 329ae6320..338b65fb0 100644 --- a/validating/tests/DynamicStringInverterTests.java +++ b/validating/tests/DynamicStringInverterTests.java @@ -1,5 +1,5 @@ // validating/tests/DynamicStringInverterTests.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; diff --git a/validating/tests/StringInverterTests.java b/validating/tests/StringInverterTests.java index 142512177..01ada920e 100644 --- a/validating/tests/StringInverterTests.java +++ b/validating/tests/StringInverterTests.java @@ -1,5 +1,5 @@ // validating/tests/StringInverterTests.java -// (c)2017 MindView LLC: see Copyright.txt +// (c)2021 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. package validating; @@ -22,7 +22,7 @@ void basicInversion1() { } @Test void basicInversion2() { - expectThrows(Error.class, () -> { + assertThrows(Error.class, () -> { assertEquals(inverter.invert("X"), "X"); }); } @@ -52,7 +52,7 @@ void allowedCharacters() { void lengthNoGreaterThan30() { String str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; assertTrue(str.length() > 30); - expectThrows(RuntimeException.class, () -> { + assertThrows(RuntimeException.class, () -> { inverter.invert(str); }); }