diff --git a/.gitignore b/.gitignore index b2c1bb917..48292956e 100644 --- a/.gitignore +++ b/.gitignore @@ -107,3 +107,5 @@ buildSrc/ /standardio/Redirecting.txt /threads/PSP2.txt /threads/primes.txt +_* +config.py 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/ShowFindbugs.py b/ShowFindbugs.py deleted file mode 100644 index ec11f8fb6..000000000 --- a/ShowFindbugs.py +++ /dev/null @@ -1,10 +0,0 @@ -#! py -3 -# Requires Python 3.5 -# Displays all the Findbugs main.html reports from "On Java 8" on Windows -# Must run "gradlew findbugsMain" first -from pathlib import Path -import os - -cmds = ["start " + str(report) for report in Path(".").rglob("main.html")] -(Path(".") / "ShowFindbugs.bat").write_text("\n".join(cmds).strip() + "\n") -os.system("ShowFindbugs.bat") diff --git a/_verify_output.py b/_verify_output.py deleted file mode 100644 index 088ca6a35..000000000 --- a/_verify_output.py +++ /dev/null @@ -1,185 +0,0 @@ -#! py -3 -# Requires Python 3.5 -# Validates output from executable Java programs in "On Java 8." -# Use chain of responsibility to successively try strategies until one matches -from pathlib import Path -import textwrap -import re -import sys -import os -import textwrap -from collections import defaultdict -WIDTH = 59 # Max line width - -#################### Phase 1: Basic formatting ##################### - -def adjust_lines(text): - text = text.replace("\0", "NUL") - lines = text.splitlines() - slug = lines[0] - if "(First and Last " in slug: - num_of_lines = int(slug.split()[5]) - adjusted = lines[:num_of_lines + 1] +\ - ["...________...________...________...________..."] +\ - lines[-num_of_lines:] - return "\n".join(adjusted) - elif "(First " in slug: - num_of_lines = int(slug.split()[3]) - adjusted = lines[:num_of_lines + 1] +\ - [" ..."] - return "\n".join(adjusted) - else: - return text - -def fill_to_width(text): - result = "" - for line in text.splitlines(): - result += textwrap.fill(line, width = WIDTH) + "\n" - return result.strip() - -def phase1(): - """ - (0) Do first/last lines before formatting to width - (1) Combine output and error (if present) files - (2) Format all output to width limit - (3) Add closing '*/' - """ - for outfile in Path(".").rglob("*.out"): - out_text = adjust_lines(outfile.read_text()) - phase_1 = outfile.with_suffix(".p1") - with phase_1.open('w') as phs1: - phs1.write(fill_to_width(out_text) + "\n") - errfile = outfile.with_suffix(".err") - if errfile.exists(): - phs1.write("___[ Error Output ]___\n") - phs1.write(fill_to_width(errfile.read_text()) + "\n") - phs1.write("*/\n") - - -########### Chain of Responsibility Match Finder ####################### - -def exact_match(text): return text - -memlocation = re.compile("@[0-9a-z]{5,7}") - -def ignore_memory_addresses(text): - return memlocation.sub("", text) - -datestamp1 = re.compile( - "(?:[MTWFS][a-z]{2} ){0,1}[JFMASOND][a-z]{2} \d{1,2} \d{2}:\d{2}:\d{2} [A-Z]{3} \d{4}") -datestamp2 = re.compile( - "[JFMASOND][a-z]{2} \d{1,2}, \d{4} \d{1,2}:\d{1,2}:\d{1,2} (:?AM|PM)") - -def ignore_dates(text): - for pat in [ datestamp1, datestamp2 ]: - text = pat.sub("", text) - return text - -def ignore_digits(input_text): - return re.sub("-?\d", "", input_text) - -def sort_lines(input_text): - return "\n".join(sorted(input_text.splitlines())).strip() - -def sort_words(input_text): - return "\n".join(sorted(input_text.split())).strip() - -def unique_lines(input_text): - return "\n".join(sorted(list(set(input_text.splitlines())))) - -# Fairly extreme but will still reveal significant changes -def unique_words(input_text): - return "\n".join(sorted(set(input_text.split()))) - -# Fairly extreme but will still reveal significant changes -word_only = re.compile("[A-Za-z]+") -def words_only(input_text): - return "\n".join( - sorted([w for w in input_text.split() - if word_only.fullmatch(w)])) - -def no_match(input_text): return True - -# Chain of responsibility: -strategies = [ - # Filter # Retain result - # for rest of chain - (exact_match, False), - (ignore_dates, True), - (ignore_memory_addresses, True), - (sort_lines, False), - (ignore_digits, False), - (sort_words, False), - (unique_lines, False), - (unique_words, False), - (words_only, False), - (no_match, False), -] - - -class Validator(defaultdict): # Map of lists - compare_output = Path(".") / "compare_output.bat" - - def __init__(self): - super().__init__(list) - if Validator.compare_output.exists(): - Validator.compare_output.unlink() - for strategy, retain in strategies: - strat_batch = Path(strategy.__name__ + ".bat") - if strat_batch.exists(): - strat_batch.unlink() - - def find_output_match(self, javafile, embedded_output, generated_output): - for strategy, retain in strategies: - filtered_embedded_output = strategy(embedded_output) - filtered_generated_output = strategy(generated_output) - if filtered_embedded_output == filtered_generated_output: - strat_name = strategy.__name__ - self[strat_name].append(str(javafile)) - if strat_name is "exact_match": return - tfile = javafile.with_suffix("." + strat_name) - with Path(strat_name + ".bat").open('a') as strat_batch: - strat_batch.write("subl " + str(tfile) + "\n") - with Validator.compare_output.open('a') as batch: - batch.write("subl " + str(tfile) + "\n") - with tfile.open('w') as trace_file: - trace_file.write(javafile.read_text() + "\n\n") - trace_file.write("// === Actual ===\n\n") - trace_file.write(str(generated_output)) - return - if retain: - embedded_output = filtered_embedded_output - generated_output = filtered_generated_output - - def display_results(self): - log = open("verified_output.txt", 'w') - for strategy, retain in strategies: - key = strategy.__name__ - if key is "exact_match": - for java in self[key]: - print(java) - elif key in self: - log.write("\n" + (" " + key + " ").center(45, "=") + "\n") - for java in self[key]: - log.write(java + "\n") - log.close() - - -if __name__ == '__main__': - phase1() # Generates '.p1' files - find_output = re.compile(r"/\* (Output:.*)\*/", re.DOTALL) - validator = Validator() - for outfile in Path(".").rglob("*.p1"): - javafile = outfile.with_suffix(".java") - if not javafile.exists(): - print(str(outfile) + " has no javafile") - sys.exit(1) - javatext = javafile.read_text() - if "/* Output:" not in javatext: - print(str(outfile) + " has no /* Output:") - sys.exit(1) - validator.find_output_match(javafile, - find_output.search(javatext).group(0).strip(), - outfile.read_text().strip()) - validator.display_results() - os.system("more verified_output.txt") diff --git a/annotations/AtUnitComposition.java b/annotations/AUComposition.java similarity index 73% rename from annotations/AtUnitComposition.java rename to annotations/AUComposition.java index 1b6d59106..94d51e607 100644 --- a/annotations/AtUnitComposition.java +++ b/annotations/AUComposition.java @@ -1,15 +1,15 @@ -// annotations/AtUnitComposition.java -// (c)2017 MindView LLC: see Copyright.txt +// annotations/AUComposition.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. // Creating non-embedded tests // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitComposition.class} +// build/classes/java/main/annotations/AUComposition.class} package annotations; import onjava.atunit.*; import onjava.*; -public class AtUnitComposition { +public class AUComposition { AtUnitExample1 testObject = new AtUnitExample1(); @Test boolean tMethodOne() { @@ -22,7 +22,7 @@ boolean tMethodTwo() { } } /* Output: -annotations.AtUnitComposition +annotations.AUComposition . tMethodOne . tMethodTwo This is methodTwo diff --git a/annotations/AtUnitExternalTest.java b/annotations/AUExternalTest.java similarity index 69% rename from annotations/AtUnitExternalTest.java rename to annotations/AUExternalTest.java index d6ba375b1..71c8f2f4b 100644 --- a/annotations/AtUnitExternalTest.java +++ b/annotations/AUExternalTest.java @@ -1,16 +1,16 @@ -// annotations/AtUnitExternalTest.java -// (c)2017 MindView LLC: see Copyright.txt +// annotations/AUExternalTest.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. // Creating non-embedded tests // {java onjava.atunit.AtUnit -// build/classes/main/annotations/AtUnitExternalTest.class} +// build/classes/java/main/annotations/AUExternalTest.class} package annotations; import onjava.atunit.*; import onjava.*; public class -AtUnitExternalTest extends AtUnitExample1 { +AUExternalTest extends AtUnitExample1 { @Test boolean tMethodOne() { return methodOne().equals("This is methodOne"); @@ -21,9 +21,9 @@ boolean tMethodTwo() { } } /* Output: -annotations.AtUnitExternalTest +annotations.AUExternalTest + . tMethodOne . tMethodTwo This is methodTwo - . tMethodOne OK (2 tests) */ diff --git a/annotations/AtUnitExample1.java b/annotations/AtUnitExample1.java index d0f6f1e12..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.*; @@ -35,11 +35,11 @@ boolean anotherDisappointment() { /* Output: annotations.AtUnitExample1 . anotherDisappointment (failed) + . methodOneTest + . failureTest (failed) . m2 This is methodTwo . m3 - . failureTest (failed) - . methodOneTest (5 tests) >>> 2 FAILURES <<< diff --git a/annotations/AtUnitExample2.java b/annotations/AtUnitExample2.java index 44cf7552c..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.*; @@ -28,7 +28,8 @@ void assertFailureExample() { } @Test void exceptionExample() throws IOException { - new FileInputStream("nofile.txt"); // Throws + try(FileInputStream fis = + new FileInputStream("nofile.txt")) {} // Throws } @Test boolean assertAndReturn() { @@ -39,8 +40,8 @@ boolean assertAndReturn() { } /* Output: annotations.AtUnitExample2 - . assertFailureExample java.lang.AssertionError: What a -surprise! + . assertFailureExample java.lang.AssertionError: What +a surprise! (failed) . assertExample . exceptionExample java.io.FileNotFoundException: diff --git a/annotations/AtUnitExample3.java b/annotations/AtUnitExample3.java index aabb92dcf..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.*; @@ -34,9 +34,9 @@ boolean methodOneTest() { } /* Output: annotations.AtUnitExample3 + . initialization + . methodOneTest . m2 This is methodTwo - . methodOneTest - . initialization OK (3 tests) */ diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java index 2837c81aa..23bc21efb 100644 --- a/annotations/AtUnitExample4.java +++ b/annotations/AtUnitExample4.java @@ -1,9 +1,10 @@ // 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.*; import onjava.atunit.*; 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 new file mode 100644 index 000000000..13f12bbf5 --- /dev/null +++ b/annotations/DemoProcessFiles.java @@ -0,0 +1,43 @@ +// annotations/DemoProcessFiles.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.ProcessFiles; + +public class DemoProcessFiles { + public static void main(String[] args) { + new ProcessFiles(file -> System.out.println(file), + "java").start(args); + } +} +/* Output: +.\AtUnitExample1.java +.\AtUnitExample2.java +.\AtUnitExample3.java +.\AtUnitExample4.java +.\AtUnitExample5.java +.\AUComposition.java +.\AUExternalTest.java +.\database\Constraints.java +.\database\DBTable.java +.\database\Member.java +.\database\SQLInteger.java +.\database\SQLString.java +.\database\TableCreator.java +.\database\Uniqueness.java +.\DemoProcessFiles.java +.\HashSetTest.java +.\ifx\ExtractInterface.java +.\ifx\IfaceExtractorProcessor.java +.\ifx\Multiplier.java +.\PasswordUtils.java +.\simplest\Simple.java +.\simplest\SimpleProcessor.java +.\simplest\SimpleTest.java +.\SimulatingNull.java +.\StackL.java +.\StackLStringTst.java +.\Testable.java +.\UseCase.java +.\UseCaseTracker.java +*/ diff --git a/annotations/HashSetTest.java b/annotations/HashSetTest.java index 27044ed92..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 - . tRemove . tContains . initialization + . tRemove 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 63c1229a7..246454c25 100644 --- a/annotations/StackL.java +++ b/annotations/StackL.java @@ -1,8 +1,8 @@ // 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 +// A stack built on a LinkedList package annotations; import java.util.*; diff --git a/annotations/StackLStringTest.java b/annotations/StackLStringTst.java similarity index 76% rename from annotations/StackLStringTest.java rename to annotations/StackLStringTst.java index fa0655b59..b7d8250f7 100644 --- a/annotations/StackLStringTest.java +++ b/annotations/StackLStringTst.java @@ -1,16 +1,16 @@ -// annotations/StackLStringTest.java -// (c)2017 MindView LLC: see Copyright.txt +// annotations/StackLStringTst.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. // Applying @Unit to generics // {java onjava.atunit.AtUnit -// build/classes/main/annotations/StackLStringTest.class} +// build/classes/java/main/annotations/StackLStringTst.class} package annotations; import onjava.atunit.*; import onjava.*; public class -StackLStringTest extends StackL { +StackLStringTst extends StackL { @Test void tPush() { push("one"); @@ -34,7 +34,7 @@ void tTop() { } } /* Output: -annotations.StackLStringTest +annotations.StackLStringTst . tPop . tTop . tPush 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 4f60f30ef..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.*; @@ -14,7 +14,7 @@ public class UseCaseTracker { if(uc != null) { System.out.println("Found Use Case " + uc.id() + "\n " + uc.description()); - useCases.remove(new Integer(uc.id())); + useCases.remove(Integer.valueOf(uc.id())); } } useCases.forEach(i -> @@ -29,9 +29,9 @@ public static void main(String[] args) { /* Output: Found Use Case 49 New passwords can't equal previously used ones -Found Use Case 47 - Passwords must contain at least one numeric Found Use Case 48 no description +Found Use Case 47 + Passwords must contain at least one numeric 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 3248645d6..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 @@ -14,7 +14,8 @@ public class TableCreator { public static void main(String[] args) throws Exception { if(args.length < 1) { - System.out.println("arguments: annotated classes"); + System.out.println( + "arguments: annotated classes"); System.exit(0); } for(String className : args) { @@ -22,7 +23,8 @@ public class TableCreator { DBTable dbTable = cl.getAnnotation(DBTable.class); if(dbTable == null) { System.out.println( - "No DBTable annotations in class " + className); + "No DBTable annotations in class " + + className); continue; } String tableName = dbTable.name(); @@ -66,11 +68,12 @@ public class TableCreator { String tableCreate = createCommand.substring( 0, createCommand.length() - 1) + ");"; System.out.println("Table Creation SQL for " + - className + " is :\n" + tableCreate); + className + " is:\n" + tableCreate); } } } - private static String getConstraints(Constraints con) { + private static + String getConstraints(Constraints con) { String constraints = ""; if(!con.allowNull()) constraints += " NOT NULL"; @@ -82,19 +85,19 @@ private static String getConstraints(Constraints con) { } } /* Output: -Table Creation SQL for annotations.database.Member is : +Table Creation SQL for annotations.database.Member is: CREATE TABLE MEMBER( FIRSTNAME VARCHAR(30)); -Table Creation SQL for annotations.database.Member is : +Table Creation SQL for annotations.database.Member is: CREATE TABLE MEMBER( FIRSTNAME VARCHAR(30), LASTNAME VARCHAR(50)); -Table Creation SQL for annotations.database.Member is : +Table Creation SQL for annotations.database.Member is: CREATE TABLE MEMBER( FIRSTNAME VARCHAR(30), LASTNAME VARCHAR(50), AGE INT); -Table Creation SQL for annotations.database.Member is : +Table Creation SQL for annotations.database.Member is: CREATE TABLE MEMBER( FIRSTNAME VARCHAR(30), LASTNAME VARCHAR(50), 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 acaa73684..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 @@ -19,11 +19,11 @@ public static void main(String[] args) { } } /* Output: -[anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv, -eloztdv, ewcippc, ezdeklu, fcjpthl, -fqmlgsh, gmeinne, hyoubzl, jbvlgwc, jlxpqds, -ljlbynx, mvducuj, qgekgly, skddcat, -taprwxz, uybypgp, vjsszkn, vniyapk, vqqakbm, -vwodhcf, ydpulcq, ygpoalk, yskvett, -zehpfmm, zofmmvm, zrxmclh] Index: 10 gmeinne +[anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv, eloztdv, +ewcippc, ezdeklu, fcjpthl, fqmlgsh, gmeinne, hyoubzl, +jbvlgwc, jlxpqds, ljlbynx, mvducuj, qgekgly, skddcat, +taprwxz, uybypgp, vjsszkn, vniyapk, vqqakbm, vwodhcf, +ydpulcq, ygpoalk, yskvett, zehpfmm, zofmmvm, zrxmclh] +Index: 10 +gmeinne */ diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java index 01022e242..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() @@ -9,15 +9,14 @@ class Sup { // Superclass private int id; - public Sup(int n) { id = n; } - @Override - public String toString() { + Sup(int n) { id = n; } + @Override public String toString() { return getClass().getSimpleName() + id; } } class Sub extends Sup { // Subclass - public Sub(int n) { super(n); } + Sub(int n) { super(n); } } public class ArrayCopying { @@ -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); @@ -61,8 +60,8 @@ public static void main(String[] args) { Sup[] b2 = new Sup[SZ/2]; Arrays.setAll(b2, Sup::new); try { - Sub[] d3 = - Arrays.copyOf(b2, b2.length, Sub[].class); // [6] + Sub[] d3 = Arrays.copyOf( + b2, b2.length, Sub[].class); // [6] } catch(Exception e) { System.out.println(e); } diff --git a/arrays/ArrayOfGenericType.java b/arrays/ArrayOfGenericType.java index fb8d0a40b..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. @@ -8,7 +8,7 @@ public class ArrayOfGenericType { @SuppressWarnings("unchecked") public ArrayOfGenericType(int size) { // error: generic array creation: - // - array = new T[size]; + //- array = new T[size]; array = (T[])new Object[size]; // unchecked cast } // error: generic array creation: diff --git a/arrays/ArrayOfGenerics.java b/arrays/ArrayOfGenerics.java index cc2a2600c..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.*; @@ -12,7 +12,7 @@ public static void main(String[] args) { ls = (List[])la; // Unchecked cast ls[0] = new ArrayList<>(); - // -ls[1] = new ArrayList(); + //- ls[1] = new ArrayList(); // error: incompatible types: ArrayList // cannot be converted to List // ls[1] = new ArrayList(); 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 67de49b4a..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() @@ -26,8 +26,8 @@ public static void main(String[] args) { } } /* Output: -Sorted array: [125, 267, 635, 650, 1131, 1506, 1634, 2400, -2766, 3063, 3768, 3941, 4720, 4762, 4948, 5070, 5682, 5807, -6177, 6193, 6656, 7021, 8479, 8737, 9954] +Sorted array: [125, 267, 635, 650, 1131, 1506, 1634, +2400, 2766, 3063, 3768, 3941, 4720, 4762, 4948, 5070, +5682, 5807, 6177, 6193, 6656, 7021, 8479, 8737, 9954] Location of 635 is 2, a[2] is 635 */ 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 4e34f753c..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.*; @@ -16,7 +16,7 @@ public static void main(String[] args) { } } /* Output: -[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [21, 22, 23, 24, 25, 26, -27, 28, 29, 30], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], -[71, 72, 73, 74, 75, 76, 77, 78, 79, 80]] +[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [21, 22, 23, 24, 25, +26, 27, 28, 29, 30], [51, 52, 53, 54, 55, 56, 57, 58, +59, 60], [71, 72, 73, 74, 75, 76, 77, 78, 79, 80]] */ diff --git a/arrays/CollectionComparison.java b/arrays/CollectionComparison.java index 108faed91..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; } } @@ -41,8 +40,8 @@ public static void main(String[] args) { } } /* Output: -[Sphere 0, Sphere 1, Sphere 2, Sphere 3, Sphere 4, null, -null, null, null, null] +[Sphere 0, Sphere 1, Sphere 2, Sphere 3, Sphere 4, +null, null, null, null, null] Sphere 4 [Sphere 5, Sphere 6, Sphere 7, Sphere 8, Sphere 9] Sphere 9 diff --git a/arrays/CompType.java b/arrays/CompType.java index 0e8e6f4e5..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 = @@ -41,14 +39,14 @@ public static void main(String[] args) { } } /* Output: -Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i = -77, j = 79] +Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i += 77, j = 79] , [i = 56, j = 68], [i = 48, j = 93], [i = 70, j = 7] , [i = 0, j = 25], [i = 62, j = 34], [i = 50, j = 82] , [i = 31, j = 67], [i = 66, j = 54], [i = 21, j = 6] ] -After sorting: [[i = 0, j = 25], [i = 21, j = 6], [i = 31, -j = 67] +After sorting: [[i = 0, j = 25], [i = 21, j = 6], [i = +31, j = 67] , [i = 35, j = 37], [i = 41, j = 20], [i = 48, j = 93] , [i = 50, j = 82], [i = 56, j = 68], [i = 62, j = 34] , [i = 66, j = 54], [i = 70, j = 7], [i = 77, j = 79] diff --git a/arrays/ComparatorTest.java b/arrays/ComparatorTest.java index 0edf8b6db..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 @@ -7,7 +7,8 @@ import onjava.*; import static onjava.ArrayShow.*; -class CompTypeComparator implements Comparator { +class CompTypeComparator +implements Comparator { public int compare(CompType o1, CompType o2) { return (o1.j < o2.j ? -1 : (o1.j == o2.j ? 0 : 1)); } @@ -23,14 +24,14 @@ public static void main(String[] args) { } } /* Output: -Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i = -77, j = 79] +Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i += 77, j = 79] , [i = 56, j = 68], [i = 48, j = 93], [i = 70, j = 7] , [i = 0, j = 25], [i = 62, j = 34], [i = 50, j = 82] , [i = 31, j = 67], [i = 66, j = 54], [i = 21, j = 6] ] -After sorting: [[i = 21, j = 6], [i = 70, j = 7], [i = 41, -j = 20] +After sorting: [[i = 21, j = 6], [i = 70, j = 7], [i = +41, j = 20] , [i = 0, j = 25], [i = 62, j = 34], [i = 35, j = 37] , [i = 66, j = 54], [i = 31, j = 67], [i = 56, j = 68] , [i = 77, j = 79], [i = 50, j = 82], [i = 48, j = 93] 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 3208e2cb2..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.*; @@ -19,6 +19,6 @@ public static void main(String[] args) { } } /* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -17, 18, 19] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +16, 17, 18, 19] */ 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 a5e38b4a6..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 @@ -19,17 +19,20 @@ public static void main(String[] args) { String[][] a3 = { { "The", "Quick", "Sly", "Fox" }, { "Jumped", "Over" }, - { "The", "Lazy", "Brown", "Dog", "and", "friend" }, + { "The", "Lazy", "Brown", "Dog", "&", "friend" }, }; - System.out.println("a1: " + Arrays.deepToString(a1)); - System.out.println("a2: " + Arrays.deepToString(a2)); - System.out.println("a3: " + Arrays.deepToString(a3)); + System.out.println( + "a1: " + Arrays.deepToString(a1)); + System.out.println( + "a2: " + Arrays.deepToString(a2)); + System.out.println( + "a3: " + Arrays.deepToString(a3)); } } /* Output: a1: [[1, 2, 3], [4, 5, 6]] -a2: [[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, 8.8]], -[[9.9, 1.2], [2.3, 3.4]]] -a3: [[The, Quick, Sly, Fox], [Jumped, Over], [The, Lazy, -Brown, Dog, and, friend]] +a2: [[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, +8.8]], [[9.9, 1.2], [2.3, 3.4]]] +a3: [[The, Quick, Sly, Fox], [Jumped, Over], [The, +Lazy, Brown, Dog, &, friend]] */ diff --git a/arrays/MultidimensionalObjectArrays.java b/arrays/MultidimensionalObjectArrays.java index d63c7c4ba..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.*; @@ -20,6 +20,6 @@ public static void main(String[] args) { } /* Output: [[Sphere 0, Sphere 1], [Sphere 2, Sphere 3, Sphere 4, -Sphere 5], [Sphere 6, Sphere 7, Sphere 8, Sphere 9, Sphere -10, Sphere 11, Sphere 12, Sphere 13]] +Sphere 5], [Sphere 6, Sphere 7, Sphere 8, Sphere 9, +Sphere 10, Sphere 11, Sphere 12, Sphere 13]] */ 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 e436023ad..88d32916e 100644 --- a/arrays/ParallelPrefix3.java +++ b/arrays/ParallelPrefix3.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} // CI Systems have trouble +// {ExcludeFromTravisCI} import java.util.*; public class ParallelPrefix3 { 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 c5c356059..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,13 +14,13 @@ 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)); } } /* Output: -[[[1], []], [[2, 3, 4, 5], [6]], [[7, 8, 9], [10, 11, 12], -[]]] +[[[1], []], [[2, 3, 4, 5], [6]], [[7, 8, 9], [10, 11, +12], []]] */ diff --git a/arrays/Reverse.java b/arrays/Reverse.java index 7bfc848fd..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 @@ -17,14 +17,14 @@ public static void main(String[] args) { } } /* Output: -Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i = -77, j = 79] +Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i += 77, j = 79] , [i = 56, j = 68], [i = 48, j = 93], [i = 70, j = 7] , [i = 0, j = 25], [i = 62, j = 34], [i = 50, j = 82] , [i = 31, j = 67], [i = 66, j = 54], [i = 21, j = 6] ] -After sorting: [[i = 77, j = 79], [i = 70, j = 7], [i = 66, -j = 54] +After sorting: [[i = 77, j = 79], [i = 70, j = 7], [i = +66, j = 54] , [i = 62, j = 34], [i = 56, j = 68], [i = 50, j = 82] , [i = 48, j = 93], [i = 41, j = 20], [i = 35, j = 37] , [i = 31, j = 67], [i = 21, j = 6], [i = 0, j = 25] diff --git a/arrays/SimpleSetAll.java b/arrays/SimpleSetAll.java index 060a986de..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.*; @@ -7,14 +7,15 @@ class Bob { final int id; - public Bob(int n) { id = n; } - @Override - public String toString() { return "Bob" + id; } + Bob(int n) { id = n; } + @Override public String toString() { + return "Bob" + id; + } } public class SimpleSetAll { public static final int SZ = 8; - public static int val = 1; + static int val = 1; static char[] chars = "abcdefghijklmnopqrstuvwxyz" .toCharArray(); static char getChar(int n) { return chars[n]; } @@ -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 29609b38e..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 @@ -20,20 +20,20 @@ public static void main(String[] args) { } } /* Output: -Before sort: [btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc, -ygpoalk, ljlbynx, taprwxz, bhmupju, cjwzmmr, anmkkyh, -fcjpthl, skddcat, jbvlgwc, mvducuj, ydpulcq, zehpfmm, -zrxmclh, qgekgly, hyoubzl] -After sort: [anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv, -eloztdv, ewcippc, fcjpthl, gmeinne, hyoubzl, jbvlgwc, -ljlbynx, mvducuj, qgekgly, skddcat, taprwxz, ydpulcq, -ygpoalk, zehpfmm, zrxmclh] -Reverse sort: [zrxmclh, zehpfmm, ygpoalk, ydpulcq, taprwxz, -skddcat, qgekgly, mvducuj, ljlbynx, jbvlgwc, hyoubzl, -gmeinne, fcjpthl, ewcippc, eloztdv, cuxszgv, cjwzmmr, -btpenpc, bhmupju, anmkkyh] -Case-insensitive sort: [anmkkyh, bhmupju, btpenpc, cjwzmmr, +Before sort: [btpenpc, cuxszgv, gmeinne, eloztdv, +ewcippc, ygpoalk, ljlbynx, taprwxz, bhmupju, cjwzmmr, +anmkkyh, fcjpthl, skddcat, jbvlgwc, mvducuj, ydpulcq, +zehpfmm, zrxmclh, qgekgly, hyoubzl] +After sort: [anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv, eloztdv, ewcippc, fcjpthl, gmeinne, hyoubzl, jbvlgwc, ljlbynx, mvducuj, qgekgly, skddcat, taprwxz, ydpulcq, ygpoalk, zehpfmm, zrxmclh] +Reverse sort: [zrxmclh, zehpfmm, ygpoalk, ydpulcq, +taprwxz, skddcat, qgekgly, mvducuj, ljlbynx, jbvlgwc, +hyoubzl, gmeinne, fcjpthl, ewcippc, eloztdv, cuxszgv, +cjwzmmr, btpenpc, bhmupju, anmkkyh] +Case-insensitive sort: [anmkkyh, bhmupju, btpenpc, +cjwzmmr, cuxszgv, eloztdv, ewcippc, fcjpthl, gmeinne, +hyoubzl, jbvlgwc, ljlbynx, mvducuj, qgekgly, skddcat, +taprwxz, ydpulcq, ygpoalk, zehpfmm, zrxmclh] */ 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 5b917902a..518a7d5f2 100644 --- a/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy +++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy @@ -9,10 +9,14 @@ import org.apache.tools.ant.util.TeeOutputStream class TaggingPlugin implements Plugin { private final static String DEBUG_PROJECT_PROPERTY_KEY = 'debug' - + void apply(Project project) { - boolean debug = project.hasProperty(DEBUG_PROJECT_PROPERTY_KEY) ? Boolean.valueOf(project.getProperty(DEBUG_PROJECT_PROPERTY_KEY)) : false + boolean debug = project.hasProperty(DEBUG_PROJECT_PROPERTY_KEY) ? Boolean.valueOf(project.getProperty(DEBUG_PROJECT_PROPERTY_KEY)) : false List createdTasks = [] + boolean runningInCI = System.getenv('CI') + boolean runningInTravis = System.getenv('TRAVIS') + boolean runningInAppveyor = System.getenv('APPVEYOR') + // println "runningInCI: " + runningInCI project.projectDir.eachFileRecurse { file -> if (file.name.endsWith('.java')) { @@ -21,7 +25,13 @@ class TaggingPlugin implements Plugin { if(debug && tags.hasTags()) println tags // Exclude java sources that will not compile - if (tags.compileTimeError) { + 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) + || (tags.excludeFromCI && runningInCI) + ) { project.sourceSets.main.java.excludes.add(file.name) } else { JavaExec javaTask = null @@ -49,7 +59,7 @@ class TaggingPlugin implements Plugin { File errFile = new File(file.parentFile, baseName + '.err') javaTask.configure { - ignoreExitValue = tags.validateByHand || tags.throwsException + ignoreExitValue = tags.excludeFromGradle || tags.throwsException doFirst { if(outFile.exists()) outFile.delete() @@ -68,7 +78,7 @@ class TaggingPlugin implements Plugin { } } - if (!tags.validateByHand) { + if (!tags.excludeFromGradle) { // Only add tasks that we know we can run successfully to the task list createdTasks.add(javaTask) } @@ -76,9 +86,9 @@ class TaggingPlugin implements Plugin { } } } - + project.tasks.create('run') { dependsOn createdTasks } } -} \ No newline at end of file +} diff --git a/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy b/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy index 91d7a8b2d..f61ed4d79 100644 --- a/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy +++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy @@ -2,10 +2,15 @@ package com.mindviewinc.plugins class Tags { Boolean hasMainMethod = false - Boolean compileTimeError = false + Boolean willNotCompile = false + Boolean excludeFromTravisCI = false + Boolean excludeFromAppveyorCI = false + Boolean excludeFromCI = false + Boolean lowLevelAppendix = false Boolean throwsException = false Boolean errorOutputExpected = false - Boolean validateByHand = 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 @@ -33,10 +38,15 @@ class Tags { else args << p } - compileTimeError = hasTag('CompileTimeError') + willNotCompile = hasTag('WillNotCompile') + excludeFromTravisCI = hasTag('ExcludeFromTravisCI') + excludeFromAppveyorCI = hasTag('ExcludeFromAppveyorCI') + excludeFromCI = hasTag('ExcludeFromCI') + lowLevelAppendix = firstLine.contains("// lowlevel/") throwsException = hasTag('ThrowsException') errorOutputExpected = hasTag('ErrorOutputExpected') - validateByHand = hasTag('ValidateByHand') + excludeFromGradle = hasTag('ExcludeFromGradle') + newFeature = hasTag('NewFeature') ignoreOutput = hasTag('IgnoreOutput') javap = extract('javap') // Includes only arguments to command runFirst = extract('RunFirst:') @@ -68,10 +78,14 @@ class Tags { } } public boolean hasTags() { - return compileTimeError || + return willNotCompile || + excludeFromTravisCI || + excludeFromAppveyorCI || + excludeFromCI || throwsException || errorOutputExpected || - validateByHand || + excludeFromGradle || + newFeature || ignoreOutput || javaCmd || args || @@ -87,10 +101,14 @@ class Tags { } """ hasMainMethod - compileTimeError + willNotCompile + excludeFromTravisCI + excludeFromAppveyorCI + excludeFromCI throwsException errorOutputExpected - validateByHand + excludeFromGradle + newFeature ignoreOutput fileRoot mainClass @@ -105,4 +123,4 @@ class Tags { } result } -} \ No newline at end of file +} diff --git a/check.bat b/check.bat deleted file mode 100644 index c250560b1..000000000 --- a/check.bat +++ /dev/null @@ -1,2 +0,0 @@ -cp ..\..\OnJava-Tools\verify_output.py . -python verify_output.py diff --git a/checkstyle.xml b/checkstyle.xml index 8731d2620..aabea2c45 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -153,7 +153,8 @@ - + + diff --git a/chkstyle.bat b/chkstyle.bat new file mode 100644 index 000000000..24838fc01 --- /dev/null +++ b/chkstyle.bat @@ -0,0 +1,2 @@ +@echo run gradlew clean first! +gradlew checkstyleMain 1> checkstyleout.txt 2>&1 diff --git a/collections/AdapterMethodIdiom.java b/collections/AdapterMethodIdiom.java index 528cb8292..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 @@ -7,7 +7,7 @@ import java.util.*; class ReversibleArrayList extends ArrayList { - public ReversibleArrayList(Collection c) { + ReversibleArrayList(Collection c) { super(c); } public Iterable reversed() { @@ -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 92103377c..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,14 +24,15 @@ 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 } } } /* Output: ___[ Error Output ]___ -Exception in thread "main" java.lang.ClassCastException: -Orange cannot be cast to Apple - at ApplesAndOrangesWithoutGenerics.main(ApplesAndOr -angesWithoutGenerics.java:23) +Exception in thread "main" +java.lang.ClassCastException: Orange cannot be cast to +Apple + at ApplesAndOrangesWithoutGenerics.main(ApplesA +ndOrangesWithoutGenerics.java:23) */ 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 d5df0f5cd..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.*; @@ -20,23 +20,27 @@ public static void main(String[] args) { HashSet extends Set, adds: [] Interfaces in HashSet: [Set, Cloneable, Serializable] LinkedHashSet extends HashSet, adds: [] -Interfaces in LinkedHashSet: [Set, Cloneable, Serializable] -TreeSet extends Set, adds: [headSet, descendingIterator, -descendingSet, pollLast, subSet, floor, tailSet, ceiling, -last, lower, comparator, pollFirst, first, higher] +Interfaces in LinkedHashSet: [Set, Cloneable, +Serializable] +TreeSet extends Set, adds: [headSet, +descendingIterator, descendingSet, pollLast, subSet, +floor, tailSet, ceiling, last, lower, comparator, +pollFirst, first, higher] Interfaces in TreeSet: [NavigableSet, Cloneable, Serializable] -List extends Collection, adds: [replaceAll, get, indexOf, -subList, set, sort, lastIndexOf, listIterator] +List extends Collection, adds: [replaceAll, get, +indexOf, subList, set, sort, lastIndexOf, listIterator] Interfaces in List: [Collection] -ArrayList extends List, adds: [trimToSize, ensureCapacity] -Interfaces in ArrayList: [List, RandomAccess, Cloneable, -Serializable] -LinkedList extends List, adds: [offerFirst, poll, getLast, -offer, getFirst, removeFirst, element, -removeLastOccurrence, peekFirst, peekLast, push, pollFirst, -removeFirstOccurrence, descendingIterator, pollLast, -removeLast, pop, addLast, peek, offerLast, addFirst] +ArrayList extends List, adds: [trimToSize, +ensureCapacity] +Interfaces in ArrayList: [List, RandomAccess, +Cloneable, Serializable] +LinkedList extends List, adds: [offerFirst, poll, +getLast, offer, getFirst, removeFirst, element, +removeLastOccurrence, peekFirst, peekLast, push, +pollFirst, removeFirstOccurrence, descendingIterator, +pollLast, removeLast, pop, addLast, peek, offerLast, +addFirst] Interfaces in LinkedList: [List, Deque, Cloneable, Serializable] Queue extends Collection, adds: [poll, peek, offer, @@ -44,24 +48,24 @@ public static void main(String[] args) { Interfaces in Queue: [Collection] PriorityQueue extends Queue, adds: [comparator] Interfaces in PriorityQueue: [Serializable] -Map: [clear, compute, computeIfAbsent, computeIfPresent, -containsKey, containsValue, entrySet, equals, forEach, get, -getOrDefault, hashCode, isEmpty, keySet, merge, put, -putAll, putIfAbsent, remove, replace, replaceAll, size, -values] +Map: [clear, compute, computeIfAbsent, +computeIfPresent, containsKey, containsValue, entrySet, +equals, forEach, get, getOrDefault, hashCode, isEmpty, +keySet, merge, put, putAll, putIfAbsent, remove, +replace, replaceAll, size, values] HashMap extends Map, adds: [] Interfaces in HashMap: [Map, Cloneable, Serializable] LinkedHashMap extends HashMap, adds: [] Interfaces in LinkedHashMap: [Map] -SortedMap extends Map, adds: [lastKey, subMap, comparator, -firstKey, headMap, tailMap] +SortedMap extends Map, adds: [lastKey, subMap, +comparator, firstKey, headMap, tailMap] Interfaces in SortedMap: [Map] TreeMap extends Map, adds: [descendingKeySet, -navigableKeySet, higherEntry, higherKey, floorKey, subMap, -ceilingKey, pollLastEntry, firstKey, lowerKey, headMap, -tailMap, lowerEntry, ceilingEntry, descendingMap, -pollFirstEntry, lastKey, firstEntry, floorEntry, -comparator, lastEntry] +navigableKeySet, higherEntry, higherKey, floorKey, +subMap, ceilingKey, pollLastEntry, firstKey, lowerKey, +headMap, tailMap, lowerEntry, ceilingEntry, +descendingMap, pollFirstEntry, lastKey, firstEntry, +floorEntry, comparator, lastEntry] Interfaces in TreeMap: [NavigableMap, Cloneable, Serializable] */ diff --git a/collections/CollectionSequence.java b/collections/CollectionSequence.java index 920017967..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 @@ -33,6 +31,8 @@ public static void main(String[] args) { } } /* Output: -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx */ 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 8966acd10..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); @@ -25,8 +25,12 @@ public static void main(String[] args) { } } /* Output: -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug +0:Rat */ diff --git a/collections/CrossCollectionIteration2.java b/collections/CrossCollectionIteration2.java index 51ca1788e..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); @@ -26,8 +26,12 @@ public static void main(String[] args) { } } /* Output: -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug +0:Rat */ diff --git a/collections/EnvironmentVariables.java b/collections/EnvironmentVariables.java index 4ae2ecaa8..6098e4cfc 100644 --- a/collections/EnvironmentVariables.java +++ b/collections/EnvironmentVariables.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {VisuallyInspectOutput} import java.util.*; public class EnvironmentVariables { 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 797f40d55..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@1db9742 -Gala@106d69c -Fuji@52e922 -Braeburn@25154f +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 8948aa80a..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, " + @@ -37,13 +37,19 @@ public static void main(String[] args) { } } /* Output: -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx {Ralph=Rat, Eric=Manx, Robin=Cymric, Lacey=Mutt, Britney=Pug, Sam=Cymric, Spot=Pug, Fluffy=Manx} [Ralph, Eric, Robin, Lacey, Britney, Sam, Spot, Fluffy] -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx */ diff --git a/collections/IterableClass.java b/collections/IterableClass.java index c9eedf57c..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 @@ -7,13 +7,12 @@ 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() { + "we know the Earth to be banana-shaped." + ).split(" "); + @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 3925e4a1b..4967f5260 100644 --- a/collections/ListIteration.java +++ b/collections/ListIteration.java @@ -1,16 +1,17 @@ // 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() + ", " + it.nextIndex() + + System.out.print(it.next() + + ", " + it.nextIndex() + ", " + it.previousIndex() + "; "); System.out.println(); // Backwards: @@ -21,16 +22,15 @@ 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); } } /* Output: -Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; -Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7; +Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, +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 151d4e1e4..d7357a6ed 100644 --- a/collections/MapOfList.java +++ b/collections/MapOfList.java @@ -1,14 +1,14 @@ // 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 { - public static Map> + public static final Map> petPeople = new HashMap<>(); static { petPeople.put(new Person("Dawn"), @@ -21,10 +21,11 @@ public class MapOfList { petPeople.put(new Person("Marilyn"), Arrays.asList( new Pug("Louie aka Louis Snorkelstein Dupree"), - new Cat("Stanford aka Stinky el Negro"), + new Cat("Stanford"), new Cat("Pinkola"))); petPeople.put(new Person("Luke"), - Arrays.asList(new Rat("Fuzzy"), new Rat("Fizzy"))); + Arrays.asList( + new Rat("Fuzzy"), new Rat("Fizzy"))); petPeople.put(new Person("Isaac"), Arrays.asList(new Rat("Freckly"))); } @@ -39,26 +40,26 @@ public static void main(String[] args) { } } /* Output: -People: [Person Marilyn, Person Dawn, Person Luke, Person -Isaac, Person Kate] -Pets: [[Pug Louie aka Louis Snorkelstein Dupree, Cat -Stanford aka Stinky el Negro, Cat Pinkola], [Cymric Molly, -Mutt Spot], [Rat Fuzzy, Rat Fizzy], [Rat Freckly], [Cat -Shackleton, Cat Elsie May, Dog Margrett]] -Person Marilyn has: - Pug Louie aka Louis Snorkelstein Dupree - Cat Stanford aka Stinky el Negro - Cat Pinkola +People: [Person Dawn, Person Kate, Person Isaac, Person +Marilyn, Person Luke] +Pets: [[Cymric Molly, Mutt Spot], [Cat Shackleton, Cat +Elsie May, Dog Margrett], [Rat Freckly], [Pug Louie aka +Louis Snorkelstein Dupree, Cat Stanford, Cat Pinkola], +[Rat Fuzzy, Rat Fizzy]] Person Dawn has: Cymric Molly Mutt Spot -Person Luke has: - Rat Fuzzy - Rat Fizzy -Person Isaac has: - Rat Freckly Person Kate has: Cat Shackleton Cat Elsie May Dog Margrett +Person Isaac has: + Rat Freckly +Person Marilyn has: + Pug Louie aka Louis Snorkelstein Dupree + Cat Stanford + Cat Pinkola +Person Luke has: + Rat Fuzzy + Rat Fizzy */ 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 af13bc25e..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 @@ -32,5 +31,6 @@ public static void main(String[] args) { } } /* Output: -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx */ 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 68029ba9d..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 { @@ -19,8 +19,8 @@ public static void main(String[] args) { } } /* Output: -{My Dog=Dog Ginger, My Cat=Cat Molly, My Hamster=Hamster -Bosco} +{My Dog=Dog Ginger, My Cat=Cat Molly, My +Hamster=Hamster Bosco} Dog Ginger true true 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 5ca4096e2..c324722a9 100644 --- a/collections/PrintingCollections.java +++ b/collections/PrintingCollections.java @@ -1,12 +1,13 @@ // 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 import java.util.*; public class PrintingCollections { - static Collection fill(Collection collection) { + static Collection + fill(Collection collection) { collection.add("rat"); collection.add("cat"); collection.add("dog"); diff --git a/collections/PriorityQueueDemo.java b/collections/PriorityQueueDemo.java index 62136ddb4..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.*; @@ -23,7 +23,8 @@ public static void main(String[] args) { QueueDemo.printQ(priorityQueue); String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION"; - List strings = Arrays.asList(fact.split("")); + List strings = + Arrays.asList(fact.split("")); PriorityQueue stringPQ = new PriorityQueue<>(strings); QueueDemo.printQ(stringPQ); @@ -44,9 +45,9 @@ public static void main(String[] args) { 0 1 1 1 1 1 3 5 8 14 1 1 2 3 3 9 9 14 14 18 18 20 21 22 23 25 25 25 25 23 22 21 20 18 18 14 14 9 9 3 3 2 1 1 - A A B C C C D D E E E F H H I I L N N O O O O S S S T -T U U U W -W U U U T T S S S O O O O N N L I I H H F E E E D D C C C B -A A + A A B C C C D D E E E F H H I I L N N O O O O S S +S T T U U U W +W U U U T T S S S O O O O N N L I I H H F E E E D D C C +C B A A A B C D E F H I L N O S T U W */ 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 0c332198f..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.*; @@ -14,6 +14,6 @@ public static void main(String[] args) { } } /* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] */ 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 e85bbf705..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.*; @@ -24,7 +24,8 @@ public static void main(String[] args) { System.out.println( "set2 removed from set1: " + set1); Collections.addAll(set1, "X Y Z".split(" ")); - System.out.println("'X Y Z' added to set1: " + set1); + System.out.println( + "'X Y Z' added to set1: " + set1); } } /* Output: @@ -34,5 +35,6 @@ public static void main(String[] args) { set1: [A, B, C, D, E, F, G, I, J, K, L, M] set2 in set1: false set2 removed from set1: [A, B, C, D, E, F, G, M] -'X Y Z' added to set1: [A, B, C, D, E, F, G, M, X, Y, Z] +'X Y Z' added to set1: [A, B, C, D, E, F, G, M, X, Y, +Z] */ 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 3c1149545..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(); @@ -28,9 +28,9 @@ public static void main(String[] args) { } } /* Output: -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -8:Cymric 9:Rat 10:EgyptianMau 11:Hamster -0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -8:Cymric 9:Rat 10:EgyptianMau 11:Hamster +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug +7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster [Pug, Manx, Cymric, Rat, EgyptianMau, Hamster] */ 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 f2a51aaca..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,14 +12,14 @@ 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); } } /* Output: -{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, 7=471, -8=468, 9=549, 10=513, 11=531, 12=521, 13=506, 14=477, -15=497, 16=533, 17=509, 18=478, 19=464} +{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, +7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506, +14=477, 15=497, 16=533, 17=509, 18=478, 19=464} */ diff --git a/collections/UniqueWords.java b/collections/UniqueWords.java index 229499773..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.*; @@ -8,8 +8,8 @@ public class UniqueWords { public static void main(String[] args) throws Exception { - List lines = - Files.readAllLines(Paths.get("SetOperations.java")); + List lines = Files.readAllLines( + Paths.get("SetOperations.java")); Set words = new TreeSet<>(); for(String line : lines) for(String word : line.split("\\W+")) @@ -19,10 +19,11 @@ public class UniqueWords { } } /* Output: -[A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K, L, -M, N, Output, Set, SetOperations, String, System, X, Y, Z, -add, addAll, added, args, class, collections, contains, -containsAll, false, from, import, in, java, main, new, out, -println, public, remove, removeAll, removed, set1, set2, -split, static, to, true, util, void] +[A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K, +L, M, N, Output, Set, SetOperations, String, System, X, +Y, Z, add, addAll, added, args, class, collections, +contains, containsAll, false, from, import, in, java, +main, new, out, println, public, remove, removeAll, +removed, set1, set2, split, static, to, true, util, +void] */ diff --git a/collections/UniqueWordsAlphabetic.java b/collections/UniqueWordsAlphabetic.java index b6b1c1cc9..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 @@ -9,8 +9,8 @@ public class UniqueWordsAlphabetic { public static void main(String[] args) throws Exception { - List lines = - Files.readAllLines(Paths.get("SetOperations.java")); + List lines = Files.readAllLines( + Paths.get("SetOperations.java")); Set words = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for(String line : lines) @@ -22,9 +22,9 @@ public class UniqueWordsAlphabetic { } /* Output: [A, add, addAll, added, args, B, C, class, collections, -contains, containsAll, D, E, F, false, from, G, H, HashSet, -I, import, in, J, java, K, L, M, main, N, new, out, Output, -println, public, remove, removeAll, removed, Set, set1, -set2, SetOperations, split, static, String, System, to, -true, util, void, X, Y, Z] +contains, containsAll, D, E, F, false, from, G, H, +HashSet, I, import, in, J, java, K, L, M, main, N, new, +out, Output, println, public, remove, removeAll, +removed, Set, set1, set2, SetOperations, split, static, +String, System, to, true, util, void, X, Y, Z] */ 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 3235ae390..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 @@ -60,19 +60,19 @@ public static void main(String[] args) { } } /* Output: -byte value: 118 -bits: {1, 2, 4, 5, 6} -bit pattern: 0110111000000000000000000000000000000000000000 -000000000000000000 -short value: 9795 -bits: {0, 1, 6, 9, 10, 13} -bit pattern: 1100001001100100000000000000000000000000000000 -000000000000000000 -int value: -645079414 -bits: {1, 3, 7, 9, 10, 11, 12, 14, 15, 18, 19, 23, 24, 27, -28, 30, 31} -bit pattern: 0101000101111011001100011001101100000000000000 -000000000000000000 +byte value: -107 +bits: {0, 2, 4, 7} +bit pattern: 101010010000000000000000000000000000000000 +0000000000000000000000 +short value: 1302 +bits: {1, 2, 4, 8, 10} +bit pattern: 011010001010000000000000000000000000000000 +0000000000000000000000 +int value: -2014573909 +bits: {0, 1, 3, 5, 7, 9, 11, 18, 19, 21, 22, 23, 24, +25, 26, 31} +bit pattern: 110101010101000000110111111000010000000000 +0000000000000000000000 set bit 127: {127} set bit 255: {255} set bit 1023: {1023, 1024} diff --git a/collectiontopics/CanonicalMapping.java b/collectiontopics/CanonicalMapping.java index f81d0bb83..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; - public 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 { - public Key(String id) { super(id); } -} - -class Value extends Element { - public 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 = new Integer(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 6c6ae7f15..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()); @@ -79,10 +78,10 @@ public static void main(String[] args) { Azure ten eleven ------------------------------- +****************************** Collections.max(c) = ten Collections.min(c) = AliceBlue ------------------------------- +****************************** AliceBlue AntiqueWhite Aquamarine @@ -93,7 +92,7 @@ public static void main(String[] args) { BurlyWood CadetBlue Chartreuse ------------------------------- +****************************** AntiqueWhite Aquamarine Azure @@ -103,13 +102,13 @@ public static void main(String[] args) { BurlyWood CadetBlue Chartreuse ------------------------------- +****************************** AntiqueWhite Aquamarine Azure ten eleven ------------------------------- +****************************** AntiqueWhite Aquamarine Azure @@ -119,11 +118,11 @@ public static void main(String[] args) { BurlyWood CadetBlue Chartreuse ------------------------------- +****************************** c.contains(Azure) = true c.containsAll(c2) = true c2.isEmpty() = true ------------------------------- +****************************** PapayaWhip PeachPuff Peru diff --git a/collectiontopics/Enumerations.java b/collectiontopics/Enumerations.java index 1d846645f..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 @@ -18,6 +18,7 @@ public static void main(String[] args) { } } /* Output: -ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, -CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, CHAD, +ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN +REPUBLIC, CHAD, */ 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 e7f1d3c49..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.*; @@ -23,7 +23,10 @@ public static void main(String[] args) { } } /* Output: -{npcc=1, ztdv=6, gvgm=3, btpe=0, einn=4, eelo=5, uxsz=2} -{npcc=1, ztdv=6, gvgm=3, btpe=0, einn=4, eelo=5, uxsz=2} -{btpe=0, npcc=1, uxsz=2, gvgm=3, einn=4, eelo=5, ztdv=6} +{npcc=1, ztdv=6, gvgm=3, btpe=0, einn=4, eelo=5, +uxsz=2} +{npcc=1, ztdv=6, gvgm=3, btpe=0, einn=4, eelo=5, +uxsz=2} +{btpe=0, npcc=1, uxsz=2, gvgm=3, einn=4, eelo=5, +ztdv=6} */ diff --git a/collectiontopics/FillingLists.java b/collectiontopics/FillingLists.java index f8fe104e2..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() @@ -7,9 +7,8 @@ class StringAddress { private String s; - public StringAddress(String s) { this.s = s; } - @Override - public String toString() { + StringAddress(String s) { this.s = s; } + @Override public String toString() { return super.toString() + " " + s; } } @@ -26,9 +25,10 @@ public static void main(String[] args) { } } /* Output: -[StringAddress@1db9742 Hello, StringAddress@1db9742 Hello, -StringAddress@1db9742 Hello, StringAddress@1db9742 Hello] -[StringAddress@106d69c World!, StringAddress@106d69c -World!, StringAddress@106d69c World!, StringAddress@106d69c -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 47418db07..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.*; @@ -37,7 +37,7 @@ public static void main(String[] args) { 0xFFF8DC: Cornsilk 0xDC143C: Crimson 0x00FFFF: Cyan ------------------------------- +****************************** AliceBlue 0xF0F8FF AntiqueWhite 0xFAEBD7 Aquamarine 0x7FFFD4 @@ -58,7 +58,7 @@ public static void main(String[] args) { Cornsilk 0xFFF8DC Crimson 0xDC143C Cyan 0x00FFFF ------------------------------- +****************************** AliceBlue AntiqueWhite Aquamarine @@ -79,7 +79,7 @@ public static void main(String[] args) { Cornsilk Crimson Cyan ------------------------------- +****************************** 0xF0F8FF 0xFAEBD7 0x7FFFD4 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 72ecf8ab9..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 @@ -32,7 +32,7 @@ public static void basicTest(List a) { b = a.isEmpty(); // Any elements inside? it = a.iterator(); // Ordinary Iterator lit = a.listIterator(); // ListIterator - lit = a.listIterator(3); // Start at loc 3 + lit = a.listIterator(3); // Start at location 3 i = a.lastIndexOf("1"); // Last match a.remove(1); // Remove location 1 a.remove("3"); // Remove this object @@ -123,4 +123,45 @@ public static void main(String[] args) { } } /* Output: +[AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet] +b = [AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet] +[AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet, +AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet, +AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet] +[AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet, +AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, one, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet, +AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet] +Bisque +Black +[AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet, +AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, one, +47, BlanchedAlmond, Blue, BlueViolet, AliceBlue, +AntiqueWhite, Aquamarine, Azure, Beige, Bisque, Black, +BlanchedAlmond, Blue, BlueViolet] +BlueViolet Blue BlanchedAlmond Black Bisque Beige Azure +Aquamarine AntiqueWhite AliceBlue BlueViolet Blue +BlanchedAlmond 47 one Beige Azure Aquamarine +AntiqueWhite AliceBlue BlueViolet Blue BlanchedAlmond +Black Bisque Beige Azure Aquamarine AntiqueWhite +AliceBlue +testVisual finished +[AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue, BlueViolet] +[two, one, AliceBlue, AntiqueWhite, Aquamarine, Azure, +Beige, Bisque, Black, BlanchedAlmond, Blue, BlueViolet] +two +two +one +BlueViolet +[AliceBlue, AntiqueWhite, Aquamarine, Azure, Beige, +Bisque, Black, BlanchedAlmond, Blue] */ diff --git a/collectiontopics/ListSortSearch.java b/collectiontopics/ListSortSearch.java index 77400b176..2f2ca2d7e 100644 --- a/collectiontopics/ListSortSearch.java +++ b/collectiontopics/ListSortSearch.java @@ -1,8 +1,8 @@ // 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 and searching Lists with Collections utilities +// Sorting/searching Lists with Collections utilities import java.util.*; public class ListSortSearch { @@ -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(); } @@ -42,16 +42,16 @@ public static void main(String[] args) { } } /* Output: -[one, Two, three, Four, five, six, one, one, Two, three, -Four, five, six, one] +[one, Two, three, Four, five, six, one, one, Two, +three, Four, five, six, one] Shuffled: [Four, five, one, one, Two, six, six, three, three, five, Four, Two, one, one] Trimmed: [Four, five, one, one, Two, six, six, three, three, five] -Sorted: [Four, Two, five, five, one, one, six, six, three, -three] +Sorted: [Four, Two, five, five, one, one, six, six, +three, three] Location of six is 7, list.get(7) = six -Case-insensitive sorted: [five, five, Four, one, one, six, -six, three, three, Two] +Case-insensitive sorted: [five, five, Four, one, one, +six, six, three, three, Two] Location of three is 7, list.get(7) = three */ diff --git a/collectiontopics/MapOps.java b/collectiontopics/MapOps.java index 9956f80f6..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 @@ -8,7 +8,8 @@ import onjava.*; public class MapOps { - public static void printKeys(Map map) { + public static + void printKeys(Map map) { System.out.print("Size = " + map.size() + ", "); System.out.print("Keys: "); // Produce a Set of the keys: @@ -56,10 +57,10 @@ public static void main(String[] args) { } /* Output: (First 11 Lines) HashMap -Size = 25, Keys: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] -Values: [A0, B0, C0, D0, E0, F0, G0, H0, I0, J0, K0, L0, -M0, N0, O0, P0, Q0, R0, S0, T0, U0, V0, W0, X0, Y0] +Size = 25, Keys: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, +12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] +Values: [A0, B0, C0, D0, E0, F0, G0, H0, I0, J0, K0, +L0, M0, N0, O0, P0, Q0, R0, S0, T0, U0, V0, W0, X0, Y0] {0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0, 10=K0, 11=L0, 12=M0, 13=N0, 14=O0, 15=P0, 16=Q0, 17=R0, 18=S0, 19=T0, 20=U0, 21=V0, 22=W0, 23=X0, 24=Y0} @@ -67,8 +68,8 @@ public static void main(String[] args) { map.get(11): L0 map.containsValue("F0"): true First key in map: 0 -Size = 24, Keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] +Size = 24, Keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, +12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] map.isEmpty(): true map.isEmpty(): true ... diff --git a/collectiontopics/NavMap.java b/collectiontopics/NavMap.java index 92e4ef198..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 @@ -35,9 +35,9 @@ public static void main(String[] args) { } /* Output: 0x000000: Black ------------------------------- +****************************** 0xFFFFFF: White ------------------------------- +****************************** 0x000000: Black 0x000080: Navy 0x00008B: DarkBlue @@ -51,11 +51,11 @@ public static void main(String[] args) { 0x00CED1: DarkTurquoise 0x00FA9A: MediumSpringGreen 0x00FF00: Lime ------------------------------- +****************************** 0x00BFFF: DeepSkyBlue ------------------------------- +****************************** 0x008B8B: DarkCyan ------------------------------- +****************************** 0x00FF00: Lime 0x00FA9A: MediumSpringGreen 0x00CED1: DarkTurquoise @@ -69,7 +69,7 @@ public static void main(String[] args) { 0x00008B: DarkBlue 0x000080: Navy 0x000000: Black ------------------------------- +****************************** 0xFFE4E1: MistyRose 0xFFEBCD: BlanchedAlmond 0xFFEFD5: PapayaWhip @@ -83,7 +83,7 @@ public static void main(String[] args) { 0xFFFFE0: LightYellow 0xFFFFF0: Ivory 0xFFFFFF: White ------------------------------- +****************************** 0xDA70D6: Orchid 0xDAA520: GoldenRod 0xDB7093: PaleVioletRed 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 8339bd52f..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 @@ -45,9 +45,11 @@ public static void main(String[] args) { } } /* Output: -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI] ALGERIA -[BENIN, BOTSWANA, ANGOLA, BURKINA FASO, ALGERIA, BURUNDI] +[BENIN, BOTSWANA, ANGOLA, BURKINA FASO, ALGERIA, +BURUNDI] {BENIN=Porto-Novo, BOTSWANA=Gaberone, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ALGERIA=Algiers, BURUNDI=Bujumbura} diff --git a/collectiontopics/References.java b/collectiontopics/References.java index 68e9ec52a..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 @@ -10,11 +10,10 @@ class VeryBig { private static final int SIZE = 10000; private long[] la = new long[SIZE]; private String ident; - public VeryBig(String id) { ident = id; } - @Override - public String toString() { return ident; } - @Override - protected void finalize() { + VeryBig(String id) { ident = id; } + @Override public String toString() { return ident; } + @SuppressWarnings("deprecation") + @Override protected void finalize() { System.out.println("Finalizing " + ident); } } @@ -31,7 +30,7 @@ public static void main(String[] args) { int size = 10; // Or, choose size via the command line: if(args.length > 0) - size = new Integer(args[0]); + size = Integer.valueOf(args[0]); LinkedList> sa = new LinkedList<>(); for(int i = 0; i < size; i++) { @@ -67,6 +66,8 @@ public static void main(String[] args) { } } /* Output: (First and Last 10 Lines) +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 @@ -75,17 +76,15 @@ public static void main(String[] args) { 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.SoftReference@14eac69 -Just created: java.lang.ref.SoftReference@a57993 ...________...________...________...________... +Just created: java.lang.ref.PhantomReference@16f6e28 +In queue: null +Just created: java.lang.ref.PhantomReference@15fbaa4 +In queue: null Just created: java.lang.ref.PhantomReference@1ee12a7 In queue: null Just created: java.lang.ref.PhantomReference@10bedb4 In queue: null Just created: java.lang.ref.PhantomReference@103dbd3 In queue: null -Just created: java.lang.ref.PhantomReference@167cf4d -In queue: null -Just created: java.lang.ref.PhantomReference@a987ac -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 1600178e9..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 @@ -9,10 +9,9 @@ class CountString implements Supplier { private int n = 0; - public CountString() {} - public CountString(int start) { n = start; } - @Override - public String get() { + CountString() {} + CountString(int start) { n = start; } + @Override public String get() { return Integer.toString(n++); } } @@ -49,11 +48,13 @@ public static void main(String[] args) { } /* Output: LinkedList -[7, 6, 5, 4, 3, 2, 1, 0, 20, 21, 22, 23, 24, 25, 26, 27] +[7, 6, 5, 4, 3, 2, 1, 0, 20, 21, 22, 23, 24, 25, 26, +27] 7 27 6 26 5 25 4 24 3 23 2 22 1 21 0 20 7 27 6 26 5 25 4 24 3 23 2 22 1 21 0 20 ArrayDeque -[7, 6, 5, 4, 3, 2, 1, 0, 20, 21, 22, 23, 24, 25, 26, 27] +[7, 6, 5, 4, 3, 2, 1, 0, 20, 21, 22, 23, 24, 25, 26, +27] 7 27 6 26 5 25 4 24 3 23 2 22 1 21 0 20 7 27 6 26 5 25 4 24 3 23 2 22 1 21 0 20 LinkedBlockingDeque @@ -61,7 +62,8 @@ public static void main(String[] args) { 4 24 3 23 2 22 1 21 0 20 4 24 3 23 2 22 1 21 0 20 ConcurrentLinkedDeque -[7, 6, 5, 4, 3, 2, 1, 0, 20, 21, 22, 23, 24, 25, 26, 27] +[7, 6, 5, 4, 3, 2, 1, 0, 20, 21, 22, 23, 24, 25, 26, +27] 7 27 6 26 5 25 4 24 3 23 2 22 1 21 0 20 7 27 6 26 5 25 4 24 3 23 2 22 1 21 0 20 */ 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 053b5d3c1..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 @@ -44,17 +44,18 @@ public static void main(String[] args) { } } /* Output: -stack = [JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, -AUGUST, SEPTEMBER, OCTOBER, NOVEMBER] +stack = [JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, +JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER] element 5 = JUNE popping elements: -The last line NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE -MAY APRIL MARCH FEBRUARY JANUARY lstack = [NOVEMBER, -OCTOBER, SEPTEMBER, AUGUST, JULY, JUNE, MAY, APRIL, MARCH, +The last line NOVEMBER OCTOBER SEPTEMBER AUGUST JULY +JUNE MAY APRIL MARCH FEBRUARY JANUARY lstack = +[NOVEMBER, OCTOBER, SEPTEMBER, AUGUST, JULY, JUNE, MAY, +APRIL, MARCH, FEBRUARY, JANUARY] +NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE MAY APRIL +MARCH FEBRUARY JANUARY stack2 = [NOVEMBER, OCTOBER, +SEPTEMBER, AUGUST, JULY, JUNE, MAY, APRIL, MARCH, FEBRUARY, JANUARY] -NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE MAY APRIL MARCH -FEBRUARY JANUARY stack2 = [NOVEMBER, OCTOBER, SEPTEMBER, -AUGUST, JULY, JUNE, MAY, APRIL, MARCH, FEBRUARY, JANUARY] -NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE MAY APRIL MARCH -FEBRUARY JANUARY +NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE MAY APRIL +MARCH FEBRUARY JANUARY */ diff --git a/collectiontopics/StreamFillMaps.java b/collectiontopics/StreamFillMaps.java index 83295aa09..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++); } } @@ -46,7 +45,10 @@ public static void main(String[] args) { } } /* Output: -{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, 11=K} -{b=btp, c=enp, d=ccu, e=xsz, f=gvg, g=mei, h=nne, i=elo} -{p=Val, q=Val, j=Val, k=Val, l=Val, m=Val, n=Val, o=Val} +{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, +11=K} +{b=btp, c=enp, d=ccu, e=xsz, f=gvg, g=mei, h=nne, +i=elo} +{p=Val, q=Val, j=Val, k=Val, l=Val, m=Val, n=Val, +o=Val} */ diff --git a/collectiontopics/SuppliersCollectionTest.java b/collectiontopics/SuppliersCollectionTest.java index 22b2661c2..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++]; } } @@ -50,18 +49,18 @@ public static void main(String[] args) { } } /* Output: -[strange, women, lying, in, ponds, distributing, swords, -is, no, basis, for, a, system, of, government] -[strange, women, lying, in, ponds, distributing, swords, -is, no, basis, for, a, system, of, government] -[strange, women, lying, in, ponds, distributing, swords, -is, no, basis, for, a, system, of, government] -[ponds, no, a, in, swords, for, is, basis, strange, system, -government, distributing, of, women, lying] -[strange, women, lying, in, ponds, distributing, swords, -is, no, basis, for, a, system, of, government] -[strange, women, lying, in, ponds, distributing, swords, -is, no, basis, for, a, system, of, government] -[strange, women, lying, in, ponds, distributing, swords, -is, no, basis, for, a, system, of, government] +[strange, women, lying, in, ponds, distributing, +swords, is, no, basis, for, a, system, of, government] +[strange, women, lying, in, ponds, distributing, +swords, is, no, basis, for, a, system, of, government] +[strange, women, lying, in, ponds, distributing, +swords, is, no, basis, for, a, system, of, government] +[ponds, no, a, in, swords, for, is, basis, strange, +system, government, distributing, of, women, lying] +[strange, women, lying, in, ponds, distributing, +swords, is, no, basis, for, a, system, of, government] +[strange, women, lying, in, ponds, distributing, +swords, is, no, basis, for, a, system, of, government] +[strange, women, lying, in, ponds, distributing, +swords, is, no, basis, for, a, system, of, government] */ 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 8b5cb8564..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 @@ -9,13 +9,12 @@ class ToDoItem implements Comparable { private char primary; private int secondary; private String item; - public ToDoItem(String td, char pri, int sec) { + ToDoItem(String td, char pri, int sec) { primary = pri; 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 cd672c9d6..e4c745879 100644 --- a/collectiontopics/TypesForSets.java +++ b/collectiontopics/TypesForSets.java @@ -1,40 +1,35 @@ // 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 import java.util.*; import java.util.function.*; import java.util.Objects; -import onjava.CountMap; class SetType { protected int i; - public SetType(int n) { i = n; } - @Override - public boolean equals(Object o) { + SetType(int n) { i = n; } + @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 { - public HashType(int n) { super(n); } - @Override - public int hashCode() { + HashType(int n) { super(n); } + @Override public int hashCode() { return Objects.hashCode(i); } } class TreeType extends SetType implements Comparable { - public TreeType(int n) { super(n); } - @Override - public int compareTo(TreeType arg) { + TreeType(int n) { super(n); } + @Override public int compareTo(TreeType arg) { return Integer.compare(arg.i, i); // Equivalent to: // return arg.i < i ? -1 : (arg.i == i ? 0 : 1); @@ -81,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 0e718671b..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 @@ -31,8 +31,8 @@ static void test(String msg, List list) { check("List.set", () -> list.set(0, "X")); } public static void main(String[] args) { - List list = - Arrays.asList("A B C D E F G H I J K L".split(" ")); + List list = Arrays.asList( + "A B C D E F G H I J K L".split(" ")); test("Modifiable Copy", new ArrayList<>(list)); test("Arrays.asList()", list); test("unmodifiableList()", 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 77cf590d6..1b847c57b 100644 --- a/compression/GZIPcompress.java +++ b/compression/GZIPcompress.java @@ -1,9 +1,9 @@ // 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} -// {ValidateByHand} +// {VisuallyInspectOutput} import java.util.zip.*; import java.io.*; diff --git a/compression/ZipCompress.java b/compression/ZipCompress.java index 7ac5dc985..532316029 100644 --- a/compression/ZipCompress.java +++ b/compression/ZipCompress.java @@ -1,11 +1,11 @@ // 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 // number of files given on the command line // {java ZipCompress ZipCompress.java} -// {ValidateByHand} +// {VisuallyInspectOutput} import java.util.zip.*; import java.io.*; import java.util.*; 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 5cf7fb009..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[2] pool-1-thread-3 -NapTask[9] pool-1-thread-10 -NapTask[6] pool-1-thread-7 +NapTask[1] pool-1-thread-2 NapTask[5] pool-1-thread-6 -NapTask[7] pool-1-thread-8 +NapTask[4] pool-1-thread-5 NapTask[8] pool-1-thread-9 NapTask[0] pool-1-thread-1 -NapTask[1] pool-1-thread-2 -NapTask[4] pool-1-thread-5 +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[7] pool-1-thread-8 */ diff --git a/concurrent/CachedThreadPool2.java b/concurrent/CachedThreadPool2.java index 52ba937d8..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 -4 pool-1-thread-5 300 -3 pool-1-thread-4 400 -1 pool-1-thread-2 200 +3 pool-1-thread-4 100 2 pool-1-thread-3 200 -6 pool-1-thread-7 500 -8 pool-1-thread-9 757 -5 pool-1-thread-6 657 -7 pool-1-thread-8 657 -9 pool-1-thread-10 857 +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 cc17e424c..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: +0 pool-1-thread-1 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 -5 pool-1-thread-6 100 7 pool-1-thread-8 100 4 pool-1-thread-5 100 -9 pool-1-thread-10 100 -3 pool-1-thread-4 100 -0 pool-1-thread-1 100 -1 pool-1-thread-2 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 f0e39d89a..5c9bcd610 100644 --- a/concurrent/CatchCompletableExceptions.java +++ b/concurrent/CatchCompletableExceptions.java @@ -1,9 +1,8 @@ // 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.*; -import onjava.Nap; public class CatchCompletableExceptions { static void handleException(int failcount) { @@ -53,11 +52,14 @@ public static void main(String[] args) { /* Output: **** Failure Mode **** Breakable_exceptionally [1] +Throwing Exception for exceptionally result: Breakable_java.lang.RuntimeException: Breakable_exceptionally failed [0] Breakable_handle [1] +Throwing Exception for handle result: Failure recovery object Breakable_whenComplete [1] +Throwing Exception for whenComplete It failed **** Success Mode **** Breakable_exceptionally [-1] 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 fd73a940e..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: -50 +103 Machina0: ONE Machina0: TWO Machina0: THREE Machina0: complete Machina0: complete -462 +545 */ diff --git a/concurrent/CompletableApplyChained.java b/concurrent/CompletableApplyChained.java index 2834e2a84..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 -460 +521 */ diff --git a/concurrent/CompletableExceptions.java b/concurrent/CompletableExceptions.java index b035c5cf3..341a0afc6 100644 --- a/concurrent/CompletableExceptions.java +++ b/concurrent/CompletableExceptions.java @@ -1,9 +1,8 @@ // 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.*; -import onjava.Nap; public class CompletableExceptions { static CompletableFuture diff --git a/concurrent/CompletableOperations.java b/concurrent/CompletableOperations.java index 3d3e3f487..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.*; @@ -9,7 +9,7 @@ public class CompletableOperations { static CompletableFuture cfi(int i) { return CompletableFuture.completedFuture( - new Integer(i)); + Integer.valueOf(i)); } public static void main(String[] args) { showr(cfi(1)); // Basic test @@ -55,6 +55,7 @@ public static void main(String[] args) { 1 runAsync thenRunAsync +runAsync is static 99 thenAcceptAsync: 4 47 @@ -65,8 +66,8 @@ public static void main(String[] args) { cancelled: true completed exceptionally: true done: true -java.util.concurrent.CompletableFuture@404b9385[Completed -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 6072e81a2..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.*; @@ -8,7 +8,7 @@ import onjava.Timer; public class CompletablePizza { - static int QUANTITY = 5; + static final int QUANTITY = 5; public static CompletableFuture makeCF(Pizza za) { return CompletableFuture @@ -42,46 +42,46 @@ public static void main(String[] args) { } } /* Output: -56 -Pizza 0: ROLLED +98 Pizza 1: ROLLED +Pizza 3: ROLLED Pizza 4: ROLLED Pizza 2: ROLLED -Pizza 3: ROLLED -Pizza 0: SAUCED -Pizza 3: SAUCED +Pizza 0: ROLLED +Pizza 1: SAUCED Pizza 2: SAUCED +Pizza 3: SAUCED +Pizza 0: SAUCED Pizza 4: SAUCED -Pizza 1: SAUCED -Pizza 0: CHEESED -Pizza 4: CHEESED Pizza 2: CHEESED +Pizza 0: CHEESED Pizza 3: CHEESED Pizza 1: CHEESED -Pizza 0: TOPPED +Pizza 4: CHEESED +Pizza 2: TOPPED Pizza 4: TOPPED Pizza 1: TOPPED Pizza 3: TOPPED -Pizza 2: TOPPED +Pizza 0: TOPPED Pizza 0: BAKED Pizza 4: BAKED -Pizza 3: BAKED Pizza 1: BAKED +Pizza 3: BAKED Pizza 2: BAKED -Pizza 0: SLICED +Pizza 3: SLICED +Pizza 1: SLICED Pizza 2: SLICED Pizza 4: SLICED -Pizza 1: SLICED -Pizza 3: SLICED +Pizza 0: SLICED Pizza 0: BOXED -Pizza0: complete -Pizza 4: BOXED -Pizza 3: BOXED Pizza 2: BOXED +Pizza 4: BOXED Pizza 1: BOXED +Pizza0: complete Pizza1: complete Pizza2: complete +Pizza 3: BOXED Pizza3: complete Pizza4: complete -1659 +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 0ab94d45c..47a1a77fb 100644 --- a/concurrent/CountingStream.java +++ b/concurrent/CountingStream.java @@ -1,7 +1,8 @@ // 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} import java.util.*; import java.util.concurrent.*; import java.util.stream.*; @@ -17,15 +18,15 @@ public static void main(String[] args) { } } /* Output: -4 ForkJoinPool.commonPool-worker-5 100 -2 ForkJoinPool.commonPool-worker-1 100 -6 main 100 -5 ForkJoinPool.commonPool-worker-1 100 -7 ForkJoinPool.commonPool-worker-4 100 1 ForkJoinPool.commonPool-worker-3 100 8 ForkJoinPool.commonPool-worker-2 100 0 ForkJoinPool.commonPool-worker-6 100 +2 ForkJoinPool.commonPool-worker-1 100 +4 ForkJoinPool.commonPool-worker-5 100 9 ForkJoinPool.commonPool-worker-7 100 -3 ForkJoinPool.commonPool-worker-5 100 +6 main 100 +7 ForkJoinPool.commonPool-worker-4 100 +5 ForkJoinPool.commonPool-worker-2 100 +3 ForkJoinPool.commonPool-worker-3 100 1000 */ diff --git a/concurrent/CountingTask.java b/concurrent/CountingTask.java index ddcbacf19..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,9 +7,8 @@ public class CountingTask implements Callable { final int id; public CountingTask(int id) { this.id = id; } - @Override - public Integer call() { - Integer val = new Integer(0); + @Override public Integer call() { + Integer val = 0; for(int i = 0; i < 100; i++) val++; System.out.println(id + " " + diff --git a/concurrent/DiningPhilosophers.java b/concurrent/DiningPhilosophers.java index 13d08aca0..8b54820a1 100644 --- a/concurrent/DiningPhilosophers.java +++ b/concurrent/DiningPhilosophers.java @@ -1,8 +1,9 @@ // 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 +// {ExcludeFromGradle} Gradle has trouble import java.util.*; import java.util.concurrent.*; import onjava.Nap; diff --git a/concurrent/DualCompletableOperations.java b/concurrent/DualCompletableOperations.java index 2c4ac45a1..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.*; @@ -102,13 +102,13 @@ public static void main(String[] args) { ***************** Workable[CW] anyOf -Workable[BW] Workable[DW] +Workable[BW] Workable[AW] ***************** Workable[CW] -Workable[BW] Workable[DW] +Workable[BW] Workable[AW] ***************** allOf diff --git a/concurrent/FrostedCake.java b/concurrent/FrostedCake.java index 0203e7223..77a15fcfe 100644 --- a/concurrent/FrostedCake.java +++ b/concurrent/FrostedCake.java @@ -1,12 +1,12 @@ // 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.*; import java.util.stream.*; import onjava.Nap; -class Frosting { +final class Frosting { private Frosting() {} static CompletableFuture make() { new Nap(0.1); @@ -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 e4f7cac5a..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.*; @@ -9,15 +9,14 @@ import com.google.common.collect.Sets; public class IDChecker { - public static int SIZE = 100_000; + public static final int SIZE = 100_000; static class MakeObjects implements Supplier> { private Supplier gen; - public MakeObjects(Supplier gen) { + 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 9ed9632bc..8715741b8 100644 --- a/concurrent/InterferingTask.java +++ b/concurrent/InterferingTask.java @@ -1,14 +1,13 @@ // 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. public class InterferingTask implements Runnable { final int id; - private static Integer val = new Integer(0); + 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 a9561e92d..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.*; 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 872e58532..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.*; @@ -19,9 +19,8 @@ public static void main(String[] args) { } /* Output: java.util.concurrent.RejectedExecutionException: Task -NapTask[99] rejected from -java.util.concurrent.ThreadPoolExecutor@25154f[Shutting -down, pool size = 1, active threads = 1, queued tasks = 0, -completed tasks = 0] +NapTask[99] rejected from java.util.concurrent.ThreadPo +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 204ef839c..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 -1612 +1665 */ diff --git a/concurrent/ParallelPrime.java b/concurrent/ParallelPrime.java index 247deb8c2..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: -616 +1635 */ diff --git a/concurrent/ParallelStreamPuzzle.java b/concurrent/ParallelStreamPuzzle.java index bf3dd365e..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,11 +18,11 @@ 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); } } /* Output: -[2, 8, 21, 24, 27, 30, 33, 37, 40, 43] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] */ diff --git a/concurrent/ParallelStreamPuzzle2.java b/concurrent/ParallelStreamPuzzle2.java index 881e0032c..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.*; @@ -10,13 +10,13 @@ import java.nio.file.*; public class ParallelStreamPuzzle2 { - public static Deque trace = + public static final Deque trace = new ConcurrentLinkedDeque<>(); static class 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: -[4, 25, 27, 32, 37, 44, 49, 56, 61, 73] +[1, 5, 7, 8, 9, 11, 13, 15, 18, 21] */ diff --git a/concurrent/ParallelStreamPuzzle3.java b/concurrent/ParallelStreamPuzzle3.java index 6045ba92a..69a35618f 100644 --- a/concurrent/ParallelStreamPuzzle3.java +++ b/concurrent/ParallelStreamPuzzle3.java @@ -1,7 +1,8 @@ // 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} import java.util.*; import java.util.stream.*; @@ -26,7 +27,7 @@ public static void main(String[] args) { 2: ForkJoinPool.commonPool-worker-6 4: ForkJoinPool.commonPool-worker-1 0: ForkJoinPool.commonPool-worker-4 -7: main +7: ForkJoinPool.commonPool-worker-1 9: ForkJoinPool.commonPool-worker-2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] */ 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 32e53360a..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.*; @@ -7,7 +7,7 @@ import onjava.Timer; public class PizzaParallelSteps { - static int QUANTITY = 5; + static final int QUANTITY = 5; public static void main(String[] args) { Timer timer = new Timer(); IntStream.range(0, QUANTITY) @@ -25,45 +25,45 @@ public static void main(String[] args) { } } /* Output: -Pizza 4: ROLLED Pizza 1: ROLLED -Pizza 3: ROLLED -Pizza 0: ROLLED Pizza 2: ROLLED +Pizza 0: ROLLED +Pizza 3: ROLLED +Pizza 4: ROLLED Pizza 4: SAUCED -Pizza 3: SAUCED -Pizza 1: SAUCED Pizza 2: SAUCED Pizza 0: SAUCED -Pizza 4: CHEESED +Pizza 1: SAUCED +Pizza 3: SAUCED Pizza 1: CHEESED Pizza 3: CHEESED -Pizza 0: CHEESED +Pizza 4: CHEESED Pizza 2: CHEESED -Pizza 1: TOPPED +Pizza 0: CHEESED Pizza 3: TOPPED -Pizza 4: TOPPED -Pizza 2: TOPPED +Pizza 1: TOPPED Pizza 0: TOPPED -Pizza 1: BAKED -Pizza 3: BAKED -Pizza 4: BAKED +Pizza 2: TOPPED +Pizza 4: TOPPED Pizza 2: BAKED +Pizza 3: BAKED +Pizza 1: BAKED Pizza 0: BAKED -Pizza 1: SLICED +Pizza 4: BAKED Pizza 3: SLICED +Pizza 1: SLICED Pizza 2: SLICED -Pizza 4: SLICED Pizza 0: SLICED -Pizza 1: BOXED +Pizza 4: SLICED Pizza 3: BOXED Pizza3: complete -Pizza 4: BOXED -Pizza4: complete +Pizza 1: BOXED Pizza1: complete -Pizza 0: BOXED Pizza 2: BOXED -Pizza2: complete +Pizza 0: BOXED Pizza0: complete -1673 +Pizza2: complete +Pizza 4: BOXED +Pizza4: complete +1766 */ diff --git a/concurrent/PizzaStreams.java b/concurrent/PizzaStreams.java index d16fc13f3..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.*; @@ -7,12 +7,12 @@ import onjava.Timer; public class PizzaStreams { - static int QUANTITY = 5; + static final int QUANTITY = 5; 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 4: ROLLED -Pizza 2: ROLLED Pizza 0: ROLLED -Pizza 3: ROLLED Pizza 1: ROLLED +Pizza 2: ROLLED +Pizza 3: ROLLED +Pizza 4: ROLLED +Pizza 1: SAUCED Pizza 0: SAUCED -Pizza 3: SAUCED Pizza 4: SAUCED -Pizza 1: SAUCED Pizza 2: SAUCED -Pizza 0: CHEESED -Pizza 4: CHEESED +Pizza 3: SAUCED Pizza 3: CHEESED Pizza 2: CHEESED +Pizza 4: CHEESED +Pizza 0: CHEESED Pizza 1: CHEESED Pizza 3: TOPPED -Pizza 4: TOPPED -Pizza 0: TOPPED Pizza 2: TOPPED +Pizza 4: TOPPED Pizza 1: TOPPED -Pizza 0: BAKED -Pizza 3: BAKED +Pizza 0: TOPPED Pizza 4: BAKED -Pizza 1: BAKED Pizza 2: BAKED +Pizza 3: BAKED +Pizza 0: BAKED +Pizza 1: BAKED Pizza 4: SLICED Pizza 3: SLICED -Pizza 0: SLICED Pizza 2: SLICED +Pizza 0: SLICED Pizza 1: SLICED -Pizza 3: BOXED +Pizza 2: BOXED Pizza 4: BOXED -Pizza 0: BOXED +Pizza 3: BOXED Pizza 1: BOXED -Pizza 2: BOXED -1667 +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 a4d3995cd..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: -125 148 115 127 120 118 106 140 77 119 97 80 143 17 92 147 -89 123 16 12 138 25 13 101 135 96 76 73 130 133 37 132 134 -149 137 122 29 49 60 40 142 131 53 1 98 145 126 65 5 64 82 -79 68 86 141 61 128 22 7 26 19 139 114 146 14 15 43 34 10 -75 87 90 31 47 38 62 18 63 41 42 144 66 23 6 4 91 70 83 102 -103 54 69 74 56 71 94 88 78 81 57 52 93 45 48 44 32 28 36 -33 104 105 112 109 100 117 24 108 21 116 20 9 85 8 84 72 -107 113 121 124 136 129 99 95 55 3 27 2 59 67 50 58 51 39 -30 35 46 110 111 11 +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 b9825a277..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: -125 148 115 127 120 118 106 140 77 119 97 80 143 17 92 147 -89 123 16 12 138 25 13 101 135 96 76 73 130 133 37 132 134 -149 137 122 29 49 60 40 142 131 53 1 98 145 126 65 5 64 82 -79 68 86 141 61 128 22 7 26 19 139 114 146 14 15 43 34 10 -75 87 90 31 47 38 62 18 63 41 42 144 66 23 6 4 91 70 83 102 -103 54 69 74 56 71 94 88 78 81 57 52 93 45 48 44 32 28 36 -33 104 105 112 109 100 117 24 108 21 116 20 9 85 8 84 72 -107 113 121 124 136 129 99 95 55 3 27 2 59 67 50 58 51 39 -30 35 46 110 111 11 +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 b49f857af..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,24 +10,23 @@ 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(); } } class SharedUser implements HasID { private final int id; - public SharedUser(SharedArg sa) { + 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: -47747 +16537 0 */ diff --git a/concurrent/SingleThreadExecutor.java b/concurrent/SingleThreadExecutor.java index 2ef99677c..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.*; @@ -26,20 +26,21 @@ public static void main(String[] args) { /* Output: All tasks submitted main awaiting termination +main awaiting termination 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 372e53fc5..e02b42743 100644 --- a/concurrent/StreamExceptions.java +++ b/concurrent/StreamExceptions.java @@ -1,10 +1,9 @@ // 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.*; import java.util.stream.*; -import onjava.Nap; public class StreamExceptions { static Stream diff --git a/concurrent/Summing.java b/concurrent/Summing.java index 286861cd0..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: 631ms -Sum Stream Parallel: 159ms -Sum Iterated: 2560ms +Sum Stream: 841ms +Sum Stream Parallel: 179ms +Sum Iterated: 4051ms */ diff --git a/concurrent/Summing2.java b/concurrent/Summing2.java index dabece6ea..257a53138 100644 --- a/concurrent/Summing2.java +++ b/concurrent/Summing2.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} // CI has trouble +// {ExcludeFromTravisCI} import java.util.*; public class Summing2 { @@ -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 bcd483260..3af34db21 100644 --- a/concurrent/Summing3.java +++ b/concurrent/Summing3.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} // CI has trouble +// {ExcludeFromTravisCI} import java.util.*; public class Summing3 { @@ -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 27353141b..03dc04ba0 100644 --- a/concurrent/Summing4.java +++ b/concurrent/Summing4.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} // CI has trouble +// {ExcludeFromTravisCI} import java.util.*; public class Summing4 { @@ -12,10 +12,12 @@ public static void main(String[] args) { Arrays.parallelSetAll(aL, i -> (long)i); Summing.timeTest("Long Parallel", Summing3.CHECK, () -> - Arrays.stream(aL).parallel().reduce(0L,Long::sum)); + Arrays.stream(aL) + .parallel() + .reduce(0L,Long::sum)); } } /* Output: 50000005000000 -Long Parallel: 1014ms +Long Parallel: 1147ms */ diff --git a/concurrent/SynchronizedConstructor.java b/concurrent/SynchronizedConstructor.java index 0533f8bbc..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.*; @@ -8,13 +8,12 @@ class SyncConstructor implements HasID { private final int id; private static Object constructorLock = new Object(); - public SyncConstructor(SharedArg sa) { + SyncConstructor(SharedArg sa) { synchronized(constructorLock) { 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 d16d3a3e4..11e5f184b 100644 --- a/concurrent/SynchronizedFactory.java +++ b/concurrent/SynchronizedFactory.java @@ -1,16 +1,15 @@ // 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.*; -class SyncFactory implements HasID { +final class SyncFactory implements HasID { private final int id; 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 5ad53adb7..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: -47643 +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 337a9e199..0cfe7bd95 100644 --- a/control/LabeledFor.java +++ b/control/LabeledFor.java @@ -1,8 +1,8 @@ // 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" and "labeled continue." +// For loops with "labeled break"/"labeled continue." public class LabeledFor { public static void main(String[] args) { 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 f8a9b1968..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 @@ -19,7 +19,7 @@ public static void main(String[] args) { case 'u': System.out.println("vowel"); break; case 'y': - case 'w': System.out.println("Sometimes a vowel"); + case 'w': System.out.println("Sometimes vowel"); break; default: System.out.println("consonant"); } @@ -27,18 +27,18 @@ public static void main(String[] args) { } } /* Output: (First 13 Lines) -y, 121: Sometimes a vowel +y, 121: Sometimes vowel n, 110: consonant z, 122: consonant b, 98: consonant r, 114: consonant n, 110: consonant -y, 121: Sometimes a vowel +y, 121: Sometimes vowel g, 103: consonant c, 99: consonant f, 102: consonant o, 111: vowel -w, 119: Sometimes a vowel +w, 119: Sometimes vowel z, 122: consonant ... */ 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 ee4abd6f5..8e2127b7a 100644 --- a/enums/BigEnumSet.java +++ b/enums/BigEnumSet.java @@ -1,17 +1,18 @@ // 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.*; public class BigEnumSet { - enum Big { A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, - A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, - A22, A23, A24, A25, A26, A27, A28, A29, A30, A31, A32, - A33, A34, A35, A36, A37, A38, A39, A40, A41, A42, A43, - A44, A45, A46, A47, A48, A49, A50, A51, A52, A53, A54, - A55, A56, A57, A58, A59, A60, A61, A62, A63, A64, A65, - A66, A67, A68, A69, A70, A71, A72, A73, A74, A75 } + enum Big { A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, + A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, + A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, + A30, A31, A32, A33, A34, A35, A36, A37, A38, A39, + A40, A41, A42, A43, A44, A45, A46, A47, A48, A49, + A50, A51, A52, A53, A54, A55, A56, A57, A58, A59, + A60, A61, A62, A63, A64, A65, A66, A67, A68, A69, + A70, A71, A72, A73, A74, A75 } public static void main(String[] args) { EnumSet bigEnumSet = EnumSet.allOf(Big.class); System.out.println(bigEnumSet); @@ -19,10 +20,10 @@ public static void main(String[] args) { } /* Output: [A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, -A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24, -A25, A26, A27, A28, A29, A30, A31, A32, A33, A34, A35, A36, -A37, A38, A39, A40, A41, A42, A43, A44, A45, A46, A47, A48, -A49, A50, A51, A52, A53, A54, A55, A56, A57, A58, A59, A60, -A61, A62, A63, A64, A65, A66, A67, A68, A69, A70, A71, A72, -A73, A74, A75] +A13, A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, +A24, A25, A26, A27, A28, A29, A30, A31, A32, A33, A34, +A35, A36, A37, A38, A39, A40, A41, A42, A43, A44, A45, +A46, A47, A48, A49, A50, A51, A52, A53, A54, A55, A56, +A57, A58, A59, A60, A61, A62, A63, A64, A65, A66, A67, +A68, A69, A70, A71, A72, A73, A74, A75] */ 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 7e485e2c7..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,8 +30,8 @@ public static void main(String[] args) { } } /* Output: -Jul 27, 2016 -C:\Users\Bruce\Documents\GitHub\on- -java\ExtractedExamples\\gradle\wrapper\gradle-wrapper.jar -1.8.0_102 +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 96eebb9ee..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 @@ -9,7 +9,8 @@ enum Shrubbery { GROUND, CRAWLING, HANGING } public class EnumClass { public static void main(String[] args) { for(Shrubbery s : Shrubbery.values()) { - System.out.println(s + " ordinal: " + s.ordinal()); + System.out.println( + s + " ordinal: " + s.ordinal()); System.out.print( s.compareTo(Shrubbery.CRAWLING) + " "); System.out.print( @@ -17,11 +18,13 @@ public static void main(String[] args) { System.out.println(s == Shrubbery.CRAWLING); System.out.println(s.getDeclaringClass()); System.out.println(s.name()); - System.out.println("----------------------"); + System.out.println("********************"); } // Produce an enum value from a String name: - for(String s : "HANGING CRAWLING GROUND".split(" ")) { - Shrubbery shrub = Enum.valueOf(Shrubbery.class, s); + for(String s : + "HANGING CRAWLING GROUND".split(" ")) { + Shrubbery shrub = + Enum.valueOf(Shrubbery.class, s); System.out.println(shrub); } } @@ -31,17 +34,17 @@ public static void main(String[] args) { -1 false false class Shrubbery GROUND ----------------------- +******************** CRAWLING ordinal: 1 0 true true class Shrubbery CRAWLING ----------------------- +******************** HANGING ordinal: 2 1 false false class Shrubbery HANGING ----------------------- +******************** HANGING CRAWLING GROUND diff --git a/enums/EnumMaps.java b/enums/EnumMaps.java index f2398e8ae..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 @@ -18,7 +18,8 @@ public static void main(String[] args) { () -> System.out.println("Kitchen fire!")); em.put(BATHROOM, () -> System.out.println("Bathroom alert!")); - for(Map.Entry e: em.entrySet()) { + for(Map.Entry e: + em.entrySet()) { System.out.print(e.getKey() + ": "); e.getValue().action(); } 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 7e0ce2876..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"); } }; @@ -34,8 +32,11 @@ public class NotClasses { abstract class LikeClasses extends java.lang.Enum { public static final LikeClasses WINKEN; + public static final LikeClasses BLINKEN; + public static final LikeClasses NOD; + public static LikeClasses[] values(); Code: 0: getstatic #2 // Field 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 4d00b25e6..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,54 +138,54 @@ public static void main(String[] args) { } } /* Output: -Mail 0, General Delivery: NO3, Address Scanability: YES2, -Address Readability: YES1, Address Address: OK4, Return -address: OK5 -Delivering Mail 0 automatically +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: NO1, Address Scanability: YES1, -Address Readability: YES3, Address Address: OK6, Return -address: OK1 +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: NO4, Address Scanability: YES2, -Address Readability: ILLEGIBLE, Address Address: OK5, -Return address: MISSING -Delivering Mail 2 automatically +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: YES, Address Scanability: -UNSCANNABLE, Address Readability: YES2, Address Address: -OK6, Return address: OK1 -Using general delivery for Mail 3 +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: YES, Address Scanability: YES4, -Address Readability: YES1, Address Address: OK6, Return -address: OK5 -Using general delivery for Mail 4 +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: NO5, Address Scanability: YES3, -Address Readability: YES3, Address Address: OK1, Return -address: OK4 +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: -UNSCANNABLE, Address Readability: YES1, Address Address: -OK3, Return address: MISSING +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: NO4, Address Scanability: YES1, -Address Readability: YES2, Address Address: OK2, Return -address: MISSING -Delivering Mail 7 automatically +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: NO1, Address Scanability: YES2, -Address Readability: YES3, Address Address: OK3, Return -address: OK3 -Delivering Mail 8 automatically +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: NO5, Address Scanability: YES1, -Address Readability: YES3, Address Address: OK2, Return -address: OK3 -Delivering Mail 9 automatically +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 b81835e64..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.*; @@ -15,7 +15,7 @@ public static void main(String[] args) { } } /* Output: -JUMPING DODGING SITTING RUNNING FLYING RUNNING DODGING -STANDING DODGING FALLING FALLING SITTING DODGING LYING -JUMPING JUMPING HOPPING DODGING SITTING FALLING +STANDING FLYING RUNNING STANDING RUNNING STANDING LYING +DODGING SITTING RUNNING HOPPING HOPPING HOPPING RUNNING +STANDING LYING FALLING RUNNING FLYING LYING */ diff --git a/enums/Reflection.java b/enums/Reflection.java index 479d23e75..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 @@ -10,9 +10,10 @@ enum Explore { HERE, THERE } public class Reflection { - public static Set analyze(Class enumClass) { + public static + Set analyze(Class enumClass) { System.out.println( - "----- Analyzing " + enumClass + " -----"); + "_____ Analyzing " + enumClass + " _____"); System.out.println("Interfaces:"); for(Type t : enumClass.getGenericInterfaces()) System.out.println(t); @@ -37,25 +38,26 @@ 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: ------ Analyzing class Explore ----- +_____ Analyzing class Explore _____ Interfaces: Base: class java.lang.Enum Methods: -[compareTo, equals, getClass, getDeclaringClass, hashCode, -name, notify, notifyAll, ordinal, toString, valueOf, -values, wait] ------ Analyzing class java.lang.Enum ----- +[compareTo, equals, getClass, getDeclaringClass, +hashCode, name, notify, notifyAll, ordinal, toString, +valueOf, values, wait] +_____ Analyzing class java.lang.Enum _____ Interfaces: java.lang.Comparable interface java.io.Serializable Base: class java.lang.Object Methods: -[compareTo, equals, getClass, getDeclaringClass, hashCode, -name, notify, notifyAll, ordinal, toString, valueOf, wait] +[compareTo, equals, getClass, getDeclaringClass, +hashCode, name, notify, notifyAll, ordinal, toString, +valueOf, wait] Explore.containsAll(Enum)? true Explore.removeAll(Enum): [values] Compiled from "Reflection.java" 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 930958836..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; @@ -81,24 +28,24 @@ public static void main(String[] args) { } } /* Output: -Scissors vs. Rock: LOSE +Rock vs. Rock: DRAW +Paper vs. Rock: WIN +Paper vs. Rock: WIN +Paper vs. Rock: WIN +Scissors vs. Paper: WIN +Scissors vs. Scissors: DRAW Scissors vs. Paper: WIN Rock vs. Paper: LOSE -Rock vs. Rock: DRAW +Paper vs. Paper: DRAW Rock vs. Paper: LOSE Paper vs. Scissors: LOSE +Paper vs. Scissors: LOSE +Rock vs. Scissors: WIN Rock vs. Paper: LOSE -Scissors vs. Scissors: DRAW -Scissors vs. Rock: LOSE +Paper vs. Rock: WIN Scissors vs. Paper: WIN -Scissors vs. Rock: LOSE Paper vs. Scissors: LOSE -Rock vs. Rock: DRAW -Scissors vs. Scissors: DRAW -Paper vs. Paper: DRAW -Scissors vs. Paper: WIN -Scissors vs. Rock: LOSE -Scissors vs. Paper: WIN -Rock vs. Paper: LOSE -Rock vs. Scissors: WIN +Paper vs. Scissors: LOSE +Paper vs. Scissors: LOSE +Paper vs. Scissors: LOSE */ diff --git a/enums/RoShamBo2.java b/enums/RoShamBo2.java index c977991c0..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 @@ -12,13 +12,13 @@ public enum RoShamBo2 implements Competitor { SCISSORS(WIN, DRAW, LOSE), ROCK(LOSE, WIN, DRAW); private Outcome vPAPER, vSCISSORS, vROCK; - RoShamBo2(Outcome paper,Outcome scissors,Outcome rock) { + RoShamBo2(Outcome paper, + Outcome scissors, Outcome rock) { this.vPAPER = paper; 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; @@ -31,24 +31,24 @@ public static void main(String[] args) { } } /* Output: -PAPER vs. ROCK: WIN +ROCK vs. ROCK: DRAW +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +PAPER vs. SCISSORS: LOSE +PAPER vs. PAPER: DRAW PAPER vs. SCISSORS: LOSE ROCK vs. SCISSORS: WIN -ROCK vs. ROCK: DRAW +SCISSORS vs. SCISSORS: DRAW ROCK vs. SCISSORS: WIN SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +ROCK vs. PAPER: LOSE ROCK vs. SCISSORS: WIN -PAPER vs. PAPER: DRAW -PAPER vs. ROCK: WIN +SCISSORS vs. ROCK: LOSE PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN SCISSORS vs. PAPER: WIN -ROCK vs. ROCK: DRAW -PAPER vs. PAPER: DRAW -SCISSORS vs. SCISSORS: DRAW -PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN -PAPER vs. SCISSORS: LOSE -ROCK vs. SCISSORS: WIN -ROCK vs. PAPER: LOSE +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN */ diff --git a/enums/RoShamBo3.java b/enums/RoShamBo3.java index a4a843b19..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; @@ -48,24 +45,24 @@ public static void main(String[] args) { } } /* Output: -PAPER vs. ROCK: WIN +ROCK vs. ROCK: DRAW +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +PAPER vs. SCISSORS: LOSE +PAPER vs. PAPER: DRAW PAPER vs. SCISSORS: LOSE ROCK vs. SCISSORS: WIN -ROCK vs. ROCK: DRAW +SCISSORS vs. SCISSORS: DRAW ROCK vs. SCISSORS: WIN SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +ROCK vs. PAPER: LOSE ROCK vs. SCISSORS: WIN -PAPER vs. PAPER: DRAW -PAPER vs. ROCK: WIN +SCISSORS vs. ROCK: LOSE PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN SCISSORS vs. PAPER: WIN -ROCK vs. ROCK: DRAW -PAPER vs. PAPER: DRAW -SCISSORS vs. SCISSORS: DRAW -PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN -PAPER vs. SCISSORS: LOSE -ROCK vs. SCISSORS: WIN -ROCK vs. PAPER: LOSE +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN */ diff --git a/enums/RoShamBo4.java b/enums/RoShamBo4.java index ccaa7e5da..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} @@ -34,24 +34,24 @@ public static void main(String[] args) { } } /* Output: -ROCK vs. PAPER: LOSE +PAPER vs. PAPER: DRAW +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +ROCK vs. SCISSORS: WIN +ROCK vs. ROCK: DRAW ROCK vs. SCISSORS: WIN PAPER vs. SCISSORS: LOSE -PAPER vs. PAPER: DRAW +SCISSORS vs. SCISSORS: DRAW PAPER vs. SCISSORS: LOSE SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +PAPER vs. ROCK: WIN PAPER vs. SCISSORS: LOSE -ROCK vs. ROCK: DRAW -ROCK vs. PAPER: LOSE +SCISSORS vs. PAPER: WIN ROCK vs. SCISSORS: WIN -ROCK vs. PAPER: LOSE SCISSORS vs. ROCK: LOSE -PAPER vs. PAPER: DRAW -ROCK vs. ROCK: DRAW -SCISSORS vs. SCISSORS: DRAW -ROCK vs. SCISSORS: WIN -ROCK vs. PAPER: LOSE -ROCK vs. SCISSORS: WIN -PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE */ diff --git a/enums/RoShamBo5.java b/enums/RoShamBo5.java index 5382aba12..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) { @@ -36,24 +35,24 @@ public static void main(String[] args) { } } /* Output: -PAPER vs. ROCK: WIN +ROCK vs. ROCK: DRAW +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +PAPER vs. SCISSORS: LOSE +PAPER vs. PAPER: DRAW PAPER vs. SCISSORS: LOSE ROCK vs. SCISSORS: WIN -ROCK vs. ROCK: DRAW +SCISSORS vs. SCISSORS: DRAW ROCK vs. SCISSORS: WIN SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +ROCK vs. PAPER: LOSE ROCK vs. SCISSORS: WIN -PAPER vs. PAPER: DRAW -PAPER vs. ROCK: WIN +SCISSORS vs. ROCK: LOSE PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN SCISSORS vs. PAPER: WIN -ROCK vs. ROCK: DRAW -PAPER vs. PAPER: DRAW -SCISSORS vs. SCISSORS: DRAW -PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN -PAPER vs. SCISSORS: LOSE -ROCK vs. SCISSORS: WIN -ROCK vs. PAPER: LOSE +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN */ diff --git a/enums/RoShamBo6.java b/enums/RoShamBo6.java index 1483a8030..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) { @@ -23,24 +22,24 @@ public static void main(String[] args) { } } /* Output: -PAPER vs. ROCK: WIN +ROCK vs. ROCK: DRAW +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +SCISSORS vs. ROCK: LOSE +PAPER vs. SCISSORS: LOSE +PAPER vs. PAPER: DRAW PAPER vs. SCISSORS: LOSE ROCK vs. SCISSORS: WIN -ROCK vs. ROCK: DRAW +SCISSORS vs. SCISSORS: DRAW ROCK vs. SCISSORS: WIN SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +ROCK vs. PAPER: LOSE ROCK vs. SCISSORS: WIN -PAPER vs. PAPER: DRAW -PAPER vs. ROCK: WIN +SCISSORS vs. ROCK: LOSE PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN SCISSORS vs. PAPER: WIN -ROCK vs. ROCK: DRAW -PAPER vs. PAPER: DRAW -SCISSORS vs. SCISSORS: DRAW -PAPER vs. SCISSORS: LOSE -PAPER vs. ROCK: WIN -PAPER vs. SCISSORS: LOSE -ROCK vs. SCISSORS: WIN -ROCK vs. PAPER: LOSE +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN +SCISSORS vs. PAPER: WIN */ 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 f915f28f5..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 @@ -33,14 +33,14 @@ public static void main(String[] args) { } } /* Output: +BOND: MUNICIPAL +BOND: MUNICIPAL +STOCK: MARGIN STOCK: MARGIN +BOND: JUNK +STOCK: SHORT STOCK: LONG STOCK: LONG -STOCK: MARGIN BOND: MUNICIPAL -BOND: MUNICIPAL -STOCK: LONG -BOND: JUNK -STOCK: MARGIN BOND: JUNK */ 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 d5d7bf4df..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; @@ -101,7 +97,8 @@ void next(Input input) { "next(Input input) for non-transient states"); } void next() { - throw new RuntimeException("Only call next() for " + + throw new RuntimeException( + "Only call next() for " + "StateDuration.TRANSIENT states"); } void output() { System.out.println(amount); } @@ -124,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(); } } @@ -133,7 +129,7 @@ public Input get() { // Create Inputs from a file of ';'-separated strings: class FileInputSupplier implements Supplier { private Iterator input; - public FileInputSupplier(String fileName) { + FileInputSupplier(String fileName) { try { input = Files.lines(Paths.get(fileName)) .skip(1) // Skip the comment line @@ -145,8 +141,7 @@ public FileInputSupplier(String fileName) { 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 68eab3581..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)]; } } @@ -32,6 +31,6 @@ public static void main(String[] args) { } } /* Output: -SILLY, SPANKY, PUNCHY, BOUNCY, BOB, SLAPPY, SLAPPY, BOB, -BOB, SLAPPY, +BOB, PUNCHY, BOB, SPANKY, NUTTY, PUNCHY, SLAPPY, NUTTY, +NUTTY, SLAPPY, */ 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 adfe92a65..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} @@ -12,34 +12,34 @@ public static void main(String[] args) { Food food = course.randomSelection(); System.out.println(food); } - System.out.println("---"); + System.out.println("***"); } } } /* Output: -SALAD -VINDALOO -GELATO -CAPPUCCINO ---- -SPRING_ROLLS -BURRITO -GELATO -HERB_TEA ---- SPRING_ROLLS +VINDALOO +FRUIT +DECAF_COFFEE +*** +SOUP +VINDALOO +FRUIT +TEA +*** +SALAD BURRITO -TIRAMISU -CAPPUCCINO ---- -SPRING_ROLLS +FRUIT +TEA +*** +SALAD BURRITO -BLACK_FOREST_CAKE +CREME_CARAMEL LATTE ---- -SALAD -PAD_THAI -GELATO -TEA ---- +*** +SOUP +BURRITO +TIRAMISU +ESPRESSO +*** */ diff --git a/enums/menu/Meal2.java b/enums/menu/Meal2.java index 5d63b54f1..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, @@ -41,34 +41,34 @@ public static void main(String[] args) { Food food = meal.randomSelection(); System.out.println(food); } - System.out.println("---"); + System.out.println("***"); } } } /* Output: -SALAD -VINDALOO -GELATO -CAPPUCCINO ---- -SPRING_ROLLS -BURRITO -GELATO -HERB_TEA ---- SPRING_ROLLS +VINDALOO +FRUIT +DECAF_COFFEE +*** +SOUP +VINDALOO +FRUIT +TEA +*** +SALAD BURRITO -TIRAMISU -CAPPUCCINO ---- -SPRING_ROLLS +FRUIT +TEA +*** +SALAD BURRITO -BLACK_FOREST_CAKE +CREME_CARAMEL LATTE ---- -SALAD -PAD_THAI -GELATO -TEA ---- +*** +SOUP +BURRITO +TIRAMISU +ESPRESSO +*** */ 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 b9931a66e..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.*; @@ -7,12 +7,11 @@ class Part { String ss; double dd; - public Part(String ss, double dd) { + Part(String ss, double dd) { 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,11 +25,11 @@ 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, ((ComposedEquality)rval).part); + Objects.equals(part, + ((ComposedEquality)rval).part); } public static void main(String[] args) { Equality.testAll( (i, s, d) -> diff --git a/equalshashcode/CountedString.java b/equalshashcode/CountedString.java index 3b0064d6b..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); @@ -55,10 +52,10 @@ public static void main(String[] args) { } } /* Output: -{String: hi id: 4 hashCode(): 146450=3, String: hi id: 5 -hashCode(): 146451=4, String: hi id: 2 hashCode(): -146448=1, String: hi id: 3 hashCode(): 146449=2, String: hi -id: 1 hashCode(): 146447=0} +{String: hi id: 4 hashCode(): 146450=3, String: hi id: +5 hashCode(): 146451=4, String: hi id: 2 hashCode(): +146448=1, String: hi id: 3 hashCode(): 146449=2, +String: hi id: 1 hashCode(): 146447=0} Looking up String: hi id: 1 hashCode(): 146447 0 Looking up String: hi id: 2 hashCode(): 146448 diff --git a/equalshashcode/DefaultComparison.java b/equalshashcode/DefaultComparison.java index a702d4da7..1c5c03ab9 100644 --- a/equalshashcode/DefaultComparison.java +++ b/equalshashcode/DefaultComparison.java @@ -1,11 +1,11 @@ // 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. class DefaultComparison { private int i, j, k; - public DefaultComparison(int i, int j, int k) { + DefaultComparison(int i, int j, int k) { this.i = i; this.j = j; this.k = k; diff --git a/equalshashcode/Equality.java b/equalshashcode/Equality.java index 4fd0e36a4..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) @@ -46,7 +45,8 @@ public static void testAll(EqualityFactory eqf) { neq = eqf.make(99, "Bob", 1.618); e.test("null", "false", null); e.test("same object", "true", e); - e.test("different type", "false", new Integer(99)); + e.test("different type", + "false", Integer.valueOf(99)); e.test("same values", "true", eq); e.test("different values", "false", neq); } 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 fc4334150..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 { @@ -20,7 +20,7 @@ public static void main(String[] args) { Cat Elsie May Cat Pinkola Cat Shackleton -Cat Stanford aka Stinky el Negro +Cat Stanford Cymric Molly Dog Margrett Mutt Spot 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 2add1e475..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); @@ -20,13 +19,12 @@ public V put(K key, V value) { return oldValue; } @Override - public V get(Object key) { // key is type Object, not K + public V get(Object key) { // key: type Object, not K if(!keys.contains(key)) 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 50cf361b8..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.*; @@ -11,24 +11,21 @@ class Animal { private final int id = counter++; private final String name; private final Size size; - public Animal(String name, Size size) { + Animal(String name, Size size) { 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()); @@ -36,13 +33,13 @@ public String toString() { } class Dog extends Animal { - public Dog(String name, Size size) { + Dog(String name, Size size) { super(name, size); } } class Pig extends Animal { - public Pig(String name, Size size) { + Pig(String name, Size size) { super(name, size); } } @@ -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 990ddf762..a107409ff 100644 --- a/equalshashcode/SubtypeEquality2.java +++ b/equalshashcode/SubtypeEquality2.java @@ -1,26 +1,24 @@ // 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.*; class Dog2 extends Animal { - public Dog2(String name, Size size) { + 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); } } class Pig2 extends Animal { - public Pig2(String name, Size size) { + 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 23f8a172a..3c0a0d036 100644 --- a/exceptions/AutoCloseableDetails.java +++ b/exceptions/AutoCloseableDetails.java @@ -1,14 +1,14 @@ // 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. class Reporter implements AutoCloseable { String name = getClass().getSimpleName(); - public Reporter() { + 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 8854bc148..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 @@ -20,7 +20,8 @@ public static void main(String[] args) { in.dispose(); } } catch(Exception e) { - System.out.println("InputFile construction failed"); + System.out.println( + "InputFile construction failed"); } } } diff --git a/exceptions/CleanupIdiom.java b/exceptions/CleanupIdiom.java index 48ce0d45f..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 @@ -17,7 +17,7 @@ class ConstructionException extends Exception {} class NeedsCleanup2 extends NeedsCleanup { // Construction can fail: - public NeedsCleanup2() throws ConstructionException {} + NeedsCleanup2() throws ConstructionException {} } public class CleanupIdiom { @@ -31,7 +31,8 @@ public static void main(String[] args) { } // [2]: - // If construction cannot fail you can group objects: + // If construction cannot fail, + // you can group objects: NeedsCleanup nc2 = new NeedsCleanup(); NeedsCleanup nc3 = new NeedsCleanup(); try { diff --git a/exceptions/CloseExceptions.java b/exceptions/CloseExceptions.java index 9ad598b43..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. @@ -7,9 +7,10 @@ class CloseException extends Exception {} class Reporter2 implements AutoCloseable { String name = getClass().getSimpleName(); - public Reporter2() { + 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 d3342b388..24191d1ce 100644 --- a/exceptions/ConstructorException.java +++ b/exceptions/ConstructorException.java @@ -1,12 +1,12 @@ // 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. class CE extends Exception {} class SecondExcept extends Reporter { - public SecondExcept() throws CE { + SecondExcept() throws CE { super(); throw new CE(); } diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index 297e8c0bd..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]); @@ -31,8 +30,8 @@ private int hasField(String id) { return i; return -1; } - private int - getFieldNumber(String id) throws NoSuchFieldException { + private int getFieldNumber(String id) + throws NoSuchFieldException { int fieldNum = hasField(id); if(fieldNum == -1) throw new NoSuchFieldException(); @@ -61,9 +60,10 @@ private int makeField(String id) { public Object setField(String id, Object value) throws DynamicFieldsException { if(value == null) { - // Most exceptions don't have a "cause" constructor. - // In these cases you must use initCause(), - // available in all Throwable subclasses. + // Most exceptions don't have a "cause" + // constructor. In these cases you must use + // initCause(), available in all + // Throwable subclasses. DynamicFieldsException dfe = new DynamicFieldsException(); dfe.initCause(new NullPointerException()); @@ -95,7 +95,8 @@ public static void main(String[] args) { System.out.println("df: " + df); System.out.println("df.getField(\"d\") : " + df.getField("d")); - Object field = df.setField("d", null); // Exception + Object field = + df.setField("d", null); // Exception } catch(NoSuchFieldException | DynamicFieldsException e) { e.printStackTrace(System.out); @@ -118,9 +119,11 @@ public static void main(String[] args) { df.getField("d") : A new value for d DynamicFieldsException - at DynamicFields.setField(DynamicFields.java:64) - at DynamicFields.main(DynamicFields.java:95) + at +DynamicFields.setField(DynamicFields.java:64) + at DynamicFields.main(DynamicFields.java:96) Caused by: java.lang.NullPointerException - at DynamicFields.setField(DynamicFields.java:66) + at +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 a86d20cca..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 @@ -27,5 +27,6 @@ public static void main(String[] args) { toString():java.lang.Exception: My Exception printStackTrace(): java.lang.Exception: My Exception - at ExceptionMethods.main(ExceptionMethods.java:7) + at +ExceptionMethods.main(ExceptionMethods.java:7) */ 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 b45c27e39..abf9d0bef 100644 --- a/exceptions/ExtraFeatures.java +++ b/exceptions/ExtraFeatures.java @@ -1,20 +1,19 @@ // 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 class MyException2 extends Exception { private int x; - public MyException2() {} - public MyException2(String msg) { super(msg); } - public MyException2(String msg, int x) { + MyException2() {} + MyException2(String msg) { super(msg); } + MyException2(String msg, int x) { super(msg); this.x = x; } public int val() { return x; } - @Override - public String getMessage() { + @Override public String getMessage() { return "Detail Message: "+ x + " "+ super.getMessage(); } @@ -22,15 +21,18 @@ public String getMessage() { public class ExtraFeatures { public static void f() throws MyException2 { - System.out.println("Throwing MyException2 from f()"); + System.out.println( + "Throwing MyException2 from f()"); throw new MyException2(); } public static void g() throws MyException2 { - System.out.println("Throwing MyException2 from g()"); + System.out.println( + "Throwing MyException2 from g()"); throw new MyException2("Originated in g()"); } public static void h() throws MyException2 { - System.out.println("Throwing MyException2 from h()"); + System.out.println( + "Throwing MyException2 from h()"); throw new MyException2("Originated in h()", 47); } public static void main(String[] args) { @@ -56,14 +58,14 @@ public static void main(String[] args) { Throwing MyException2 from f() MyException2: Detail Message: 0 null at ExtraFeatures.f(ExtraFeatures.java:23) - at ExtraFeatures.main(ExtraFeatures.java:35) + at ExtraFeatures.main(ExtraFeatures.java:37) Throwing MyException2 from g() MyException2: Detail Message: 0 Originated in g() - at ExtraFeatures.g(ExtraFeatures.java:27) - at ExtraFeatures.main(ExtraFeatures.java:40) + 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:31) - at ExtraFeatures.main(ExtraFeatures.java:45) + 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 1851d2d6c..bb10b0f1c 100644 --- a/exceptions/FullConstructors.java +++ b/exceptions/FullConstructors.java @@ -1,11 +1,11 @@ // 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. class MyException extends Exception { - public MyException() {} - public MyException(String msg) { super(msg); } + MyException() {} + MyException(String msg) { super(msg); } } public class FullConstructors { @@ -34,9 +34,11 @@ public static void main(String[] args) { Throwing MyException from f() MyException at FullConstructors.f(FullConstructors.java:11) - at FullConstructors.main(FullConstructors.java:19) + at +FullConstructors.main(FullConstructors.java:19) Throwing MyException from g() MyException: Originated in g() at FullConstructors.g(FullConstructors.java:15) - at FullConstructors.main(FullConstructors.java:24) + at +FullConstructors.main(FullConstructors.java:24) */ 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 72afe65ed..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 @@ -8,11 +8,13 @@ class SimpleException extends Exception {} public class InheritingExceptions { public void f() throws SimpleException { - System.out.println("Throw SimpleException from f()"); + System.out.println( + "Throw SimpleException from f()"); throw new SimpleException(); } public static void main(String[] args) { - InheritingExceptions sed = new InheritingExceptions(); + InheritingExceptions sed = + new InheritingExceptions(); try { sed.f(); } catch(SimpleException e) { 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 ebdd809d8..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 @@ -10,7 +10,7 @@ class LoggingException extends Exception { private static Logger logger = Logger.getLogger("LoggingException"); - public LoggingException() { + LoggingException() { StringWriter trace = new StringWriter(); printStackTrace(new PrintWriter(trace)); logger.severe(trace.toString()); @@ -33,13 +33,13 @@ public static void main(String[] args) { } /* Output: ___[ Error Output ]___ -Jul 27, 2016 10:50:30 AM LoggingException +Jan 24, 2021 8:48:54 AM LoggingException SEVERE: LoggingException at LoggingExceptions.main(LoggingExceptions.java:20) Caught LoggingException -Jul 27, 2016 10:50:30 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 a99d0a855..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 ]___ -Jul 27, 2016 10:50:30 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 1999b4862..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 @@ -18,8 +18,8 @@ public static void main(String[] args) { } /* Output: ___[ Error Output ]___ -Exception in thread "main" java.lang.RuntimeException: From -f() +Exception in thread "main" java.lang.RuntimeException: +From f() at NeverCaught.f(NeverCaught.java:7) at NeverCaught.g(NeverCaught.java:10) at NeverCaught.main(NeverCaught.java:13) 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 cc2601b07..1725d0a25 100644 --- a/exceptions/RethrowNew.java +++ b/exceptions/RethrowNew.java @@ -1,15 +1,15 @@ // 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 class OneException extends Exception { - public OneException(String s) { super(s); } + OneException(String s) { super(s); } } class TwoException extends Exception { - public TwoException(String s) { super(s); } + TwoException(String s) { super(s); } } public class RethrowNew { 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 5b2b727c0..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 @@ -11,7 +11,7 @@ class Foul extends BaseballException {} class Strike extends BaseballException {} abstract class Inning { - public Inning() throws BaseballException {} + Inning() throws BaseballException {} public void event() throws BaseballException { // Doesn't actually have to throw anything } @@ -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 547a16c95..faa446cd3 100644 --- a/exceptions/TryAnything.java +++ b/exceptions/TryAnything.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} class Anything {} 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 654ac285b..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 @@ -11,7 +11,8 @@ void throwRuntimeException(int type) { switch(type) { case 0: throw new FileNotFoundException(); case 1: throw new IOException(); - case 2: throw new RuntimeException("Where am I?"); + case 2: throw new + RuntimeException("Where am I?"); default: return; } } catch(IOException | RuntimeException e) { @@ -25,9 +26,11 @@ class SomeOtherException extends Exception {} public class TurnOffChecking { public static void main(String[] args) { - WrapCheckedException wce = new WrapCheckedException(); - // You can call throwRuntimeException() without a try - // block, and let RuntimeExceptions leave the method: + WrapCheckedException wce = + new WrapCheckedException(); + // You can call throwRuntimeException() without + // a try block, and let RuntimeExceptions + // leave the method: wce.throwRuntimeException(3); // Or you can choose to catch exceptions: for(int i = 0; i < 4; i++) @@ -37,7 +40,8 @@ public static void main(String[] args) { else throw new SomeOtherException(); } catch(SomeOtherException e) { - System.out.println("SomeOtherException: " + e); + System.out.println( + "SomeOtherException: " + e); } catch(RuntimeException re) { try { throw re.getCause(); diff --git a/exceptions/WhoCalled.java b/exceptions/WhoCalled.java index f27a0bb6a..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 @@ -18,20 +18,20 @@ static void f() { static void h() { g(); } public static void main(String[] args) { f(); - System.out.println("-------------------------------"); + System.out.println("*******"); g(); - System.out.println("-------------------------------"); + System.out.println("*******"); h(); } } /* Output: f main -------------------------------- +******* f g main -------------------------------- +******* f g h 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 0172344bc..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_3697011820450773773 +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\234245189903117886.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\8752987828022262887.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\465343347528104633.tmp +test\baz\bag\foo\bar\6666183168609095028.tmp test\baz\bag\foo\bar\File.txt -test\DIR_3697011820450773773 -test\DIR_3697011820450773773\pre3304897437567097054.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\2118206626074637804.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 98c517761..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@1db9742 +sun.nio.fs.WindowsFileSystem$LookupService$1@1bd4fdd isOpen: true isReadOnly: false FileSystemProvider: -sun.nio.fs.WindowsFileSystemProvider@106d69c +sun.nio.fs.WindowsFileSystemProvider@55183b20 File Attribute Views: [owner, dos, acl, basic, user] */ diff --git a/files/Find.java b/files/Find.java index 464615467..d27c69ed7 100644 --- a/files/Find.java +++ b/files/Find.java @@ -1,7 +1,8 @@ // 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} import java.nio.file.*; public class Find { @@ -36,24 +37,24 @@ public class Find { } } /* Output: -test\bag\foo\bar\baz\369594599218802549.tmp +test\bag\foo\bar\baz\5208762845883213974.tmp test\bag\foo\bar\baz\File.txt -test\bar\baz\bag\foo\2372197258227988384.tmp +test\bar\baz\bag\foo\7918367201207778677.tmp test\bar\baz\bag\foo\File.txt -test\baz\bag\foo\bar\1091363470697614580.tmp +test\baz\bag\foo\bar\8016595521026696632.tmp test\baz\bag\foo\bar\File.txt test\dir.tmp -test\foo\bar\baz\bag\48863440153181406.tmp +test\foo\bar\baz\bag\5832319279813617280.tmp test\foo\bar\baz\bag\File.txt *************** -369594599218802549.tmp -2372197258227988384.tmp -1091363470697614580.tmp +5208762845883213974.tmp +7918367201207778677.tmp +8016595521026696632.tmp dir.tmp -48863440153181406.tmp +5832319279813617280.tmp *************** -369594599218802549.tmp -2372197258227988384.tmp -1091363470697614580.tmp -48863440153181406.tmp +5208762845883213974.tmp +7918367201207778677.tmp +8016595521026696632.tmp +5832319279813617280.tmp */ 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 b76be5519..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: 1630 -FileStore: SSD (C:) -LastModified: : 2016-07-27T15:52:49.898848Z -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 fc6ba1d59..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,18 +9,18 @@ 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()); - System.out.println("----------------"); + 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) { System.out.println(System.getProperty("os.name")); @@ -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 @@ -53,8 +54,9 @@ public static void main(String[] args) { FileName: NoFile.txt Parent: C:\path\to\nowhere Root: C:\ ----------------- -toString: PathInfo.java +****************** +toString: + PathInfo.java Exists: true RegularFile: true Directory: false @@ -62,41 +64,38 @@ public static void main(String[] args) { FileName: PathInfo.java 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 c9ffdd8e1..8a1f46107 100644 --- a/files/PathWatcher.java +++ b/files/PathWatcher.java @@ -1,7 +1,8 @@ // 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} import java.io.IOException; import java.nio.file.*; import static java.nio.file.StandardWatchEventKinds.*; @@ -34,8 +35,10 @@ static void delTxtFiles() { WatchService watcher = FileSystems.getDefault().newWatchService(); test.register(watcher, ENTRY_DELETE); - Executors.newSingleThreadScheduledExecutor().schedule( - PathWatcher::delTxtFiles,250,TimeUnit.MILLISECONDS); + Executors.newSingleThreadScheduledExecutor() + .schedule( + PathWatcher::delTxtFiles, + 250, TimeUnit.MILLISECONDS); WatchKey key = watcher.take(); for(WatchEvent evt : key.pollEvents()) { System.out.println( 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 b13107cc2..1162ff807 100644 --- a/files/TreeWatcher.java +++ b/files/TreeWatcher.java @@ -1,7 +1,8 @@ // 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} import java.io.IOException; import java.nio.file.*; import static java.nio.file.StandardWatchEventKinds.*; @@ -47,7 +48,4 @@ static void watchDir(Path dir) { evt.context(): File.txt evt.count(): 1 evt.kind(): ENTRY_DELETE -evt.context(): File.txt -evt.count(): 1 -evt.kind(): ENTRY_DELETE */ 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 3bba09ea4..40728b5f3 100644 --- a/functional/Closure3.java +++ b/functional/Closure3.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} import java.util.function.*; public class Closure3 { 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 d9a5df2f6..dcd7a08f4 100644 --- a/functional/Closure5.java +++ b/functional/Closure5.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} import java.util.function.*; public class Closure5 { 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 dba502fc4..098685296 100644 --- a/functional/Closure7.java +++ b/functional/Closure7.java @@ -1,13 +1,13 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} import java.util.function.*; public class Closure7 { IntSupplier makeFun(int x) { - Integer i = new Integer(0); + Integer i = 0; i = i + 1; return () -> x + i; } 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 4b6c8e27a..4679e474e 100644 --- a/functional/Closure9.java +++ b/functional/Closure9.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} import java.util.*; import java.util.function.*; 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 ff53990a1..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,16 +12,17 @@ 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: - Function sumHi = sum.apply("Hup "); + Function sumHi = + sum.apply("Hup "); System.out.println(sumHi.apply("Ho")); System.out.println(sumHi.apply("Hey")); } 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 976f7f283..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.*; @@ -8,26 +8,26 @@ class Foo {} class Bar { Foo f; - public Bar(Foo f) { this.f = f; } + Bar(Foo f) { this.f = f; } } class IBaz { int i; - public IBaz(int i) { + IBaz(int i) { this.i = i; } } class LBaz { long l; - public LBaz(long l) { + LBaz(long l) { this.l = l; } } class DBaz { double d; - public DBaz(double d) { + DBaz(double d) { this.d = d; } } 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 c56812859..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. @@ -29,7 +29,8 @@ public String goodbye(String arg) { return "Goodbye, " + arg; } public static void main(String[] args) { - FunctionalAnnotation fa = new FunctionalAnnotation(); + FunctionalAnnotation fa = + new FunctionalAnnotation(); Functional f = fa::goodbye; FunctionalNoAnn fna = fa::goodbye; // Functional fac = fa; // Incompatible 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 85a4f0b93..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; - public Description(String desc) { about = desc; } - void help(String msg) { // [4] + Description(String desc) { about = desc; } + 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 9e5b161e4..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.*; @@ -7,16 +7,19 @@ import onjava.*; public class ApplyTest { - public static void main(String[] args) throws Exception { + public static + void main(String[] args) throws Exception { List shapes = Suppliers.create(ArrayList::new, Shape::new, 3); - Apply.apply(shapes, Shape.class.getMethod("rotate")); + Apply.apply(shapes, + Shape.class.getMethod("rotate")); Apply.apply(shapes, Shape.class.getMethod("resize", int.class), 7); List squares = Suppliers.create(ArrayList::new, Square::new, 3); - Apply.apply(squares, Shape.class.getMethod("rotate")); + Apply.apply(squares, + Shape.class.getMethod("rotate")); Apply.apply(squares, Shape.class.getMethod("resize", int.class), 7); @@ -30,7 +33,8 @@ public static void main(String[] args) throws Exception { Shape::new, 3); Suppliers.fill(shapeQ, SimpleQueue::add, Square::new, 3); - Apply.apply(shapeQ, Shape.class.getMethod("rotate")); + Apply.apply(shapeQ, + Shape.class.getMethod("rotate")); } } /* Output: 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 d55ac5b3c..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. @@ -15,7 +15,7 @@ class WithColor { class Coord { public int x, y, z; } -// This won't work. Class must be first, then interfaces: +// This fails. Class must be first, then interfaces: // class WithColorCoord { // Multiple bounds: @@ -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 bd1c22b7d..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 { @@ -29,7 +29,7 @@ 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 +Expected: java.lang.ClassCastException: Attempt to +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 cf779321f..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 { @@ -33,7 +33,8 @@ public static void main(String[] args) { CommunicateA.perform(new RobotA(), RobotA::speak, RobotA::sit); CommunicateA.perform(new Mime(), - Mime::walkAgainstTheWind, Mime::pushInvisibleWalls); + Mime::walkAgainstTheWind, + Mime::pushInvisibleWalls); } } /* Output: 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 337ab3e8e..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.*; @@ -10,7 +10,7 @@ class MixinProxy implements InvocationHandler { Map delegatesByMethod; @SuppressWarnings("unchecked") - public MixinProxy(Tuple2>... pairs) { + MixinProxy(Tuple2>... pairs) { delegatesByMethod = new HashMap<>(); for(Tuple2> pair : pairs) { for(Method method : pair.a2.getMethods()) { @@ -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 -1469638238271 +1611503350927 1 */ diff --git a/generics/EpicBattle.java b/generics/EpicBattle.java index 60bb4ca82..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 @@ -31,18 +31,18 @@ class SuperSleuth void see() { power.seeThroughWalls(); } } -class CanineHero +class +CanineHero extends SuperHero { CanineHero(POWER power) { super(power); } void hear() { power.hearSubtleNoises(); } void smell() { power.trackBySmell(); } } -class SuperHearSmell implements SuperHearing, SuperSmell { - @Override - public void hearSubtleNoises() {} - @Override - public void trackBySmell() {} +class SuperHearSmell +implements SuperHearing, SuperSmell { + @Override public void hearSubtleNoises() {} + @Override public void trackBySmell() {} } class DogPerson extends CanineHero { diff --git a/generics/Erased.java b/generics/Erased.java index 8a1edd9dc..304385afb 100644 --- a/generics/Erased.java +++ b/generics/Erased.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} public class Erased { private final int SIZE = 100; 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 36957a867..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,17 +8,15 @@ class IntegerFactory implements Supplier { private int i = 0; - @Override - public Integer get() { + @Override public Integer get() { return ++i; } } class Widget { private int id; - public Widget(int n) { id = n; } - @Override - public String toString() { + Widget(int n) { id = n; } + @Override public String toString() { return "Widget " + id; } public static @@ -32,24 +30,29 @@ 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 { private List x = new ArrayList<>(); - public Foo2(Supplier factory) { + 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 { public static void main(String[] args) { - System.out.println(new Foo2<>(new IntegerFactory())); - System.out.println(new Foo2<>(new Widget.Factory())); - System.out.println(new Foo2<>(Fudge::new)); + System.out.println( + new Foo2<>(new IntegerFactory())); + System.out.println( + new Foo2<>(new Widget.Factory())); + System.out.println( + new Foo2<>(Fudge::new)); } } /* Output: diff --git a/generics/Fibonacci.java b/generics/Fibonacci.java index 10d2e8b4a..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 @@ -22,5 +22,6 @@ public static void main(String[] args) { } } /* Output: -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 +1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 +2584 */ diff --git a/generics/FilledList.java b/generics/FilledList.java index b9e1cb285..662d50f98 100644 --- a/generics/FilledList.java +++ b/generics/FilledList.java @@ -1,13 +1,13 @@ // 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.*; import java.util.function.*; import onjava.*; -class FilledList extends ArrayList { - public FilledList(Supplier gen, int size) { +public class FilledList extends ArrayList { + FilledList(Supplier gen, int size) { Suppliers.fill(this, gen, size); } public FilledList(T t, int size) { diff --git a/generics/GenericArray.java b/generics/GenericArray.java index d91a68d52..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. @@ -27,5 +27,6 @@ public static void main(String[] args) { } } /* Output: -[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; +[Ljava.lang.Object; cannot be cast to +[Ljava.lang.Integer; */ diff --git a/generics/GenericArray2.java b/generics/GenericArray2.java index 9fa0910fb..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. @@ -34,6 +34,6 @@ public static void main(String[] args) { } /* Output: 0 1 2 3 4 5 6 7 8 9 -java.lang.ClassCastException: [Ljava.lang.Object; cannot be -cast to [Ljava.lang.Integer; +java.lang.ClassCastException: [Ljava.lang.Object; +cannot be cast to [Ljava.lang.Integer; */ 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 9c1ca2828..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.*; @@ -9,7 +9,7 @@ class FixedSizeStack { private final int size; private Object[] storage; private int index = 0; - public FixedSizeStack(int size) { + FixedSizeStack(int size) { this.size = size; storage = new Object[size]; } 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 8479f105e..a661798c5 100644 --- a/generics/GenericReading.java +++ b/generics/GenericReading.java @@ -1,11 +1,12 @@ // 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.*; public class GenericReading { - static List apples = Arrays.asList(new Apple()); + static List apples = + Arrays.asList(new Apple()); static List fruit = Arrays.asList(new Fruit()); static T readExact(List list) { return list.get(0); @@ -16,8 +17,8 @@ static void f1() { Fruit f = readExact(fruit); f = readExact(apples); } - // If you have a class, its type is - // established when the class is instantiated: + // A class type is established + // when the class is instantiated: static class Reader { T readExact(List list) { return list.get(0); } } diff --git a/generics/GenericVarargs.java b/generics/GenericVarargs.java index 82a120378..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.*; @@ -17,13 +17,14 @@ public static void main(String[] args) { System.out.println(ls); ls = makeList("A", "B", "C"); System.out.println(ls); - ls = makeList("ABCDEFFHIJKLMNOPQRSTUVWXYZ".split("")); + ls = makeList( + "ABCDEFFHIJKLMNOPQRSTUVWXYZ".split("")); System.out.println(ls); } } /* Output: [A] [A, B, C] -[A, B, C, D, E, F, F, H, I, J, K, L, M, N, O, P, Q, R, S, -T, U, V, W, X, Y, Z] +[A, B, C, D, E, F, F, H, I, J, K, L, M, N, O, P, Q, R, +S, T, U, V, W, X, Y, Z] */ 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 7787d1f42..edf01b7b2 100644 --- a/generics/HijackedInterface.java +++ b/generics/HijackedInterface.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} class Cat extends ComparablePet implements Comparable{ 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 bb01d71ee..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. @@ -9,7 +9,8 @@ class HoldItem { T getItem() { return item; } } -class WithColor2 extends HoldItem { +class WithColor2 +extends HoldItem { WithColor2(T item) { super(item); } java.awt.Color color() { return item.getColor(); } } 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 627e17bc3..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; - public ClassAsFactory(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 1494157c6..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(); } @@ -31,5 +29,6 @@ public static void main(String[] args) { } } /* Output: -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 +1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 +2584 */ 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 484aa809b..f3857515c 100644 --- a/generics/Manipulation.java +++ b/generics/Manipulation.java @@ -1,12 +1,12 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} class Manipulator { private T obj; - public Manipulator(T x) { obj = x; } + Manipulator(T x) { obj = x; } // Error: cannot find symbol: method f(): public void manipulate() { obj.f(); } } diff --git a/generics/Manipulator2.java b/generics/Manipulator2.java index c705b84ed..2d112dc60 100644 --- a/generics/Manipulator2.java +++ b/generics/Manipulator2.java @@ -1,10 +1,10 @@ // 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. class Manipulator2 { private T obj; - public Manipulator2(T x) { obj = x; } + Manipulator2(T x) { obj = x; } public void manipulate() { obj.f(); } } diff --git a/generics/Manipulator3.java b/generics/Manipulator3.java index e2a9878e4..a737a727b 100644 --- a/generics/Manipulator3.java +++ b/generics/Manipulator3.java @@ -1,10 +1,10 @@ // 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. class Manipulator3 { private HasF obj; - public Manipulator3(HasF x) { obj = x; } + Manipulator3(HasF x) { obj = x; } public void manipulate() { obj.f(); } } 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 a5216675b..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.*; @@ -8,7 +8,7 @@ interface TimeStamped { long getStamp(); } class TimeStampedImp implements TimeStamped { private final long timeStamp; - public TimeStampedImp() { + TimeStampedImp() { timeStamp = new Date().getTime(); } @Override @@ -42,10 +42,10 @@ class Mixin extends BasicImp private TimeStamped timeStamp = new TimeStampedImp(); private SerialNumbered serialNumber = new SerialNumberedImp(); - @Override - public long getStamp() { return timeStamp.getStamp(); } - @Override - public long getSerialNumber() { + @Override public long getStamp() { + return timeStamp.getStamp(); + } + @Override public long getSerialNumber() { return serialNumber.getSerialNumber(); } } @@ -64,6 +64,6 @@ public static void main(String[] args) { } } /* Output: -test string 1 1469638250315 1 -test string 2 1469638250317 2 +test string 1 1611503367257 1 +test string 2 1611503367258 2 */ diff --git a/generics/MultipleInterfaceVariants.java b/generics/MultipleInterfaceVariants.java index 95054a4ab..c8a58fdd0 100644 --- a/generics/MultipleInterfaceVariants.java +++ b/generics/MultipleInterfaceVariants.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} package generics; interface Payable {} 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 7df8f464c..9b56a1d95 100644 --- a/generics/NonCovariantGenerics.java +++ b/generics/NonCovariantGenerics.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} import java.util.*; public class NonCovariantGenerics { 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 c2b3c5c40..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. @@ -21,7 +21,8 @@ public static void main(String[] args) { Derived derived = new Derived(); DerivedSetter ds = new DerivedSetter(); ds.set(derived); - ds.set(base); // Compiles: overloaded, not overridden! + // Compiles--overloaded, not overridden!: + ds.set(base); } } /* Output: 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 a16eef03e..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.*; @@ -21,5 +21,6 @@ public static void main(String[] args) { } } /* Output: -brown over fox quick quick dog brown The brown lazy brown +brown over fox quick quick dog brown The brown lazy +brown */ 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 4f66b7e79..1e6dc005f 100644 --- a/generics/ReturnGenericType.java +++ b/generics/ReturnGenericType.java @@ -1,10 +1,10 @@ // 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. class ReturnGenericType { private T obj; - public ReturnGenericType(T x) { obj = x; } + ReturnGenericType(T x) { obj = x; } public T get() { return obj; } } diff --git a/generics/SelfBounding.java b/generics/SelfBounding.java index ccecc9182..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. @@ -22,7 +22,8 @@ class C extends SelfBounded { class D {} // Can't do this: // class E extends SelfBounded {} -// Compile error: Type parameter D is not within its bound +// Compile error: +// Type parameter D is not within its bound // Alas, you can do this, so you cannot force the idiom: class F extends SelfBounded {} diff --git a/generics/SelfBoundingAndCovariantArguments.java b/generics/SelfBoundingAndCovariantArguments.java index 55ffabac2..eefa864d1 100644 --- a/generics/SelfBoundingAndCovariantArguments.java +++ b/generics/SelfBoundingAndCovariantArguments.java @@ -1,16 +1,18 @@ // 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. -interface SelfBoundSetter> { +interface +SelfBoundSetter> { void set(T arg); } interface Setter extends SelfBoundSetter {} public class SelfBoundingAndCovariantArguments { - void testA(Setter s1, Setter s2, SelfBoundSetter sbs) { + void + testA(Setter s1, Setter s2, SelfBoundSetter sbs) { s1.set(s2); //- s1.set(sbs); // error: method set in interface SelfBoundSetter 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 3ce697290..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 @@ -11,16 +11,15 @@ class Product { private final int id; private String description; private double price; - public Product(int idNumber, String descr, double price) { id = idNumber; description = descr; this.price = price; System.out.println(toString()); } - @Override - public String toString() { - return id + ": " + description + ", price: $" + price; + @Override public String toString() { + return id + ": " + description + + ", price: $" + price; } public void priceChange(double change) { price += change; @@ -28,22 +27,22 @@ 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); + Math.round( + rand.nextDouble() * 1000.0) + 0.99); } }; } class Shelf extends ArrayList { - public Shelf(int nProducts) { + Shelf(int nProducts) { Suppliers.fill(this, Product.generator, nProducts); } } class Aisle extends ArrayList { - public Aisle(int nShelves, int nProducts) { + Aisle(int nShelves, int nProducts) { for(int i = 0; i < nShelves; i++) add(new Shelf(nProducts)); } @@ -56,12 +55,12 @@ public class Store extends ArrayList { private ArrayList checkouts = new ArrayList<>(); private Office office = new Office(); - public Store(int nAisles, int nShelves, int nProducts) { + public Store( + int nAisles, int nShelves, int nProducts) { 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) @@ -72,7 +71,7 @@ public String toString() { return result.toString(); } public static void main(String[] args) { - System.out.println(new Store(14, 5, 10)); + System.out.println(new Store(5, 4, 3)); } } /* Output: (First 8 Lines) 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 55a1c6512..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.*; @@ -20,11 +20,12 @@ List processAll() throws E { class Failure1 extends Exception {} -class Processor1 implements Processor { +class Processor1 +implements Processor { static int count = 3; @Override - public void - process(List resultCollector) throws Failure1 { + public void process(List resultCollector) + throws Failure1 { if(count-- > 1) resultCollector.add("Hep!"); else @@ -36,11 +37,12 @@ class Processor1 implements Processor { class Failure2 extends Exception {} -class Processor2 implements Processor { +class Processor2 +implements Processor { static int count = 2; @Override - public void - process(List resultCollector) throws Failure2 { + public void process(List resultCollector) + throws Failure2 { if(count-- == 0) resultCollector.add(47); else { diff --git a/generics/TupleList.java b/generics/TupleList.java index c25a135be..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@107d329, Amphibian@1629346, hi, 47) -(Vehicle@4b9385, Amphibian@1311334, 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 7a0e3c732..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.*; @@ -19,7 +19,8 @@ Tuple4 h() { new Vehicle(), new Amphibian(), "hi", 47); } static - Tuple5 k() { + Tuple5 k() { return new Tuple5<>( new Vehicle(), new Amphibian(), "hi", 47, 11.1); diff --git a/generics/TupleTest2.java b/generics/TupleTest2.java index c12d77efa..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.*; @@ -19,7 +19,8 @@ Tuple4 h() { new Vehicle(), new Amphibian(), "hi", 47); } static - Tuple5 k() { + Tuple5 k() { return tuple(new Vehicle(), new Amphibian(), "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 329768789..3c9073aff 100644 --- a/generics/UseList.java +++ b/generics/UseList.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} import java.util.*; public class UseList { 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 365cace8a..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.*; @@ -33,16 +33,17 @@ public static void main(String[] args) { VIOLET, CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE] set2: [CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, -COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, SAP_GREEN, -YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, BURNT_UMBER] +COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, +SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, +BURNT_UMBER] 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] +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, diff --git a/generics/Wildcards.java b/generics/Wildcards.java index 02643eee8..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 @@ -22,8 +22,9 @@ static void rawArgs(Holder holder, Object arg) { // OK, but type information is lost: Object obj = holder.get(); } - // Similar to rawArgs(), but errors instead of warnings: - static void unboundedArg(Holder holder, Object arg) { + // Like rawArgs(), but errors instead of warnings: + static void + unboundedArg(Holder holder, Object arg) { //- holder.set(arg); // error: method set in class Holder // cannot be applied to given types; @@ -68,7 +69,8 @@ T wildSubtype(Holder holder, T arg) { // wildSubtype(Holder,T#1) // T#2 extends Object declared in class Holder // where CAP#1 is a fresh type-variable: - // CAP#1 extends T#1 from capture of ? extends T#1 + // CAP#1 extends T#1 from + // capture of ? extends T#1 // 1 error return holder.get(); @@ -214,7 +216,7 @@ public static void main(String[] args) { // found: Holder // where T is a type-variable: // T extends Object declared in - // method wildSubtype(Holder,T) + // method wildSubtype(Holder,T) // 2 warnings Long r10 = wildSubtype(qualified, lng); 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 7693c8aa3..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} @@ -14,7 +14,7 @@ class Basic { class Decorator extends Basic { protected Basic basic; - public Decorator(Basic basic) { this.basic = basic; } + Decorator(Basic basic) { this.basic = basic; } @Override public void set(String val) { basic.set(val); } @Override @@ -23,7 +23,7 @@ class Decorator extends Basic { class TimeStamped extends Decorator { private final long timeStamp; - public TimeStamped(Basic basic) { + TimeStamped(Basic basic) { super(basic); timeStamp = new Date().getTime(); } @@ -33,7 +33,7 @@ public TimeStamped(Basic basic) { class SerialNumbered extends Decorator { private static long counter = 1; private final long serialNumber = counter++; - public SerialNumbered(Basic basic) { super(basic); } + SerialNumbered(Basic basic) { super(basic); } public long getSerialNumber() { return serialNumber; } } 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 ea2957243..33922ba10 100644 --- a/generics/watercolors/Watercolors.java +++ b/generics/watercolors/Watercolors.java @@ -1,14 +1,15 @@ // 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; public enum Watercolors { - ZINC, LEMON_YELLOW, MEDIUM_YELLOW, DEEP_YELLOW, ORANGE, - BRILLIANT_RED, CRIMSON, MAGENTA, ROSE_MADDER, VIOLET, - CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, - COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, - SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, + ZINC, LEMON_YELLOW, MEDIUM_YELLOW, DEEP_YELLOW, + ORANGE, BRILLIANT_RED, CRIMSON, MAGENTA, + ROSE_MADDER, VIOLET, CERULEAN_BLUE_HUE, + PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, + PERMANENT_GREEN, VIRIDIAN_HUE, SAP_GREEN, + YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, BURNT_UMBER, PAYNES_GRAY, IVORY_BLACK } diff --git a/gg.bat b/gg.bat deleted file mode 100644 index 174efa64c..000000000 --- a/gg.bat +++ /dev/null @@ -1 +0,0 @@ -gradlew --console plain %* 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 0a6e31bee..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-snapshots/gradle-3.5-20170120000025+0000-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 new file mode 100644 index 000000000..823d6b265 --- /dev/null +++ b/hiding/CreatePackageAccessObject.java @@ -0,0 +1,12 @@ +// hiding/CreatePackageAccessObject.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. +// {WillNotCompile} +import hiding.packageaccess.*; + +public class CreatePackageAccessObject { + public static void main(String[] args) { + new PublicConstructor(); + } +} 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 65e75685f..e0a74371e 100644 --- a/hiding/FullQualification.java +++ b/hiding/FullQualification.java @@ -1,10 +1,11 @@ // 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. public class FullQualification { public static void main(String[] args) { - java.util.ArrayList list = new java.util.ArrayList(); + java.util.ArrayList list = + new java.util.ArrayList(); } } 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 new file mode 100644 index 000000000..250090505 --- /dev/null +++ b/hiding/packageaccess/PublicConstructor.java @@ -0,0 +1,9 @@ +// hiding/packageaccess/PublicConstructor.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 hiding.packageaccess; + +class PublicConstructor { + public PublicConstructor() {} +} 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 6bb267e47..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 @@ -17,6 +17,6 @@ public static void main(String[] args) { } /* Output: length of a = 18 -[55, 193, 361, 461, 429, 368, 200, 22, 207, 288, 128, 51, -89, 309, 278, 498, 361, 20] +[55, 193, 361, 461, 429, 368, 200, 22, 207, 288, 128, +51, 89, 309, 278, 498, 361, 20] */ 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 cabddb70c..5534bccb1 100644 --- a/housekeeping/Demotion.java +++ b/housekeeping/Demotion.java @@ -1,11 +1,13 @@ // 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 public class Demotion { - void f1(double x) { System.out.println("f1(double)"); } + void f1(double x) { + System.out.println("f1(double)"); + } void f2(float x) { System.out.println("f2(float)"); } void f3(long x) { System.out.println("f3(long)"); } void f4(int x) { System.out.println("f4(int)"); } 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 acae8d51b..8927ae50f 100644 --- a/housekeeping/EnumOrder.java +++ b/housekeeping/EnumOrder.java @@ -1,12 +1,13 @@ // 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. public class EnumOrder { public static void main(String[] args) { for(Spiciness s : Spiciness.values()) - System.out.println(s + ", ordinal " + s.ordinal()); + System.out.println( + s + ", ordinal " + s.ordinal()); } } /* Output: diff --git a/housekeeping/ExplicitStatic.java b/housekeeping/ExplicitStatic.java index 1b46002a9..034fbd417 100644 --- a/housekeeping/ExplicitStatic.java +++ b/housekeeping/ExplicitStatic.java @@ -1,8 +1,8 @@ // 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 the "static" clause +// Explicit static initialization with "static" clause class Cup { Cup(int marker) { @@ -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 90ebbae9c..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 @@ -8,15 +8,12 @@ class Mug { Mug(int marker) { System.out.println("Mug(" + marker + ")"); } - void f(int marker) { - System.out.println("f(" + marker + ")"); - } } 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 2e19809aa..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@1db9742 A@106d69c A@52e922 +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 340da66f8..2c1755d41 100644 --- a/housekeeping/OverloadingVarargs2.java +++ b/housekeeping/OverloadingVarargs2.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} public class OverloadingVarargs2 { static void f(float i, Character... args) { 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 2e1261abc..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 d067cf8f1..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 @@ -40,9 +40,9 @@ void f3(int marker) { public class StaticInitialization { public static void main(String[] args) { - System.out.println("Creating new Cupboard() in main"); + System.out.println("main creating new Cupboard()"); new Cupboard(); - System.out.println("Creating new Cupboard() in main"); + System.out.println("main creating new Cupboard()"); new Cupboard(); table.f2(1); cupboard.f3(1); @@ -60,11 +60,11 @@ public static void main(String[] args) { Bowl(3) Cupboard() f1(2) -Creating new Cupboard() in main +main creating new Cupboard() Bowl(3) Cupboard() f1(2) -Creating new Cupboard() in main +main creating new Cupboard() Bowl(3) Cupboard() f1(2) 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 0b15efa04..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@1db9742 A@106d69c A@52e922 +A@19e0bfd A@139a55 A@1db9742 */ diff --git a/housekeeping/VarargType.java b/housekeeping/VarargType.java index 72d8bfdc3..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. @@ -17,7 +17,8 @@ public static void main(String[] args) { f(); g(1); g(); - System.out.println("int[]: " + new int[0].getClass()); + System.out.println("int[]: " + + new int[0].getClass()); } } /* Output: diff --git a/innerclasses/AnonymousConstructor.java b/innerclasses/AnonymousConstructor.java index 25de92a5b..10a6b6433 100644 --- a/innerclasses/AnonymousConstructor.java +++ b/innerclasses/AnonymousConstructor.java @@ -1,11 +1,11 @@ // 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 abstract class Base { - public Base(int i) { + Base(int i) { System.out.println("Base constructor, i = " + i); } public abstract void f(); @@ -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 a510ddda5..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 @@ -11,7 +11,7 @@ public Yolk() { System.out.println("Egg.Yolk()"); } } - public Egg() { + Egg() { System.out.println("New Egg()"); y = new Yolk(); } diff --git a/innerclasses/BigEgg2.java b/innerclasses/BigEgg2.java index 6f8cf4aae..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 @@ -14,7 +14,7 @@ public void f() { } } private Yolk y = new Yolk(); - public Egg2() { System.out.println("New Egg2()"); } + Egg2() { System.out.println("New Egg2()"); } public void insertYolk(Yolk yy) { y = yy; } public void g() { y.f(); } } @@ -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 92d3f7944..3f77dc608 100644 --- a/innerclasses/DotNew.java +++ b/innerclasses/DotNew.java @@ -1,8 +1,8 @@ // 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 the .new syntax +// Creating an inner class directly using .new syntax public class DotNew { public class Inner {} 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 e39a470f4..5ec13cab6 100644 --- a/innerclasses/GreenhouseController.java +++ b/innerclasses/GreenhouseController.java @@ -1,9 +1,8 @@ // 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 -// {java GreenhouseController 5000} import innerclasses.controller.*; public class GreenhouseController { @@ -21,10 +20,8 @@ gc.new WaterOff(800), gc.new ThermostatDay(1400) }; gc.addEvent(gc.new Restart(2000, eventList)); - if(args.length == 1) - gc.addEvent( - new GreenhouseControls.Terminate( - new Integer(args[0]))); + gc.addEvent( + new GreenhouseControls.Terminate(5000)); gc.run(); } } 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 119c1ca93..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 @@ -13,12 +13,11 @@ public class LocalInnerClass { Counter getCounter(final String name) { // A local inner class: class LocalCounter implements Counter { - public LocalCounter() { + LocalCounter() { // 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 48ae8aa18..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 @@ -19,6 +19,7 @@ public static void main(String[] args) { // Must use instance of outer class // to create an instance of the inner class: Parcel3.Contents c = p.new Contents(); - Parcel3.Destination d = p.new Destination("Tasmania"); + Parcel3.Destination d = + p.new Destination("Tasmania"); } } 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 c909d29ce..ee69f61ab 100644 --- a/innerclasses/mui/MultiInterfaces.java +++ b/innerclasses/mui/MultiInterfaces.java @@ -1,8 +1,8 @@ // 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 that a class can implement multiple interfaces +// Two ways a class can implement multiple interfaces // {java innerclasses.mui.MultiInterfaces} package innerclasses.mui; 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 733820e68..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()) + " "; @@ -21,13 +20,15 @@ public int read(CharBuffer cb) { return result.length(); } public static void main(String[] args) { - Scanner s = new Scanner(new AdaptedRandomDoubles(7)); + Scanner s = + new Scanner(new AdaptedRandomDoubles(7)); while(s.hasNextDouble()) System.out.print(s.nextDouble() + " "); } } /* Output: -0.7271157860730044 0.5309454508634242 0.16020656493302599 -0.18847866977771732 0.5166020801268457 0.2678662084200585 +0.7271157860730044 0.5309454508634242 +0.16020656493302599 0.18847866977771732 +0.5166020801268457 0.2678662084200585 0.2613610344283964 */ 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 33edd1cfe..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.*; @@ -30,7 +30,7 @@ public String process(Object input) { class Splitter extends Processor { @Override public String process(Object input) { - // The split() argument divides a String into pieces: + // split() divides a String into pieces: return Arrays.toString(((String)input).split(" ")); } } @@ -40,9 +40,9 @@ public static void apply(Processor p, Object s) { System.out.println("Using Processor " + p.name()); System.out.println(p.process(s)); } - public static final String s = - "Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { + String s = + "We are such stuff as dreams are made on"; apply(new Upcase(), s); apply(new Downcase(), s); apply(new Splitter(), s); @@ -50,10 +50,9 @@ public static void main(String[] args) { } /* Output: Using Processor Upcase -DISAGREEMENT WITH BELIEFS IS BY DEFINITION INCORRECT +WE ARE SUCH STUFF AS DREAMS ARE MADE ON Using Processor Downcase -disagreement with beliefs is by definition incorrect +we are such stuff as dreams are made on Using Processor Splitter -[Disagreement, with, beliefs, is, by, definition, -incorrect] +[We, are, such, stuff, as, dreams, are, made, on] */ diff --git a/interfaces/AttemptToUseBasic.java b/interfaces/AttemptToUseBasic.java index 5b71bc59f..d8e67f72b 100644 --- a/interfaces/AttemptToUseBasic.java +++ b/interfaces/AttemptToUseBasic.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} public class AttemptToUseBasic { Basic b = new Basic(); 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 3d3d5cf99..a22f53dd3 100644 --- a/interfaces/Jim.java +++ b/interfaces/Jim.java @@ -1,20 +1,25 @@ // 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.*; interface Jim1 { - default void jim() { System.out.println("Jim1::jim"); } + default void jim() { + System.out.println("Jim1::jim"); + } } interface Jim2 { - default void jim() { System.out.println("Jim2::jim"); } + default void jim() { + System.out.println("Jim2::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 43af8fda7..ab1c8090f 100644 --- a/interfaces/MICollision.java +++ b/interfaces/MICollision.java @@ -1,15 +1,19 @@ // 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.*; interface Bob1 { - default void bob() { System.out.println("Bob1::bob"); } + default void bob() { + System.out.println("Bob1::bob"); + } } interface Bob2 { - default void bob() { System.out.println("Bob2::bob"); } + default void bob() { + System.out.println("Bob2::bob"); + } } // class Bob implements Bob1, Bob2 {} @@ -22,18 +26,24 @@ class Bob implements Bob1, Bob2 {} */ interface Sam1 { - default void sam() { System.out.println("Sam1::sam"); } + default void sam() { + System.out.println("Sam1::sam"); + } } interface Sam2 { - default void sam(int i) { System.out.println(i * 2); } + default void sam(int i) { + System.out.println(i * 2); + } } -// This works because the argument lists are distinct: +// Works because the argument lists are distinct: class Sam implements Sam1, Sam2 {} interface Max1 { - default void max() { System.out.println("Max1::max"); } + default void max() { + System.out.println("Max1::max"); + } } interface Max2 { 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 ab5cd5144..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.*; @@ -9,7 +9,9 @@ interface One { } interface Two { - default void second() { System.out.println("second"); } + default void second() { + System.out.println("second"); + } } interface Three { 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 ced3f21cb..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.*; @@ -14,7 +14,8 @@ static void main(String[] args) { } } /* Output: -0.7271157860730044 0.5309454508634242 0.16020656493302599 -0.18847866977771732 0.5166020801268457 0.2678662084200585 +0.7271157860730044 0.5309454508634242 +0.16020656493302599 0.18847866977771732 +0.5166020801268457 0.2678662084200585 0.2613610344283964 */ diff --git a/interfaces/RandomStrings.java b/interfaces/RandomStrings.java index 8274acd5f..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 @@ -15,9 +15,10 @@ public class RandomStrings implements Readable { private static final char[] VOWELS = "aeiou".toCharArray(); private int count; - public RandomStrings(int count) { this.count = count; } - @Override - public int read(CharBuffer cb) { + public RandomStrings(int count) { + this.count = count; + } + @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 95f977a02..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} @@ -8,7 +8,7 @@ class FilterAdapter implements Processor { Filter filter; - public FilterAdapter(Filter filter) { + FilterAdapter(Filter filter) { this.filter = filter; } @Override 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 01ec16806..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,10 +8,11 @@ interface StringProcessor extends Processor { @Override - 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] + 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] 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 810bdc5ff..c31cf7f21 100644 --- a/iostreams/BasicFileOutput.java +++ b/iostreams/BasicFileOutput.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {VisuallyInspectOutput} import java.io.*; public class BasicFileOutput { diff --git a/iostreams/BufferedInputFile.java b/iostreams/BufferedInputFile.java index ff7c0caf1..2c5c8ae7f 100644 --- a/iostreams/BufferedInputFile.java +++ b/iostreams/BufferedInputFile.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {VisuallyInspectOutput} import java.io.*; import java.util.stream.*; diff --git a/iostreams/FileOutputShortcut.java b/iostreams/FileOutputShortcut.java index f1d476557..54d3e0597 100644 --- a/iostreams/FileOutputShortcut.java +++ b/iostreams/FileOutputShortcut.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {VisuallyInspectOutput} import java.io.*; public class FileOutputShortcut { diff --git a/iostreams/FormattedMemoryInput.java b/iostreams/FormattedMemoryInput.java index 4e38370c4..f29e75128 100644 --- a/iostreams/FormattedMemoryInput.java +++ b/iostreams/FormattedMemoryInput.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {VisuallyInspectOutput} import java.io.*; public class FormattedMemoryInput { diff --git a/iostreams/MemoryInput.java b/iostreams/MemoryInput.java index 2fc1cc8ab..db5f8d4f9 100644 --- a/iostreams/MemoryInput.java +++ b/iostreams/MemoryInput.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {VisuallyInspectOutput} import java.io.*; public class MemoryInput { 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 692ea4070..a1c939667 100644 --- a/iostreams/TestEOF.java +++ b/iostreams/TestEOF.java @@ -1,9 +1,9 @@ // 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 -// {ValidateByHand} +// {VisuallyInspectOutput} import java.io.*; public class TestEOF { 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/objects/Documentation1.java b/javadoc/Documentation1.java similarity index 77% rename from objects/Documentation1.java rename to javadoc/Documentation1.java index 42d7bfb9a..790f69fd5 100644 --- a/objects/Documentation1.java +++ b/javadoc/Documentation1.java @@ -1,5 +1,5 @@ -// objects/Documentation1.java -// (c)2017 MindView LLC: see Copyright.txt +// javadoc/Documentation1.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. /** A class comment */ diff --git a/objects/Documentation2.java b/javadoc/Documentation2.java similarity index 73% rename from objects/Documentation2.java rename to javadoc/Documentation2.java index db857a29b..397009e4c 100644 --- a/objects/Documentation2.java +++ b/javadoc/Documentation2.java @@ -1,5 +1,5 @@ -// objects/Documentation2.java -// (c)2017 MindView LLC: see Copyright.txt +// javadoc/Documentation2.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/objects/Documentation3.java b/javadoc/Documentation3.java
similarity index 77%
rename from objects/Documentation3.java
rename to javadoc/Documentation3.java
index 582b83468..c48351ea5 100644
--- a/objects/Documentation3.java
+++ b/javadoc/Documentation3.java
@@ -1,7 +1,8 @@
-// objects/Documentation3.java
-// (c)2017 MindView LLC: see Copyright.txt
+// javadoc/Documentation3.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.
+
 /** You can even insert a list:
  * 
    *
  1. Item one @@ -9,4 +10,5 @@ *
  2. Item three *
*/ + public class Documentation3 {} diff --git a/objects/HelloDateDoc.java b/javadoc/HelloDateDoc.java similarity index 85% rename from objects/HelloDateDoc.java rename to javadoc/HelloDateDoc.java index 93f326dd3..b6ebe8b47 100644 --- a/objects/HelloDateDoc.java +++ b/javadoc/HelloDateDoc.java @@ -1,5 +1,5 @@ -// objects/HelloDateDoc.java -// (c)2017 MindView LLC: see Copyright.txt +// javadoc/HelloDateDoc.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.*; @@ -22,5 +22,5 @@ public static void main(String[] args) { } /* Output: Hello, it's: -Wed Jul 27 10:50:45 MDT 2016 +Sun Jan 24 08:49:10 MST 2021 */ diff --git a/lowlevel/AtomicEvenProducer.java b/lowlevel/AtomicEvenProducer.java index a965e0011..d45592c93 100644 --- a/lowlevel/AtomicEvenProducer.java +++ b/lowlevel/AtomicEvenProducer.java @@ -1,15 +1,14 @@ // 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 are occasionally useful in regular code +// Atomic classes: occasionally useful in regular code import java.util.concurrent.atomic.*; 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 d845bf366..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.*; @@ -14,30 +14,26 @@ class DelayedTask implements Runnable, Delayed { private final long trigger; protected static List sequence = new ArrayList<>(); - public DelayedTask(int delayInMilliseconds) { + DelayedTask(int delayInMilliseconds) { delta = delayInMilliseconds; trigger = System.nanoTime() + 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); } @@ -45,9 +41,8 @@ public String summary() { return String.format("(%d:%d)", id, delta); } public static class EndTask extends DelayedTask { - public EndTask(int delay) { super(delay); } - @Override - public void run() { + EndTask(int delay) { super(delay); } + @Override public void run() { sequence.forEach(dt -> System.out.println(dt.summary())); } @@ -70,14 +65,12 @@ public class DelayQueueDemo { } } /* Output: -[128] Task 12 [429] Task 6 [551] Task 13 - [555] Task 2 [693] Task 3 [809] Task 15 - [961] Task 5 [1258] Task 1 [1258] Task 20 - [1520] Task 19 [1861] Task 4 [1998] T -ask 17 [2200] Task 8 [2207] Task 10 [2288] -Task 11 [2522] Task 9 [2589] Task 14 -[2861] Task 18 [2868] Task 7 [3278] -Task 16 (0:4000) +[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] +Task 9 [2589] Task 14 [2861] Task 18 [2868] Task 7 +[3278] Task 16 (0:4000) (1:1258) (2:555) (3:693) 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 d51ec8380..67774aa24 100644 --- a/lowlevel/EvenProducer.java +++ b/lowlevel/EvenProducer.java @@ -1,14 +1,14 @@ // 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 +// {VisuallyInspectOutput} public class EvenProducer extends IntGenerator { private int currentEvenValue = 0; - @Override - public int next() { - ++currentEvenValue; // [1] + @Override public int next() { + ++currentEvenValue; // [1] ++currentEvenValue; return currentEvenValue; } @@ -17,10 +17,9 @@ public static void main(String[] args) { } } /* Output: -1563 not even! -1573 not even! -1571 not even! -1569 not even! -1567 not even! -1565 not even! +419 not even! +425 not even! +423 not even! +421 not even! +417 not even! */ diff --git a/lowlevel/ExceptionThread.java b/lowlevel/ExceptionThread.java index c9f7f82a4..9fee108c9 100644 --- a/lowlevel/ExceptionThread.java +++ b/lowlevel/ExceptionThread.java @@ -1,14 +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. -// {ValidateByHand} // {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) { @@ -18,3 +16,14 @@ public static void main(String[] args) { es.shutdown(); } } +/* Output: +___[ Error Output ]___ +Exception in thread "pool-1-thread-1" +java.lang.RuntimeException + at ExceptionThread.run(ExceptionThread.java:7) + at java.util.concurrent.ThreadPoolExecutor.runW +orker(ThreadPoolExecutor.java:1142) + at java.util.concurrent.ThreadPoolExecutor$Work +er.run(ThreadPoolExecutor.java:617) + at java.lang.Thread.run(Thread.java:745) +*/ 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 0a1f9d1d7..efda2778e 100644 --- a/lowlevel/NaiveExceptionHandling.java +++ b/lowlevel/NaiveExceptionHandling.java @@ -1,8 +1,7 @@ // 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. -// {ValidateByHand} // {ThrowsException} import java.util.concurrent.*; @@ -20,3 +19,14 @@ public static void main(String[] args) { } } } +/* Output: +___[ Error Output ]___ +Exception in thread "pool-1-thread-1" +java.lang.RuntimeException + at ExceptionThread.run(ExceptionThread.java:7) + at java.util.concurrent.ThreadPoolExecutor.runW +orker(ThreadPoolExecutor.java:1142) + at java.util.concurrent.ThreadPoolExecutor$Work +er.run(ThreadPoolExecutor.java:617) + at java.lang.Thread.run(Thread.java:745) +*/ diff --git a/lowlevel/NotAtomic.java b/lowlevel/NotAtomic.java index ab9577a99..00a1b0102 100644 --- a/lowlevel/NotAtomic.java +++ b/lowlevel/NotAtomic.java @@ -1,8 +1,10 @@ // 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 { int i; @@ -17,28 +19,31 @@ 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(); Code: 0: aload_0 1: dup - 2: getfield #2 // Field i:I + 2: getfield #2 // Field +i:I 5: iconst_1 6: iadd - 7: putfield #2 // Field i:I + 7: putfield #2 // Field +i:I 10: return void f2(); Code: 0: aload_0 1: dup - 2: getfield #2 // Field i:I + 2: getfield #2 // Field +i:I 5: iconst_3 6: iadd - 7: putfield #2 // Field i:I + 7: putfield #2 // Field +i:I 10: return } */ 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 93664a663..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.*; @@ -15,17 +15,15 @@ class Prioritized implements Comparable { private final int priority; private static List sequence = new CopyOnWriteArrayList<>(); - public Prioritized(int priority) { + Prioritized(int priority) { 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); } @@ -38,7 +36,7 @@ public void displaySequence() { } } public static class EndSentinel extends Prioritized { - public EndSentinel() { super(-1); } + EndSentinel() { super(-1); } } } @@ -48,11 +46,10 @@ class Producer implements Runnable { private SplittableRandom rand = new SplittableRandom(seed.getAndAdd(10)); private Queue queue; - public Producer(Queue q) { + 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)) @@ -65,12 +62,10 @@ class Consumer implements Runnable { private PriorityBlockingQueue q; private SplittableRandom rand = new SplittableRandom(47); - public Consumer(PriorityBlockingQueue q) { this.q = q; } - @Override - public void run() { + @Override public void run() { while(true) { try { Prioritized pt = q.take(); @@ -109,11 +104,11 @@ public static void main(String[] args) { [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 @@ -130,10 +125,10 @@ public static void main(String[] args) { [0] Prioritized 14 [0] Prioritized 21 [-1] Prioritized 28 -(0:17)(2:12)(1:15)(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 19e82ca7f..70d21454e 100644 --- a/lowlevel/SafeReturn.java +++ b/lowlevel/SafeReturn.java @@ -1,14 +1,14 @@ // 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.*; import java.util.concurrent.*; -import onjava.TimedAbort; 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 d19b8f6ba..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: 4119 +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 a76a62b56..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(); @@ -38,13 +37,12 @@ public void method() { class Caller implements Runnable { private Guarded g; - public Caller(Guarded g) { this.g = g; } + Caller(Guarded g) { this.g = g; } private AtomicLong successfulCalls = 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: --> 152 --> 152 --> 153 --> 153 -CriticalSection: 610 --> 44 --> 28 --> 62 --> 24 -SynchronizedMethod: 158 +-> 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 2c38fc5c7..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.*; @@ -13,5 +13,5 @@ public static void main(String[] args) { } /* Output: Napping for 4 -TimedAbort 1 +TimedAbort 1.0 */ diff --git a/lowlevel/ThreadSize.java b/lowlevel/ThreadSize.java index 522ff717e..ff6f91fb5 100644 --- a/lowlevel/ThreadSize.java +++ b/lowlevel/ThreadSize.java @@ -1,15 +1,14 @@ // 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. -// {ValidateByHand} +// {ExcludeFromGradle} Takes a long time or hangs import java.util.concurrent.*; import onjava.Nap; 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 42a763574..964cc3af4 100644 --- a/lowlevel/UnsafeReturn.java +++ b/lowlevel/UnsafeReturn.java @@ -1,14 +1,14 @@ // 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.*; import java.util.concurrent.*; -import onjava.TimedAbort; public class UnsafeReturn extends IntTestable { private int i = 0; public int getAsInt() { return i; } + @Override public synchronized void evenIncrement() { i++; i++; } @@ -17,5 +17,5 @@ public static void main(String[] args) { } } /* Output: -failed with: 21 +failed with: 39 */ diff --git a/lowlevel/WorkStealingPool.java b/lowlevel/WorkStealingPool.java index a24f3722f..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()); } @@ -31,11 +30,11 @@ public static void main(String[] args) ForkJoinPool-1-worker-1 ForkJoinPool-1-worker-2 ForkJoinPool-1-worker-1 -ForkJoinPool-1-worker-1 -ForkJoinPool-1-worker-4 -ForkJoinPool-1-worker-1 ForkJoinPool-1-worker-3 -ForkJoinPool-1-worker-5 +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/network/ChatterClient.java b/network/ChatterClient.java deleted file mode 100644 index 78b51f311..000000000 --- a/network/ChatterClient.java +++ /dev/null @@ -1,49 +0,0 @@ -// network/ChatterClient.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. -// Starts multiple clients, each of which sends datagrams. -import java.net.*; -import java.io.*; - -public class ChatterClient implements Runnable { - private InetAddress host; - private byte[] buf = new byte[1000]; - private DatagramPacket dp = - new DatagramPacket(buf, buf.length); - private static int counter = 0; - private int id = counter++; - - public ChatterClient(InetAddress host) { - this.host = host; - System.out.println( - "ChatterClient #" + id + " starting"); - } - public void sendAndEcho(String msg) { - try ( - // Auto-assign port number: - DatagramSocket s = new DatagramSocket(); - ) { - // Make and send a datagram: - s.send(Dgram.toDatagram( - msg, host, ChatterServer.INPORT)); - // Block until it echoes back: - s.receive(dp); - // Display the echoed contents: - String rcvd = "Client #" + id + - ", rcvd from " + - dp.getAddress() + ", " + - dp.getPort() + ": " + - Dgram.toString(dp); - System.out.println(rcvd); - } catch(IOException e) { - throw new RuntimeException(e); - } - } - @Override - public void run() { - for(int i = 0; i < 10; i++) - sendAndEcho( - "Client #" + id + ", message #" + i); - } -} diff --git a/network/ChatterServer.java b/network/ChatterServer.java deleted file mode 100644 index 11b3c6b14..000000000 --- a/network/ChatterServer.java +++ /dev/null @@ -1,41 +0,0 @@ -// network/ChatterServer.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. -// A server that echoes datagrams -import java.net.*; -import java.io.*; - -public class ChatterServer implements Runnable { - static final int INPORT = 1711; - private byte[] buf = new byte[1000]; - private DatagramPacket dp = - new DatagramPacket(buf, buf.length); - @Override - public void run() { - // Can listen & send on the same socket: - try ( - DatagramSocket socket = new DatagramSocket(INPORT) - ) { - System.out.println("Server started"); - while(true) { - // Block until a datagram appears: - socket.receive(dp); - String rcvd = Dgram.toString(dp) + - ", from address: " + dp.getAddress() + - ", port: " + dp.getPort(); - System.out.println(rcvd); - String echoString = - "Echoed: " + rcvd; - // Extract address and port from received - // datagram and send it back there: - DatagramPacket echo = - Dgram.toDatagram(echoString, - dp.getAddress(), dp.getPort()); - socket.send(echo); - } - } catch(IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/network/Dgram.java b/network/Dgram.java deleted file mode 100644 index 9fbd774d1..000000000 --- a/network/Dgram.java +++ /dev/null @@ -1,19 +0,0 @@ -// network/Dgram.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. -// Converts between Strings and DataGramPackets -import java.net.*; - -public class Dgram { - public static DatagramPacket toDatagram( - String s, InetAddress destIA, int destPort) { - byte[] buf = s.getBytes(); - return new DatagramPacket(buf, buf.length, - destIA, destPort); - } - public static String toString(DatagramPacket p) { - return - new String(p.getData(), 0, p.getLength()); - } -} diff --git a/network/Local.java b/network/Local.java deleted file mode 100644 index 35202670e..000000000 --- a/network/Local.java +++ /dev/null @@ -1,15 +0,0 @@ -// network/Local.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.net.*; - -public class Local { - public static InetAddress host() { - try { - return InetAddress.getByName(null); - } catch(UnknownHostException e) { - throw new RuntimeException(e); - } - } -} diff --git a/network/LocalHost.java b/network/LocalHost.java deleted file mode 100644 index 487680a60..000000000 --- a/network/LocalHost.java +++ /dev/null @@ -1,27 +0,0 @@ -// network/LocalHost.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 local loopback IP address -import java.net.*; - -public class LocalHost { - public static void - main(String[] args) throws Exception { - InetAddress - local1 = InetAddress.getByName(null), - local2 = InetAddress.getByName("localhost"), - local3 = InetAddress.getByName("127.0.0.1"), - local4 = InetAddress.getLoopbackAddress(); - System.out.println(local1); - System.out.println(local2); - System.out.println(local3); - System.out.println(local4); - } -} -/* Output: -localhost/127.0.0.1 -localhost/127.0.0.1 -/127.0.0.1 -localhost/127.0.0.1 -*/ diff --git a/network/MultiServer.java b/network/MultiServer.java deleted file mode 100644 index f538ccb57..000000000 --- a/network/MultiServer.java +++ /dev/null @@ -1,29 +0,0 @@ -// network/MultiServer.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. -// Uses concurrency to handle any number of clients. -import java.io.*; -import java.net.*; -import java.util.concurrent.*; - -public class MultiServer implements Runnable { - private final int port; - public MultiServer(int port) { - this.port = port; - } - @Override - public void run() { - System.out.println("Server: Running"); - try ( - ServerSocket ss = new ServerSocket(port) - ) { - System.out.println("Server: " + ss); - for(int i = 0; i < 10; i++) - CompletableFuture - .runAsync(new SimpleServer(ss)); - } catch(IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/network/SimpleClient.java b/network/SimpleClient.java deleted file mode 100644 index 0cd88845b..000000000 --- a/network/SimpleClient.java +++ /dev/null @@ -1,51 +0,0 @@ -// network/SimpleClient.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. -// Sends to the server, reads from the server -import java.net.*; -import java.io.*; -import java.util.concurrent.atomic.*; - -public class SimpleClient implements Runnable { - public final int port; - private static AtomicInteger idcount = - new AtomicInteger(0); - private final int id = idcount.getAndIncrement(); - private InetAddress host; - public SimpleClient(InetAddress host, int port) { - this.host = host; - this.port = port; - } - @Override - public String toString() { - return "Client[" + id + "]: "; - } - @Override - public void run() { - System.out.println(this + "Running"); - try( - Socket socket = new Socket(host, port); - BufferedReader in = - new BufferedReader( - new InputStreamReader( - socket.getInputStream())); - PrintWriter out = - new PrintWriter( - new BufferedWriter( - new OutputStreamWriter( - // Enable auto-flush: - socket.getOutputStream())), true); - ) { - System.out.println(this.toString() + socket); - for(int i = 0; i < 10; i ++) { - out.println(this + "(*" + i + "*)"); - System.out.println(this + - "Received '" + in.readLine() + "'"); - } - out.println("END"); - } catch(IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/network/SimpleServer.java b/network/SimpleServer.java deleted file mode 100644 index 56e0cf36d..000000000 --- a/network/SimpleServer.java +++ /dev/null @@ -1,47 +0,0 @@ -// network/SimpleServer.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. -// Echoes what the client sends. -import java.io.*; -import java.net.*; - -public class SimpleServer implements Runnable { - private ServerSocket ss; - public SimpleServer(ServerSocket ss) { - this.ss = ss; - } - @Override - public String toString() { return "Server: "; } - @Override - public void run() { - System.out.println(this + "Running"); - try ( - // Blocks until a connection occurs: - Socket socket = ss.accept(); - BufferedReader in = - new BufferedReader( - new InputStreamReader( - socket.getInputStream())); - PrintWriter out = - new PrintWriter( - new BufferedWriter( - new OutputStreamWriter( - // Boolean enables auto-flush: - socket.getOutputStream())), true) - ) { - System.out.println(this.toString() + socket); - in.lines().anyMatch(message -> { - if(message.equals("END")) { - System.out.println(this + - "Received END. Closing Socket."); - return true; - } - out.println(this + message); - return false; - }); - } catch(IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/network/TestChatter.java b/network/TestChatter.java deleted file mode 100644 index b801bf7bb..000000000 --- a/network/TestChatter.java +++ /dev/null @@ -1,18 +0,0 @@ -// network/TestChatter.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.concurrent.*; -import java.net.*; -import onjava.Nap; - -public class TestChatter { - public static void main(String[] args) { - CompletableFuture.runAsync( - new ChatterServer()); - CompletableFuture.runAsync( - new ChatterClient(Local.host())); - new Nap(1); - // No exceptions means success - } -} diff --git a/network/TestMultiServer.java b/network/TestMultiServer.java deleted file mode 100644 index cd68e23c4..000000000 --- a/network/TestMultiServer.java +++ /dev/null @@ -1,22 +0,0 @@ -// network/TestMultiServer.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.net.*; -import java.util.concurrent.*; -import onjava.Nap; - -public class TestMultiServer { - public static final int port = 8080; - public static void main(String[] args) { - CompletableFuture.runAsync( - new MultiServer(port)); - new Nap(1); // Let the server get started - for(int i = 0; i < 10; i++) { - CompletableFuture.runAsync( - new SimpleClient(Local.host(), port)); - } - new Nap(4); - // No exceptions mean success - } -} diff --git a/network/TestSimpleServer.java b/network/TestSimpleServer.java deleted file mode 100644 index 99f3ca55c..000000000 --- a/network/TestSimpleServer.java +++ /dev/null @@ -1,28 +0,0 @@ -// network/TestSimpleServer.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.io.*; -import java.net.*; -import java.util.concurrent.*; -import onjava.Nap; - -public class TestSimpleServer { - // Choose a port outside of the range 1-1024: - public static final int port = 8080; - public static void main(String[] args) { - try ( - ServerSocket ss = - new ServerSocket(port) - ) { - CompletableFuture.runAsync( - new SimpleServer(ss)); - CompletableFuture.runAsync( - new SimpleClient(Local.host(), port)); - new Nap(1); - // Success if no exceptions happen - } catch(IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/network/WhoAmI.java b/network/WhoAmI.java deleted file mode 100644 index c636a7ccc..000000000 --- a/network/WhoAmI.java +++ /dev/null @@ -1,19 +0,0 @@ -// network/WhoAmI.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. -// Discovers your machine name and network address. -import java.net.*; - -public class WhoAmI { - public static void - main(String[] args) throws UnknownHostException { - InetAddress whoami = InetAddress.getLocalHost(); - System.out.println(whoami.getHostName()); - System.out.println(whoami.getHostAddress()); - } -} -/* Output: -MindviewToshibaLaptop -192.168.0.104 -*/ diff --git a/newio/AvailableCharSets.java b/newio/AvailableCharSets.java index 64c0e3a92..bb60164c9 100644 --- a/newio/AvailableCharSets.java +++ b/newio/AvailableCharSets.java @@ -1,9 +1,8 @@ // 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 -// {ValidateByHand} // CI has trouble import java.nio.charset.*; import java.util.*; @@ -33,10 +32,10 @@ public static void main(String[] args) { EUC-JP: csEUCPkdFmtjapanese, x-euc-jp, eucjis, 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 +EUC-KR: ksc5601-1987, csEUCKR, ksc5601_1987, ksc5601, +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: gb2312, euc-cn, x-EUC-CN, euccn, EUC_CN, +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 92a4df674..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); @@ -53,8 +52,8 @@ public void run() { } } /* Output: -Locked: 0 to 50331647 Locked: 75497471 to 113246206 +Locked: 0 to 50331647 Released: 75497471 to 113246206 Released: 0 to 50331647 */ diff --git a/newio/MappedIO.java b/newio/MappedIO.java index 367f56b59..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.*; @@ -12,7 +13,7 @@ public class MappedIO { private static int numOfUbuffInts = 100_000; private abstract static class Tester { private String name; - public Tester(String name) { + Tester(String name) { this.name = name; } public void runTest() { @@ -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() @@ -135,10 +130,10 @@ public static void main(String[] args) { } } /* Output: -Stream Write: 0.269 -Mapped Write: 0.022 -Stream Read: 0.262 -Mapped Read: 0.010 -Stream Read/Write: 1.620 -Mapped Read/Write: 0.007 +Stream Write: 0.615 +Mapped Write: 0.050 +Stream Read: 0.577 +Mapped Read: 0.015 +Stream Read/Write: 4.069 +Mapped Read/Write: 0.013 */ 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 8ba4a478e..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.*; @@ -58,8 +58,8 @@ public static void main(String[] args) { } } /* Output: -Byte Buffer 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, -6 -> 0, 7 -> 97, +Byte Buffer 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0, 5 +-> 0, 6 -> 0, 7 -> 97, Char Buffer 0 -> NUL, 1 -> NUL, 2 -> NUL, 3 -> a, Float Buffer 0 -> 0.0, 1 -> 1.36E-43, Int Buffer 0 -> 0, 1 -> 97, 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 73f00f2e5..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 -(x86)\Java\jdk1.8.0_... -java.vm.version=25.102-b14 +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) Client VM +java.vm.name=OpenJDK Client VM file.encoding.pkg=sun.io user.script= user.country=US @@ -28,11 +28,11 @@ 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_102-b14 +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 -(x86)\Java\jdk1.8.0_... +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 4cfca583a..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} @@ -27,10 +27,11 @@ static void interfaces(Class type) { static void difference(Class superset, Class subset) { System.out.print(superset.getSimpleName() + - " extends " + subset.getSimpleName() + ", adds: "); + " extends " + subset.getSimpleName() + + ", adds: "); Set comp = Sets.difference( methodSet(superset), methodSet(subset)); - comp.removeAll(object); // Don't show 'Object' methods + comp.removeAll(object); // Ignore 'Object' methods System.out.println(comp); interfaces(superset); } @@ -65,23 +66,27 @@ public static void main(String[] args) { HashSet extends Set, adds: [] Interfaces in HashSet: [Set, Cloneable, Serializable] LinkedHashSet extends HashSet, adds: [] -Interfaces in LinkedHashSet: [Set, Cloneable, Serializable] -TreeSet extends Set, adds: [headSet, descendingIterator, -descendingSet, pollLast, subSet, floor, tailSet, ceiling, -last, lower, comparator, pollFirst, first, higher] +Interfaces in LinkedHashSet: [Set, Cloneable, +Serializable] +TreeSet extends Set, adds: [headSet, +descendingIterator, descendingSet, pollLast, subSet, +floor, tailSet, ceiling, last, lower, comparator, +pollFirst, first, higher] Interfaces in TreeSet: [NavigableSet, Cloneable, Serializable] -List extends Collection, adds: [replaceAll, get, indexOf, -subList, set, sort, lastIndexOf, listIterator] +List extends Collection, adds: [replaceAll, get, +indexOf, subList, set, sort, lastIndexOf, listIterator] Interfaces in List: [Collection] -ArrayList extends List, adds: [trimToSize, ensureCapacity] -Interfaces in ArrayList: [List, RandomAccess, Cloneable, -Serializable] -LinkedList extends List, adds: [offerFirst, poll, getLast, -offer, getFirst, removeFirst, element, -removeLastOccurrence, peekFirst, peekLast, push, pollFirst, -removeFirstOccurrence, descendingIterator, pollLast, -removeLast, pop, addLast, peek, offerLast, addFirst] +ArrayList extends List, adds: [trimToSize, +ensureCapacity] +Interfaces in ArrayList: [List, RandomAccess, +Cloneable, Serializable] +LinkedList extends List, adds: [offerFirst, poll, +getLast, offer, getFirst, removeFirst, element, +removeLastOccurrence, peekFirst, peekLast, push, +pollFirst, removeFirstOccurrence, descendingIterator, +pollLast, removeLast, pop, addLast, peek, offerLast, +addFirst] Interfaces in LinkedList: [List, Deque, Cloneable, Serializable] Queue extends Collection, adds: [poll, peek, offer, @@ -89,24 +94,24 @@ public static void main(String[] args) { Interfaces in Queue: [Collection] PriorityQueue extends Queue, adds: [comparator] Interfaces in PriorityQueue: [Serializable] -Map: [clear, compute, computeIfAbsent, computeIfPresent, -containsKey, containsValue, entrySet, equals, forEach, get, -getOrDefault, hashCode, isEmpty, keySet, merge, put, -putAll, putIfAbsent, remove, replace, replaceAll, size, -values] +Map: [clear, compute, computeIfAbsent, +computeIfPresent, containsKey, containsValue, entrySet, +equals, forEach, get, getOrDefault, hashCode, isEmpty, +keySet, merge, put, putAll, putIfAbsent, remove, +replace, replaceAll, size, values] HashMap extends Map, adds: [] Interfaces in HashMap: [Map, Cloneable, Serializable] LinkedHashMap extends HashMap, adds: [] Interfaces in LinkedHashMap: [Map] -SortedMap extends Map, adds: [lastKey, subMap, comparator, -firstKey, headMap, tailMap] +SortedMap extends Map, adds: [lastKey, subMap, +comparator, firstKey, headMap, tailMap] Interfaces in SortedMap: [Map] TreeMap extends Map, adds: [descendingKeySet, -navigableKeySet, higherEntry, higherKey, floorKey, subMap, -ceilingKey, pollLastEntry, firstKey, lowerKey, headMap, -tailMap, lowerEntry, ceilingEntry, descendingMap, -pollFirstEntry, lastKey, firstEntry, floorEntry, -comparator, lastEntry] +navigableKeySet, higherEntry, higherKey, floorKey, +subMap, ceilingKey, pollLastEntry, firstKey, lowerKey, +headMap, tailMap, lowerEntry, ceilingEntry, +descendingMap, pollFirstEntry, lastKey, firstEntry, +floorEntry, comparator, lastEntry] Interfaces in TreeMap: [NavigableMap, Cloneable, Serializable] */ diff --git a/onjava/ConvertTo.java b/onjava/ConvertTo.java index c6d430166..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; @@ -57,7 +57,7 @@ static double[] primitive(Double[] in) { static Boolean[] boxed(boolean[] in) { Boolean[] result = new Boolean[in.length]; for(int i = 0; i < in.length; i++) - result[i] = in[i]; // Autboxing + result[i] = in[i]; // Autoboxing return result; } static Character[] boxed(char[] in) { diff --git a/onjava/Count.java b/onjava/Count.java index f8c326494..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 @@ -9,11 +9,10 @@ import static onjava.ConvertTo.*; public interface Count { - public static class Boolean + 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); } @@ -27,7 +26,7 @@ public java.lang.Boolean[] array(int sz) { return result; } } - public static class Pboolean { + class Pboolean { private boolean b = true; public boolean get() { b = !b; @@ -38,7 +37,7 @@ public boolean[] array(int sz) { return primitive(new Boolean().array(sz)); } } - public static class Byte + class Byte implements Supplier { private byte b; @Override @@ -53,7 +52,7 @@ public java.lang.Byte[] array(int sz) { return result; } } - public static class Pbyte { + class Pbyte { private byte b; public byte get() { return b++; } public byte get(int n) { return get(); } @@ -63,11 +62,10 @@ public byte[] array(int sz) { } char[] CHARS = "abcdefghijklmnopqrstuvwxyz".toCharArray(); - public static class Character + 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]; } @@ -81,7 +79,7 @@ public java.lang.Character[] array(int sz) { return result; } } - public static class Pchar { + class Pchar { private int i; public char get() { i = (i + 1) % CHARS.length; @@ -92,7 +90,7 @@ public char[] array(int sz) { return primitive(new Character().array(sz)); } } - public static class Short + class Short implements Supplier { short s; @Override @@ -107,7 +105,7 @@ public java.lang.Short[] array(int sz) { return result; } } - public static class Pshort { + class Pshort { short s; public short get() { return s++; } public short get(int n) { return get(); } @@ -115,7 +113,7 @@ public short[] array(int sz) { return primitive(new Short().array(sz)); } } - public static class Integer + class Integer implements Supplier { int i; @Override @@ -130,7 +128,7 @@ public java.lang.Integer[] array(int sz) { return result; } } - public static class Pint implements IntSupplier { + class Pint implements IntSupplier { int i; public int get() { return i++; } public int get(int n) { return get(); } @@ -140,7 +138,7 @@ public int[] array(int sz) { return primitive(new Integer().array(sz)); } } - public static class Long + class Long implements Supplier { private long l; @Override @@ -155,7 +153,6 @@ public java.lang.Long[] array(int sz) { return result; } } - public static class Plong implements LongSupplier { private long l; public long get() { return l++; } @@ -166,11 +163,10 @@ public long[] array(int sz) { return primitive(new Long().array(sz)); } } - public class Float + 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) { @@ -183,7 +179,7 @@ public java.lang.Float[] array(int sz) { return result; } } - public class Pfloat { + class Pfloat { private int i; public float get() { return i++; } public float get(int n) { return get(); } @@ -191,11 +187,10 @@ public float[] array(int sz) { return primitive(new Float().array(sz)); } } - public class Double + 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) { @@ -208,7 +203,7 @@ public java.lang.Double[] array(int sz) { return result; } } - public class Pdouble implements DoubleSupplier { + class Pdouble implements DoubleSupplier { private int i; public double get() { return i++; } public double get(int n) { return get(); } diff --git a/onjava/CountMap.java b/onjava/CountMap.java index 71fe527ce..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); } } @@ -58,15 +52,15 @@ public Set> entrySet() { .toCollection(LinkedHashSet::new)); } public static void main(String[] args) { - final int LIM = 6; + final int size = 6; CountMap cm = new CountMap(60); System.out.println(cm); System.out.println(cm.get(500)); cm.values().stream() - .limit(LIM) + .limit(size) .forEach(System.out::println); System.out.println(); - new Random(47).ints(LIM, 0, 1000) + new Random(47).ints(size, 0, 1000) .mapToObj(cm::get) .forEach(System.out::println); } diff --git a/onjava/CountingIntegerList.java b/onjava/CountingIntegerList.java index f55aa043c..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); @@ -28,7 +26,7 @@ public static void main(String[] args) { } } /* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] 500 */ diff --git a/onjava/Countries.java b/onjava/Countries.java index fc82676dc..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,21 +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() { return DATA[index][1]; } - @Override - public String setValue(String value) { + @Override public String getValue() { + return DATA[index][1]; + } + @Override public String setValue(String value) { throw new UnsupportedOperationException(); } } @@ -249,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 @@ -264,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(); } @@ -311,7 +305,8 @@ public static void main(String[] args) { System.out.println(capitals(10)); System.out.println(names(10)); System.out.println(new HashMap<>(capitals(3))); - System.out.println(new LinkedHashMap<>(capitals(3))); + System.out.println( + new LinkedHashMap<>(capitals(3))); System.out.println(new TreeMap<>(capitals(3))); System.out.println(new Hashtable<>(capitals(3))); System.out.println(new HashSet<>(names(6))); @@ -327,16 +322,22 @@ public static void main(String[] args) { BOTSWANA=Gaberone, BURKINA FASO=Ouagadougou, BURUNDI=Bujumbura, CAMEROON=Yaounde, CAPE VERDE=Praia, CENTRAL AFRICAN REPUBLIC=Bangui, CHAD=N'djamena} -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, -CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, CHAD] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN +REPUBLIC, CHAD] {BENIN=Porto-Novo, ANGOLA=Luanda, ALGERIA=Algiers} {ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo} {ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo} {ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo} -[BENIN, BOTSWANA, ANGOLA, BURKINA FASO, ALGERIA, BURUNDI] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[BENIN, BOTSWANA, ANGOLA, BURKINA FASO, ALGERIA, +BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, +BURUNDI] Brasilia */ 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 0f773983c..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 @@ -189,7 +189,7 @@ public static Integer rgb(String colorName) { public static void show(Map.Entry e) { System.out.format( - "0x%06X: %s\n", e.getKey(), e.getValue()); + "0x%06X: %s%n", e.getKey(), e.getValue()); } public static void show(Map m, int count) { @@ -224,12 +224,13 @@ void showInv(Map m, int count) { .limit(count) .forEach(e -> System.out.format( - "%-20s 0x%06X\n", e.getKey(), e.getValue())); + "%-20s 0x%06X%n", e.getKey(), e.getValue())); } public static void showInv(Map m) { showInv(m, m.size()); } public static void border() { - System.out.println("------------------------------"); + System.out.println( + "******************************"); } } 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 353062b35..af9d5e2e8 100644 --- a/onjava/ProcessFiles.java +++ b/onjava/ProcessFiles.java @@ -1,9 +1,7 @@ // 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. -// {ValidateByHand} -// {java onjava.ProcessFiles} package onjava; import java.io.*; import java.nio.file.*; @@ -47,9 +45,4 @@ public void start(String[] args) { .filter(matcher::matches) .forEach(p -> strategy.process(p.toFile())); } - // Demonstration of how to use it: - public static void main(String[] args) { - new ProcessFiles(file -> System.out.println(file), - "java").start(args); - } } diff --git a/onjava/Rand.java b/onjava/Rand.java index 79d42ce69..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 @@ -10,11 +10,10 @@ public interface Rand { int MOD = 10_000; - public static class Boolean + 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) { @@ -27,16 +26,15 @@ public java.lang.Boolean[] array(int sz) { return result; } } - public static class Pboolean { + class Pboolean { public boolean[] array(int sz) { return primitive(new Boolean().array(sz)); } } - public static class Byte + 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) { @@ -49,16 +47,15 @@ public java.lang.Byte[] array(int sz) { return result; } } - public static class Pbyte { + class Pbyte { public byte[] array(int sz) { return primitive(new Byte().array(sz)); } } - public static class Character + 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) { @@ -71,16 +68,15 @@ public java.lang.Character[] array(int sz) { return result; } } - public static class Pchar { + class Pchar { public char[] array(int sz) { return primitive(new Character().array(sz)); } } - public static class Short + 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) { @@ -93,16 +89,15 @@ public java.lang.Short[] array(int sz) { return result; } } - public static class Pshort { + class Pshort { public short[] array(int sz) { return primitive(new Short().array(sz)); } } - public static class Integer + 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) { @@ -117,10 +112,9 @@ public java.lang.Integer[] array(int sz) { return result; } } - public static class Pint implements IntSupplier { + 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(); } @@ -128,11 +122,10 @@ public int[] array(int sz) { return r.ints(sz, 0, MOD).toArray(); } } - public static class Long + 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) { @@ -147,11 +140,9 @@ public java.lang.Long[] array(int sz) { return result; } } - public static 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(); } @@ -159,11 +150,10 @@ public long[] array(int sz) { return r.longs(sz, 0, MOD).toArray(); } } - public static class Float + 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) { @@ -176,7 +166,7 @@ public java.lang.Float[] array(int sz) { return result; } } - public static class Pfloat { + class Pfloat { public float[] array(int sz) { return primitive(new Float().array(sz)); } @@ -185,11 +175,10 @@ static double trim(double d) { return ((double)Math.round(d * 1000.0)) / 100.0; } - public static class Double + 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) { @@ -205,11 +194,9 @@ public java.lang.Double[] array(int sz) { return result; } } - public static 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) { @@ -222,7 +209,7 @@ public double[] array(int sz) { return result; } } - public static class String + class String implements Supplier { SplittableRandom r = new SplittableRandom(47); private int strlen = 7; // Default length @@ -230,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 dfece996c..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 a sequence [start..end) incrementing by step + // 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 45cae6d27..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; @@ -8,17 +8,17 @@ import java.io.IOException; public class RmDir { - public static void rmdir(Path dir) throws IOException { - Files.walkFileTree(dir,new SimpleFileVisitor() { - @Override - public FileVisitResult + public static void rmdir(Path dir) + throws IOException { + Files.walkFileTree(dir, + new SimpleFileVisitor() { + @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 c48ece0f5..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 @@ -10,8 +10,8 @@ public class Suppliers { // Create a collection and fill it: - public static > - C create(Supplier factory, Supplier gen, int n) { + public static > C + create(Supplier factory, Supplier gen, int n) { return Stream.generate(gen) .limit(n) .collect(factory, C::add, C::addAll); 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 19d29d146..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 @@ -20,7 +20,7 @@ public class AtUnit implements ProcessFiles.Strategy { public static void main(String[] args) throws Exception { ClassLoader.getSystemClassLoader() - .setDefaultAssertionStatus(true); // Enable asserts + .setDefaultAssertionStatus(true); // Enable assert new ProcessFiles(new AtUnit(), "class").start(args); if(failures == 0) System.out.println("OK (" + testsRun + " tests)"); @@ -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())); @@ -61,13 +60,14 @@ public void process(File cFile) { if(creator == null) try { if(!Modifier.isPublic(testClass - .getDeclaredConstructor().getModifiers())) { + .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()); } @@ -112,11 +112,12 @@ void addIfTestMethod(Method m) { m.getReturnType().equals(void.class))) throw new RuntimeException("@Test method" + " must return boolean or void"); - m.setAccessible(true); // In case it's private, etc. + m.setAccessible(true); // If it's private, etc. add(m); } } - private static Method checkForCreatorMethod(Method m) { + private static + Method checkForCreatorMethod(Method m) { if(m.getAnnotation(TestObjectCreate.class) == null) return null; if(!m.getReturnType().equals(testClass)) @@ -129,7 +130,8 @@ private static Method checkForCreatorMethod(Method m) { m.setAccessible(true); return m; } - private static Method checkForCleanupMethod(Method m) { + private static + Method checkForCleanupMethod(Method m) { if(m.getAnnotation(TestObjectCleanup.class) == null) return null; if(!m.getReturnType().equals(void.class)) @@ -157,10 +159,13 @@ private static 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 1444fa577..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} @@ -12,7 +12,8 @@ public class ClassNameFinder { public static String thisClass(byte[] classBytes) { Map offsetTable = new HashMap<>(); - Map classNameTable = new HashMap<>(); + Map classNameTable = + new HashMap<>(); try { DataInputStream data = new DataInputStream( new ByteArrayInputStream(classBytes)); @@ -52,7 +53,7 @@ public static String thisClass(byte[] classBytes) { case 11: // INTERFACE_METHOD_REF case 12: // NAME_AND_TYPE case 18: // Invoke Dynamic - data.readInt(); // discard 4 bytes; + data.readInt(); // discard 4 bytes break; case 15: // Method Handle data.readByte(); @@ -62,7 +63,8 @@ public static String thisClass(byte[] classBytes) { data.readShort(); break; default: - throw new RuntimeException("Bad tag " + tag); + throw + new RuntimeException("Bad tag " + tag); } } short accessFlags = data.readShort(); @@ -84,7 +86,6 @@ public static String thisClass(byte[] classBytes) { // Walk the entire tree: Files.walk(Paths.get(".")) .filter(matcher::matches) - //.peek(System.out::println) .map(p -> { try { return thisClass(Files.readAllBytes(p)); @@ -113,63 +114,63 @@ public static String thisClass(byte[] classBytes) { onjava.CollectionMethodDifferences onjava.ConvertTo onjava.Count$Boolean -onjava.Count$Pboolean onjava.Count$Byte -onjava.Count$Pbyte onjava.Count$Character -onjava.Count$Pchar onjava.Count$Double -onjava.Count$Pdouble onjava.Count$Float -onjava.Count$Pfloat onjava.Count$Integer -onjava.Count$Pint onjava.Count$Long +onjava.Count$Pboolean +onjava.Count$Pbyte +onjava.Count$Pchar +onjava.Count$Pdouble +onjava.Count$Pfloat +onjava.Count$Pint onjava.Count$Plong -onjava.Count$Short onjava.Count$Pshort +onjava.Count$Short onjava.Count onjava.CountingIntegerList onjava.CountMap onjava.Countries onjava.Enums onjava.FillMap -onjava.Hex +onjava.HTMLColors onjava.MouseClick +onjava.Nap onjava.Null -onjava.Operation +onjava.Operations onjava.OSExecute onjava.OSExecuteException onjava.Pair onjava.ProcessFiles$Strategy onjava.ProcessFiles onjava.Rand$Boolean -onjava.Rand$Pboolean onjava.Rand$Byte -onjava.Rand$Pbyte onjava.Rand$Character -onjava.Rand$Pchar onjava.Rand$Double -onjava.Rand$Pdouble onjava.Rand$Float -onjava.Rand$Pfloat onjava.Rand$Integer -onjava.Rand$Pint onjava.Rand$Long +onjava.Rand$Pboolean +onjava.Rand$Pbyte +onjava.Rand$Pchar +onjava.Rand$Pdouble +onjava.Rand$Pfloat +onjava.Rand$Pint onjava.Rand$Plong -onjava.Rand$Short onjava.Rand$Pshort +onjava.Rand$Short onjava.Rand$String onjava.Rand onjava.Range onjava.Repeat onjava.RmDir onjava.Sets -onjava.Sleep onjava.Stack onjava.Suppliers onjava.TimedAbort -onjava.TimeIt +onjava.Timer onjava.Tuple onjava.Tuple2 onjava.Tuple3 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 385ca9731..bcb090935 100644 --- a/operators/AutoInc.java +++ b/operators/AutoInc.java @@ -1,27 +1,27 @@ // 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) { int i = 1; - System.out.println("i : " + i); - System.out.println("++i : " + ++i); // Pre-increment - System.out.println("i++ : " + i++); // Post-increment - System.out.println("i : " + i); - System.out.println("--i : " + --i); // Pre-decrement - System.out.println("i-- : " + i--); // Post-decrement - System.out.println("i : " + i); + System.out.println("i: " + i); + System.out.println("++i: " + ++i); // Pre-increment + System.out.println("i++: " + i++); // Post-increment + System.out.println("i: " + i); + System.out.println("--i: " + --i); // Pre-decrement + System.out.println("i--: " + i--); // Post-decrement + System.out.println("i: " + i); } } /* Output: -i : 1 -++i : 2 -i++ : 2 -i : 3 ---i : 2 -i-- : 2 -i : 1 +i: 1 +++i: 2 +i++: 2 +i: 3 +--i: 2 +i--: 2 +i: 1 */ 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 baa3877d6..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 = new Integer(47); - Integer n2 = new Integer(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 a3d26fd12..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 = new Integer(47); - Integer n2 = new Integer(47); - System.out.println(n1 == n2); - System.out.println(n1 != n2); + test(127); + test(128); } } /* Output: -false -true +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 2f7804044..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,14 +17,14 @@ 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 System.out.println( "s: " + Integer.toBinaryString(s)); long n1 = 200L; // long suffix - long n2 = 200l; // long suffix (but can be confusing) + long n2 = 200l; // long suffix (can be confusing) long n3 = 200; // Java 7 Binary Literals: byte blb = (byte)0b00110101; 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 1ea173921..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 -111111111111111111111111111111111111111111111111111111111 -11111 +1111111111111111111111111111111111111111111111111111111111111111 111111111111111111111111111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 diff --git a/operators/Underscores.java b/operators/Underscores.java index 2805f43e8..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); + 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 b19a448c0..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 -// {ValidateByHand} // CI servers have problems +// 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 4a042d179..e290cff43 100644 --- a/patterns/Facade.java +++ b/patterns/Facade.java @@ -1,11 +1,11 @@ // 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. -class A { public A(int x) {} } -class B { public B(long x) {} } -class C { public C(double x) {} } +class A { A(int x) {} } +class B { B(long x) {} } +class C { C(double x) {} } // Other classes that aren't exposed by the // facade go here ... 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 d673a3e68..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; - public 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 @@ public Proxy() { } 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 c9c8a79a9..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.*; @@ -15,19 +15,19 @@ interface PolymorphicFactory { class RandomShapes implements Supplier { private final PolymorphicFactory[] factories; private Random rand = new Random(42); - public 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 new file mode 100644 index 000000000..3ed313e6c --- /dev/null +++ b/patterns/SingletonPattern.java @@ -0,0 +1,47 @@ +// patterns/SingletonPattern.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. + +final class IntegerSingleton + implements Resource { + private static IntegerSingleton value = + new IntegerSingleton(); + private Integer i = Integer.valueOf(0); + private IntegerSingleton() { + System.out.println("IntegerSingleton()"); + } + 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) { + System.out.println("Inside main()"); + Resource ir = + IntegerSingleton.instance(); + Resource ir2 = + IntegerSingleton.instance(); + show(ir); + put(ir2, Integer.valueOf(9)); + show(ir); + } +} +/* Output: +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 976c8dbc9..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; - public 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 ef2559162..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 { - public 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 609ba8623..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; @@ -17,11 +17,10 @@ interface WhatIWant { class ProxyAdapter implements WhatIWant { WhatIHave whatIHave; - public ProxyAdapter(WhatIHave wih) { + 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 140b4dffe..b291c3e00 100644 --- a/patterns/chain/ChainOfResponsibility.java +++ b/patterns/chain/ChainOfResponsibility.java @@ -1,70 +1,48 @@ // 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; - public Result(List data) { - success = true; - line = data; - } - public 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( + static List, Result>> + algorithms = Arrays.asList( FindMinima::leastSquares, FindMinima::perturbation, FindMinima::bisection ); public static Result minima(List line) { - for(Function, Result> alg : algorithms) { + for(Function, Result> alg : + algorithms) { Result result = alg.apply(line); if(result.success) return result; } - return new Fail(); + return Result.fail; } } @@ -82,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 a3c0328a9..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; - public 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 a36c0569e..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; - public 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; - public 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; - public 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 de84445c9..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(), - }; - public 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 + private Iterator states = + Arrays.asList( + new Wash(), new Spin(), + new Rinse(), new Spin() + ).iterator(); + Washer() { runAll(); } + @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 d26e7801b..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; - public 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 7c72d4817..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; } } @@ -31,5 +30,6 @@ public static void main(String[] args) { } /* Output: sup.field = 0, sup.getField() = 1 -sub.field = 1, sub.getField() = 1, sub.getSuperField() = 0 +sub.field = 1, sub.getField() = 1, sub.getSuperField() += 0 */ diff --git a/polymorphism/Frog.java b/polymorphism/Frog.java index f36de16cd..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(); @@ -76,11 +74,11 @@ protected void dispose() { } public class Frog extends Amphibian { - private Characteristic p = new Characteristic("Croaks"); + private Characteristic p = + 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 cd6f895e6..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 @@ -7,7 +7,9 @@ package polymorphism; public class PrivateOverride { - private void f() { System.out.println("private f()"); } + private void f() { + System.out.println("private f()"); + } public static void main(String[] args) { PrivateOverride po = new Derived(); po.f(); diff --git a/polymorphism/PrivateOverride2.java b/polymorphism/PrivateOverride2.java index df695d55f..d53d9a256 100644 --- a/polymorphism/PrivateOverride2.java +++ b/polymorphism/PrivateOverride2.java @@ -1,13 +1,15 @@ // 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 -// {CompileTimeError} (Will not compile) +// {WillNotCompile} package polymorphism; public class PrivateOverride2 { - private void f() { System.out.println("private f()"); } + private void f() { + System.out.println("private f()"); + } public static void main(String[] args) { PrivateOverride2 po = new Derived2(); po.f(); @@ -15,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 e594f79f7..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 @@ -8,7 +8,7 @@ class Shared { private int refcount = 0; private static long counter = 0; private final long id = counter++; - public Shared() { + Shared() { System.out.println("Creating " + this); } public void addRef() { refcount++; } @@ -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; } } @@ -26,7 +25,7 @@ class Composing { private Shared shared; private static long counter = 0; private final long id = counter++; - public Composing(Shared shared) { + Composing(Shared shared) { System.out.println("Creating " + this); this.shared = shared; this.shared.addRef(); @@ -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 61% rename from polymorphism/RTTI.java rename to polymorphism/Reflect.java index c7ed65f54..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,13 +27,14 @@ 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 } } /* Output: ___[ Error Output ]___ -Exception in thread "main" java.lang.ClassCastException: -Useful cannot be cast to MoreUseful - at RTTI.main(RTTI.java:31) +Exception in thread "main" +java.lang.ClassCastException: Useful cannot be cast to +MoreUseful + 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/preferences/PreferencesDemo.java b/preferences/PreferencesDemo.java deleted file mode 100644 index e6d40260c..000000000 --- a/preferences/PreferencesDemo.java +++ /dev/null @@ -1,41 +0,0 @@ -// preferences/PreferencesDemo.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.prefs.*; - -public class PreferencesDemo { - public static void - main(String[] args) throws Exception { - Preferences prefs = Preferences - .userNodeForPackage(PreferencesDemo.class); - prefs.put("Location", "Oz"); - prefs.put("Footwear", "Ruby Slippers"); - prefs.putInt("Companions", 4); - prefs.putBoolean("Are there witches?", true); - int usageCount = prefs.getInt("UsageCount", 0); - usageCount++; - prefs.putInt("UsageCount", usageCount); - for(String key : prefs.keys()) - System.out.println(key + ": " - + prefs.get(key, null)); - // You must always provide a default value: - System.out.println( - "How many companions does Dorothy have? " + - prefs.getInt("Companions", 0)); - } -} -/* Output: -Location: Oz -Footwear: Ruby Slippers -Companions: 4 -Are there witches?: true -UsageCount: 191 -How many companions does Dorothy have? 4 -___[ Error Output ]___ -Jul 27, 2016 10:50:50 AM java.util.prefs.WindowsPreferences - -WARNING: Could not open/create prefs root node -Software\JavaSoft\Prefs at root 0x80000002. Windows -RegCreateKeyEx(...) returned error code 5. -*/ diff --git a/references/AddingClone.java b/references/AddingClone.java index d9972c950..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 @@ -9,14 +9,12 @@ class Int2 implements Cloneable { private int i; - public Int2(int ii) { i = ii; } + 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) { @@ -28,7 +26,7 @@ public Int2 clone() { // Inheritance doesn't remove cloneability: class Int3 extends Int2 { private int j; // Automatically duplicated - public Int3(int i) { super(i); } + Int3(int i) { super(i); } } public class AddingClone { 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 5135a3734..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 @@ -9,10 +9,9 @@ class Int { private int i; - public Int(int ii) { i = ii; } + 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 0b0d77f40..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: 776 Milliseconds -Duplication via cloning: 122 Milliseconds +Duplication via serialization: 385 Milliseconds +Duplication via cloning: 38 Milliseconds */ diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java index edaeefd20..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,14 +13,14 @@ class FruitQualities { private int ripeness; private int smell; // etc. - // No-arg constructor: - public FruitQualities() { + // Zero-argument constructor: + FruitQualities() { // Do something meaningful... } // Other constructors: // ... // Copy constructor: - public FruitQualities(FruitQualities f) { + FruitQualities(FruitQualities f) { weight = f.weight; color = f.color; firmness = f.firmness; @@ -32,15 +32,15 @@ public FruitQualities(FruitQualities f) { class Seed { // Members... - public Seed() { /* No-arg constructor */ } - public Seed(Seed s) { /* Copy constructor */ } + Seed() { /* Zero-argument constructor */ } + Seed(Seed s) { /* Copy constructor */ } } class Fruit { private FruitQualities fq; private int seeds; private Seed[] s; - public Fruit(FruitQualities q, int seedCount) { + Fruit(FruitQualities q, int seedCount) { fq = q; seeds = seedCount; s = new Seed[seeds]; @@ -50,7 +50,7 @@ public Fruit(FruitQualities q, int seedCount) { // Other constructors: // ... // Copy constructor: - public Fruit(Fruit f) { + Fruit(Fruit f) { fq = new FruitQualities(f.fq); seeds = f.seeds; s = new Seed[seeds]; @@ -70,10 +70,10 @@ protected FruitQualities getQualities() { } class Tomato extends Fruit { - public Tomato() { + Tomato() { super(new FruitQualities(), 100); } - public Tomato(Tomato t) { // Copy-constructor + Tomato(Tomato t) { // Copy-constructor super(t); // Upcast to base copy-constructor // Other copy-construction activities... } @@ -81,22 +81,22 @@ public Tomato(Tomato t) { // Copy-constructor class ZebraQualities extends FruitQualities { private int stripedness; - // No-arg constructor: - public ZebraQualities() { + // Zero-argument constructor: + ZebraQualities() { super(); // do something meaningful... } - public ZebraQualities(ZebraQualities z) { + ZebraQualities(ZebraQualities z) { super(z); stripedness = z.stripedness; } } class GreenZebra extends Tomato { - public GreenZebra() { + GreenZebra() { addQualities(new ZebraQualities()); } - public GreenZebra(GreenZebra g) { + GreenZebra(GreenZebra g) { super(g); // Calls Tomato(Tomato) // Restore the right qualities: addQualities(new ZebraQualities()); @@ -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()); } @@ -177,10 +177,12 @@ public static void main(String[] args) { /* Output: In ripen, t is a Tomato In slice, f is a Fruit -In ripen2, t is a Tomato -In slice2, f is a Tomato +java.lang.NoSuchMethodException: Tomato.(Tomato) +java.lang.NoSuchMethodException: Tomato.(Tomato) In ripen, t is a Tomato In slice, f is a Fruit -In ripen2, t is a GreenZebra -In slice2, f is a GreenZebra +java.lang.NoSuchMethodException: +GreenZebra.(GreenZebra) +java.lang.NoSuchMethodException: +GreenZebra.(GreenZebra) */ 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 8c47f721f..e4a8656d9 100644 --- a/references/HorrorFlick.java +++ b/references/HorrorFlick.java @@ -1,16 +1,15 @@ // 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. -// You can insert Cloneability at any level of inheritance +// Insert Cloneability at any level of inheritance 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 9275a537b..aa23cadad 100644 --- a/references/Immutable2.java +++ b/references/Immutable2.java @@ -1,12 +1,12 @@ // 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 class Mutable { private int data; - public Mutable(int initVal) { + Mutable(int initVal) { data = initVal; } public Mutable add(int x) { 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 new file mode 100644 index 000000000..f19f63a62 --- /dev/null +++ b/references/LocalCopy.java @@ -0,0 +1,55 @@ +// references/LocalCopy.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. +// Creating local copies with clone() + +class Duplo implements Cloneable { + private int n; + Duplo(int n) { this.n = n; } + @Override public Duplo clone() { // [1] + try { + return (Duplo)super.clone(); + } catch(CloneNotSupportedException e) { + throw new RuntimeException(e); + } + } + public int getValue() { return n; } + public void setValue(int n) { this.n = n; } + public void increment() { n++; } + @Override public String toString() { + return Integer.toString(n); + } +} + +public class LocalCopy { + public static Duplo g(Duplo v) { + // Passing a reference, modifies outside object: + v.increment(); + return v; + } + public static Duplo f(Duplo v) { + v = v.clone(); // Local copy // [2] + v.increment(); + return v; + } + public static void main(String[] args) { + Duplo a = new Duplo(11); + Duplo b = g(a); + // Reference equivalence, not object equivalence: + System.out.println("a == b: " + (a == b) + + "\na = " + a + "\nb = " + b); + Duplo c = new Duplo(47); + Duplo d = f(c); + System.out.println("c == d: " + (c == d) + + "\nc = " + c + "\nd = " + d); + } +} +/* Output: +a == b: true +a = 12 +b = 12 +c == d: false +c = 47 +d = 48 +*/ diff --git a/references/MutableInteger.java b/references/MutableInteger.java index 30c99e0c9..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 @@ -8,12 +8,11 @@ class IntValue { private int n; - public IntValue(int x) { n = x; } + IntValue(int x) { n = x; } 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 d42f4a21e..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@1db9742 -h inside f(): PassReferences@1db9742 +p inside main(): PassReferences@19e0bfd +h inside f(): PassReferences@19e0bfd */ diff --git a/references/SimplerMutableInteger.java b/references/SimplerMutableInteger.java index e0f7d24c6..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 @@ -8,7 +8,7 @@ class IntValue2 { public int n; - public IntValue2(int n) { this.n = n; } + IntValue2(int n) { this.n = n; } } public class SimplerMutableInteger { 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 79% rename from typeinfo/HiddenImplementation.java rename to reflection/HiddenImplementation.java index 385a93a3d..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 { @@ -28,14 +28,15 @@ public class HiddenImplementation { static void callHiddenMethod(Object a, String methodName) throws Exception { - Method g = a.getClass().getDeclaredMethod(methodName); + Method g = + a.getClass().getDeclaredMethod(methodName); g.setAccessible(true); g.invoke(a); } } /* 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 78% rename from typeinfo/NullRobot.java rename to reflection/NullRobot.java index ae68d7b04..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 @@ -8,7 +8,8 @@ import java.util.stream.*; import onjava.*; -class NullRobotProxyHandler implements InvocationHandler { +class NullRobotProxyHandler +implements InvocationHandler { private String nullName; private Robot proxied = new NRobot(); NullRobotProxyHandler(Class type) { @@ -19,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); @@ -42,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); } } @@ -57,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 82% rename from typeinfo/Person.java rename to reflection/Person.java index 611dcfcd1..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 @@ -12,7 +12,6 @@ class Person { public final Optional address; // etc. public final boolean empty; - public Person(String first, String last, String address) { this.first = Optional.ofNullable(first); this.last = Optional.ofNullable(last); @@ -21,13 +20,12 @@ class Person { && !this.last.isPresent() && !this.address.isPresent(); } - public Person(String first, String last) { + Person(String first, String last) { this(first, last, null); } - public Person(String last) { this(null, last, null); } - public Person() { this(null, null, null); } - @Override - public String toString() { + Person(String last) { this(null, last, null); } + Person() { this(null, null, null); } + @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 58% rename from typeinfo/PetCount2.java rename to reflection/PetCounter2.java index d24ebe982..ccac0b57f 100644 --- a/typeinfo/PetCount2.java +++ b/reflection/PetCounter2.java @@ -1,18 +1,18 @@ -// 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: Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat -EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug -Mouse Cymric +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/PetCount3.java b/reflection/PetCounter3.java similarity index 68% rename from typeinfo/PetCount3.java rename to reflection/PetCounter3.java index 803f2b925..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> { - public Counter() { - super(LiteralPetCreator.ALL_TYPES.stream() - .map(lpc -> Pair.make(lpc, 0)) + HashMap, Integer> { + Counter() { + 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( @@ -46,8 +45,9 @@ public static void main(String[] args) { } /* Output: Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat -EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug -Mouse Cymric -{Hamster=1, Rodent=5, Mouse=2, Dog=6, Cymric=5, Manx=7, -Rat=2, Pug=3, Mutt=3, Pet=20, EgyptianMau=2, Cat=9} +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{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 58% rename from typeinfo/PetCount4.java rename to reflection/PetCounter4.java index 803f1c373..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( @@ -18,8 +18,9 @@ public static void main(String[] args) { } /* Output: Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat -EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug -Mouse Cymric -{EgyptianMau=2, Hamster=1, Pug=3, Manx=7, Cymric=5, Dog=6, -Pet=20, Mutt=3, Rat=2, Mouse=2, Rodent=5, Cat=9} +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{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 86% rename from typeinfo/Position.java rename to reflection/Position.java index c1bfaf81f..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.*; @@ -9,11 +9,11 @@ class EmptyTitleException extends RuntimeException {} class Position { private String title; private Person person; - public Position(String jobTitle, Person employee) { + Position(String jobTitle, Person employee) { setTitle(jobTitle); setPerson(employee); } - public Position(String jobTitle) { + Position(String jobTitle) { this(jobTitle, null); } public String getTitle() { return title; } @@ -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 81% rename from typeinfo/SelectingMethods.java rename to reflection/SelectingMethods.java index 918df79ba..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 @@ -7,11 +7,10 @@ class MethodSelector implements InvocationHandler { private Object proxied; - public MethodSelector(Object proxied) { + 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/reflection/Shapes.java b/reflection/Shapes.java new file mode 100644 index 000000000..05d15df5c --- /dev/null +++ b/reflection/Shapes.java @@ -0,0 +1,43 @@ +// 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(); +} + +class Circle extends Shape { + @Override public String toString() { + return "Circle"; + } +} + +class Square extends Shape { + @Override public String toString() { + return "Square"; + } +} + +class Triangle extends Shape { + @Override public String toString() { + return "Triangle"; + } +} + +public class Shapes { + public static void main(String[] args) { + Stream.of( + new Circle(), new Square(), new Triangle()) + .forEach(Shape::draw); + } +} +/* Output: +Circle.draw() +Square.draw() +Triangle.draw() +*/ diff --git a/typeinfo/ShowMethods.java b/reflection/ShowMethods.java similarity index 93% rename from typeinfo/ShowMethods.java rename to reflection/ShowMethods.java index 4bc507f6c..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, @@ -29,7 +29,8 @@ public static void main(String[] args) { if(args.length == 1) { for(Method method : methods) System.out.println( - p.matcher(method.toString()).replaceAll("")); + p.matcher( + method.toString()).replaceAll("")); for(Constructor ctor : ctors) System.out.println( p.matcher(ctor.toString()).replaceAll("")); @@ -55,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 84% rename from typeinfo/SimpleDynamicProxy.java rename to reflection/SimpleDynamicProxy.java index 361d87f9c..9eeb02926 100644 --- a/typeinfo/SimpleDynamicProxy.java +++ b/reflection/SimpleDynamicProxy.java @@ -1,19 +1,19 @@ -// 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.*; class DynamicProxyHandler implements InvocationHandler { private Object proxied; - public DynamicProxyHandler(Object proxied) { + DynamicProxyHandler(Object proxied) { this.proxied = proxied; } - @Override - public Object + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - System.out.println("**** proxy: " + proxy.getClass() + + System.out.println( + "**** proxy: " + proxy.getClass() + ", method: " + method + ", args: " + args); if(args != null) for(Object arg : args) @@ -46,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;@1c7c054 +[Ljava.lang.Object;@1b84c92 bonobo somethingElse bonobo */ diff --git a/typeinfo/SimpleProxyDemo.java b/reflection/SimpleProxyDemo.java similarity index 76% rename from typeinfo/SimpleProxyDemo.java rename to reflection/SimpleProxyDemo.java index d526f0c8a..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,28 +9,24 @@ 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); } } class SimpleProxy implements Interface { private Interface proxied; - public SimpleProxy(Interface proxied) { + 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 63% rename from typeinfo/SnowRemovalRobot.java rename to reflection/SnowRobot.java index f1518eaeb..227dcb49d 100644 --- a/typeinfo/SnowRemovalRobot.java +++ b/reflection/SnowRobot.java @@ -1,31 +1,34 @@ -// 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", - () -> System.out.println(name + " shoveling snow")), + () -> System.out.println( + name + " shoveling snow")), new Operation( () -> name + " can chip ice", () -> System.out.println(name + " chipping ice")), new Operation( () -> name + " can clear the roof", - () -> System.out.println(name + " clearing 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 73% rename from typeinfo/Staff.java rename to reflection/Staff.java index 3d07e2c78..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.*; @@ -43,19 +43,21 @@ public static void main(String[] args) { new Person("Janet", "Planner", "The Burbs")); if(staff.positionAvailable("Software Engineer")) staff.fillPosition("Software Engineer", - new Person("Bob", "Coder", "Bright Light City")); + new Person( + "Bob", "Coder", "Bright Light City")); System.out.println(staff); } } /* Output: -[Position: President, Employee: Me Last The Top, Lonely At, -Position: CTO, Employee: , Position: Marketing -Manager, Employee: , Position: Product Manager, -Employee: , Position: Project Lead, Employee: Janet -Planner The Burbs, Position: Software Engineer, Employee: -Bob Coder Bright Light City, Position: Software Engineer, -Employee: , Position: Software Engineer, Employee: -, Position: Software Engineer, Employee: , +[Position: President, Employee: Me Last The Top, Lonely +At, Position: CTO, Employee: , Position: +Marketing Manager, Employee: , Position: Product +Manager, Employee: , Position: Project Lead, +Employee: Janet Planner The Burbs, Position: Software +Engineer, Employee: Bob Coder Bright Light City, +Position: Software Engineer, Employee: , +Position: Software Engineer, Employee: , +Position: Software Engineer, Employee: , Position: Test Engineer, Employee: , Position: Technical Writer, Employee: ] */ 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/reflection/pets/PetCreator.java b/reflection/pets/PetCreator.java new file mode 100644 index 000000000..1f01ceed3 --- /dev/null +++ b/reflection/pets/PetCreator.java @@ -0,0 +1,42 @@ +// 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 reflection.pets.PetCreator} +package reflection.pets; +import java.util.*; + +public class PetCreator extends Creator { + // No try block needed. + public static final + List> ALL_TYPES = + Collections.unmodifiableList(Arrays.asList( + Pet.class, Dog.class, Cat.class, Rodent.class, + Mutt.class, Pug.class, EgyptianMau.class, + Manx.class, Cymric.class, Rat.class, + Mouse.class, Hamster.class)); + // Types for random creation: + private static final + List> TYPES = + ALL_TYPES.subList( + ALL_TYPES.indexOf(Mutt.class), + ALL_TYPES.size()); + @Override + public List> types() { + return TYPES; + } + public static void main(String[] args) { + System.out.println(TYPES); + List pets = new PetCreator().list(7); + System.out.println(pets); + } +} +/* Output: +[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 53% rename from typeinfo/toys/ToyTest.java rename to reflection/toys/ToyTest.java index df7d6bda6..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,32 +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? [false] +Class name: reflection.toys.FancyToy is interface? +[false] Simple name: FancyToy -Canonical name : typeinfo.toys.FancyToy -Class name: typeinfo.toys.HasBatteries is interface? [true] +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? [true] +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/remote/DisplayPerfectTime.java b/remote/DisplayPerfectTime.java deleted file mode 100644 index c3556b324..000000000 --- a/remote/DisplayPerfectTime.java +++ /dev/null @@ -1,21 +0,0 @@ -// remote/DisplayPerfectTime.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. -// Uses remote object PerfectTime -// {ValidateByHand} -package remote; -import java.rmi.registry.*; - -public class DisplayPerfectTime { - public static void - main(String[] args) throws Exception { - Registry reg = - LocateRegistry.getRegistry("localhost"); - PerfectTime pt = - (PerfectTime)reg.lookup("PerfectTime"); - for(int i = 0; i < 10; i++) - System.out.println( - "Time: "+ pt.getPerfectTime()); - } -} diff --git a/remote/PerfectTime.java b/remote/PerfectTime.java deleted file mode 100644 index 73c9c67b4..000000000 --- a/remote/PerfectTime.java +++ /dev/null @@ -1,11 +0,0 @@ -// remote/PerfectTime.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 PerfectTime remote interface -package remote; -import java.rmi.*; - -public interface PerfectTime extends Remote { - long getPerfectTime() throws RemoteException; -} diff --git a/remote/PerfectTimeImpl.java b/remote/PerfectTimeImpl.java deleted file mode 100644 index a1a913025..000000000 --- a/remote/PerfectTimeImpl.java +++ /dev/null @@ -1,13 +0,0 @@ -// remote/PerfectTimeImpl.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. -// Implementing the PerfectTime remote object -package remote; -import java.rmi.RemoteException; - -public class PerfectTimeImpl implements PerfectTime { - public long getPerfectTime() throws RemoteException { - return System.currentTimeMillis(); - } -} diff --git a/remote/PerfectTimeServer.java b/remote/PerfectTimeServer.java deleted file mode 100644 index b466b04e6..000000000 --- a/remote/PerfectTimeServer.java +++ /dev/null @@ -1,23 +0,0 @@ -// remote/PerfectTimeServer.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. -// Server for the PerfectTime remote object -// {ValidateByHand} -package remote; -import java.rmi.registry.Registry; -import java.rmi.registry.LocateRegistry; -import java.rmi.RemoteException; -import java.rmi.server.UnicastRemoteObject; - -public class PerfectTimeServer { - public static void - main(String[] args) throws RemoteException { - PerfectTimeImpl pt = new PerfectTimeImpl(); - PerfectTime stub = (PerfectTime) - UnicastRemoteObject.exportObject(pt, 0); - Registry registry = LocateRegistry.getRegistry(); - registry.rebind("PerfectTime", stub); - System.out.println("Ready to do time"); - } -} diff --git a/remote/tests/RMITests.java b/remote/tests/RMITests.java deleted file mode 100644 index 4e1f7fd50..000000000 --- a/remote/tests/RMITests.java +++ /dev/null @@ -1,25 +0,0 @@ -// remote/tests/RMITests.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -package remote; - -import java.rmi.registry.*; - -import org.junit.jupiter.api.*; -import org.junit.jupiter.api.TestInfo; - -public class RMITests { - @Test - void test_remote_time() throws Exception { - LocateRegistry.createRegistry(1099); - PerfectTimeServer timeServer = new PerfectTimeServer(); - timeServer.main(null); - Registry reg = - LocateRegistry.getRegistry("localhost"); - PerfectTime pt = - (PerfectTime) reg.lookup("PerfectTime"); - for (int i = 0; i < 10; i++) - System.out.println("Time: " + pt.getPerfectTime()); - } -} 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 dc73da65a..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 @@ -13,14 +13,14 @@ public class BlankFinal { private final int i = 0; // Initialized final private final int j; // Blank final private final Poppet p; // Blank final reference - // Blank finals MUST be initialized in the constructor: + // Blank finals MUST be initialized in constructor: public BlankFinal() { j = 1; // Initialize blank final - p = new Poppet(1); // Initialize blank final reference + p = new Poppet(1); // Init blank final reference } public BlankFinal(int x) { j = x; // Initialize blank final - p = new Poppet(x); // Initialize blank final reference + p = new Poppet(x); // Init blank final reference } public static void main(String[] args) { new BlankFinal(); 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 c8edb4fe9..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 } @@ -41,7 +39,8 @@ public static void main(String[] args) { } } /* Output: -Cleanser dilute() apply() Detergent.scrub() scrub() foam() +Cleanser dilute() apply() Detergent.scrub() scrub() +foam() Testing base class: Cleanser dilute() apply() scrub() */ 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 0ee781ff3..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 @@ -7,7 +7,7 @@ class Value { int i; // Package access - public Value(int i) { this.i = i; } + Value(int i) { this.i = i; } } public class FinalData { @@ -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 bc0df2071..68cccf0a7 100644 --- a/reuse/Lisa.java +++ b/reuse/Lisa.java @@ -1,8 +1,8 @@ // 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. -// {CompileTimeError} (Will not compile) +// {WillNotCompile} class Lisa extends Homer { @Override void doh(Milhouse m) { diff --git a/reuse/Orc.java b/reuse/Orc.java index dc70d3cf1..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 @@ -7,9 +7,8 @@ class Villain { private String name; protected void set(String nm) { name = nm; } - public Villain(String name) { this.name = name; } - @Override - public String toString() { + Villain(String name) { this.name = name; } + @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 7b66507f0..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(); - public Shape(int xVal, int yVal, int dim) { + 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; - public Circle(int xVal, int yVal, int dim) { + 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; - public 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(); } - public 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 701b6987f..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 @@ -8,9 +8,12 @@ public class FreezeAlien { public static void main(String[] args) throws Exception { - ObjectOutput out = new ObjectOutputStream( - new FileOutputStream("X.file")); - Alien quellek = new Alien(); - out.writeObject(quellek); + try( + ObjectOutputStream out = new ObjectOutputStream( + new FileOutputStream("X.file")); + ) { + Alien quellek = new Alien(); + out.writeObject(quellek); + } } } diff --git a/serialization/Logon.java b/serialization/Logon.java index eafa30d69..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: Sat Jan 21 22:06:35 PST 2017 + date: Sun Jan 24 08:49:30 MST 2021 password: myLittlePony -Recovering object at Sat Jan 21 22:06:36 PST 2017 +Recovering object at Sun Jan 24 08:49:31 MST 2021 logon a = logon info: username: Hulk - date: Sat Jan 21 22:06:35 PST 2017 + date: Sun Jan 24 08:49:30 MST 2021 password: null */ diff --git a/serialization/MyWorld.java b/serialization/MyWorld.java index de5cad4ec..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,20 +76,20 @@ public static void main(String[] args) { } } /* Output: -animals: [Bosco the dog[Animal@1db9742], House@106d69c -, Ralph the hamster[Animal@52e922], House@106d69c -, Molly the cat[Animal@25154f], House@106d69c +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@1a4f24f], House@19a45b3 -, Ralph the hamster[Animal@99a589], House@19a45b3 -, Molly the cat[Animal@372a00], House@19a45b3 +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@1a4f24f], House@19a45b3 -, Ralph the hamster[Animal@99a589], House@19a45b3 -, Molly the cat[Animal@372a00], House@19a45b3 +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@dd8dc3], House@103e736 -, Ralph the hamster[Animal@8db2f2], House@103e736 -, Molly the cat[Animal@18bf509], House@103e736 +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 6e5e9595e..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 @@ -8,9 +8,8 @@ class Data implements Serializable { private int n; - public Data(int n) { this.n = n; } - @Override - public String toString() { + Data(int n) { this.n = n; } + @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("("); @@ -94,9 +92,9 @@ public String toString() { Worm constructor: 3 Worm constructor: 2 Worm constructor: 1 -w = :a(571):b(079):c(688):d(307):e(052):f(402) +w = :a(853):b(119):c(802):d(788):e(199):f(881) Worm storage -w2 = :a(571):b(079):c(688):d(307):e(052):f(402) +w2 = :a(853):b(119):c(802):d(788):e(199):f(881) Worm storage -w3 = :a(571):b(079):c(688):d(307):e(052):f(402) +w3 = :a(853):b(119):c(802):d(788):e(199):f(881) */ 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 48f8f8856..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.*; @@ -7,7 +7,8 @@ public class ArrayStreams { public static void main(String[] args) { - Arrays.stream(new double[] { 3.14159, 2.718, 1.618 }) + Arrays.stream( + new double[] { 3.14159, 2.718, 1.618 }) .forEach(n -> System.out.format("%f ", n)); System.out.println(); Arrays.stream(new int[] { 1, 3, 5 }) 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 55a2cb654..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.*; @@ -16,7 +16,8 @@ public FileToWordsRegexp(String filePath) .collect(Collectors.joining(" ")); } public Stream stream() { - return Pattern.compile("[ .,?]+").splitAsStream(all); + return Pattern + .compile("[ .,?]+").splitAsStream(all); } public static void main(String[] args) throws Exception { 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 6258b8e72..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 589 200 861 522 429 868 961 288 555 128 693 207 258 +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 d482c1efb..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.*; @@ -14,7 +14,8 @@ public static void main(String[] args) { Optional lastobj = Stream.of("one", "two", "three") .reduce((n1, n2) -> n2); - System.out.println(lastobj.orElse("Nothing there!")); + System.out.println( + lastobj.orElse("Nothing there!")); } } /* Output: 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 21bf52941..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.*; @@ -8,14 +8,13 @@ class Pair { public final Character c; public final Integer i; - public Pair(Character c, Integer i) { + Pair(Character c, Integer i) { this.c = c; this.i = i; } public Character getC() { return c; } public Integer getI() { return i; } - @Override - public String toString() { + @Override public String toString() { return "Pair(" + c + ", " + i + ")"; } } @@ -43,5 +42,6 @@ public static void main(String[] args) { } } /* Output: -{688=W, 309=C, 293=B, 761=N, 858=N, 668=G, 622=F, 751=N} +{688=W, 309=C, 293=B, 761=N, 858=N, 668=G, 622=F, +751=N} */ 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 1636a9b2e..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.*; @@ -13,7 +13,8 @@ class OptionalFilter { static Stream testStream() { return Arrays.stream(elements); } - static void test(String descr, Predicate pred) { + static void + test(String descr, Predicate pred) { System.out.println(" ---( " + descr + " )---"); for(int i = 0; i <= elements.length; i++) { System.out.println( @@ -28,7 +29,8 @@ public static void main(String[] args) { test("false", str -> false); test("str != \"\"", str -> str != ""); test("str.length() == 3", str -> str.length() == 3); - test("startsWith(\"B\")", str -> str.startsWith("B")); + test("startsWith(\"B\")", + str -> str.startsWith("B")); } } /* Output: diff --git a/streams/OptionalFlatMap.java b/streams/OptionalFlatMap.java index 4e06156df..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.*; @@ -24,11 +24,13 @@ static void test(String descr, } public static void main(String[] args) { - test("Add brackets", s -> Optional.of("[" + s + "]")); + test("Add brackets", + s -> Optional.of("[" + s + "]")); test("Increment", s -> { try { - return Optional.of(Integer.parseInt(s) + 1 + ""); + return Optional.of( + Integer.parseInt(s) + 1 + ""); } catch(NumberFormatException e) { return Optional.of(s); } diff --git a/streams/OptionalMap.java b/streams/OptionalMap.java index d4e02cac1..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.*; @@ -25,7 +25,8 @@ static Stream testStream() { public static void main(String[] args) { // If Optional is not empty, map() first extracts - // the contents which it then passes to the function: + // the contents which it then passes + // to the function: test("Add brackets", s -> "[" + s + "]"); diff --git a/streams/Optionals.java b/streams/Optionals.java index 18163f218..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.*; @@ -31,8 +31,8 @@ static void orElseThrow(Optional optString) { System.out.println("Caught " + e); } } - static void - test(String testName, Consumer> cos) { + static void test(String testName, + Consumer> cos) { System.out.println(" === " + testName + " === "); cos.accept(Stream.of("Epithets").findFirst()); cos.accept(Stream.empty().findFirst()); 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 96ebf3825..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.*; @@ -11,7 +11,8 @@ public static boolean isPrime(long n) { .noneMatch(i -> n % i == 0); } public LongStream numbers() { - return iterate(2, i -> i + 1).filter(Prime::isPrime); + return iterate(2, i -> i + 1) + .filter(Prime::isPrime); } public static void main(String[] args) { new Prime().numbers() 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 3e897be2c..7ae3adefc 100644 --- a/streams/StreamOf.java +++ b/streams/StreamOf.java @@ -1,12 +1,13 @@ // 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.*; public class StreamOf { public static void main(String[] args) { - Stream.of(new Bubble(1), new Bubble(2), new Bubble(3)) + Stream.of( + new Bubble(1), new Bubble(2), new Bubble(3)) .forEach(System.out::println); Stream.of("It's ", "a ", "wonderful ", "day ", "for ", "pie!") 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 64b79198a..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.*; 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 05746f706..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.*; @@ -21,10 +21,11 @@ public class TreeSetOfWords { } } /* Output: -[Arrays, Collectors, Exception, Files, Output, Paths, Set, -String, System, TreeSet, TreeSetOfWords, args, class, -collect, file, filter, flatMap, get, import, java, length, -limit, lines, main, map, matches, new, nio, numbers, out, -println, public, split, static, stream, streams, throws, -toCollection, trim, util, void, words2] +[Arrays, Collectors, Exception, Files, Output, Paths, +Set, String, System, TreeSet, TreeSetOfWords, args, +class, collect, file, filter, flatMap, get, import, +java, length, limit, lines, main, map, matches, new, +nio, numbers, out, println, public, split, static, +stream, streams, throws, toCollection, trim, util, +void, words2] */ diff --git a/strings/ArrayListDisplay.java b/strings/ArrayListDisplay.java index db22ca530..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.*; @@ -16,6 +16,7 @@ public static void main(String[] args) { } } /* Output: -[Americano 0, Latte 1, Americano 2, Mocha 3, Mocha 4, Breve -5, Americano 6, Latte 7, Cappuccino 8, Cappuccino 9] +[Americano 0, Latte 1, Americano 2, Mocha 3, Mocha 4, +Breve 5, Americano 6, Latte 7, Cappuccino 8, Cappuccino +9] */ 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 9009d9b81..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@1db9742 -h: 1db9742 +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 73d6b665d..5a7a9bd98 100644 --- a/strings/DatabaseException.java +++ b/strings/DatabaseException.java @@ -1,11 +1,11 @@ // 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. public class DatabaseException extends Exception { - public DatabaseException(int transactionID, int queryID, - String message) { + public DatabaseException(int transactionID, + int queryID, String message) { super(String.format("(t%d, q%d) %s", transactionID, queryID, message)); } diff --git a/strings/Finding.java b/strings/Finding.java index 001e304d8..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.*; @@ -21,7 +21,7 @@ public static void main(String[] args) { } /* Output: Evening is full of the linnet s wings -Evening vening ening ning ing ng g is is s full full ull ll -l of of f the the he e linnet linnet innet nnet net et t s -s wings wings ings ngs gs s +Evening vening ening ning ing ng g is is s full full +ull ll l of of f the the he e linnet linnet innet nnet +net et t s s wings wings ings ngs gs s */ diff --git a/strings/Groups.java b/strings/Groups.java index e4f212306..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.*; @@ -15,9 +15,9 @@ public class Groups { "Beware the Jubjub bird, and shun\n" + "The frumious Bandersnatch."; public static void main(String[] args) { - Matcher m = - Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$") - .matcher(POEM); + Matcher m = Pattern.compile( + "(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$") + .matcher(POEM); while(m.find()) { for(int j = 0; j <= m.groupCount(); j++) System.out.print("[" + m.group(j) + "]"); 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 857f4a67a..cc523ec88 100644 --- a/strings/InfiniteRecursion.java +++ b/strings/InfiniteRecursion.java @@ -1,17 +1,17 @@ // 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 // {ThrowsException} -// {ValidateByHand} +// {VisuallyInspectOutput} Throws very long exception import java.util.*; import java.util.stream.*; public class InfiniteRecursion { - @Override - public String toString() { - return " InfiniteRecursion address: " + this + "\n"; + @Override public String toString() { + return + " InfiniteRecursion address: " + this + "\n"; } public static void main(String[] args) { Stream.generate(InfiniteRecursion::new) 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 2cde029e3..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.*; @@ -13,23 +13,38 @@ public class JGrep { public static void main(String[] args) throws Exception { if(args.length < 2) { - System.out.println("Usage: java JGrep file regex"); + System.out.println( + "Usage: java JGrep file regex"); 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 bfca7a6b4..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.*; @@ -9,25 +9,30 @@ public class ReceiptBuilder { private Formatter f = new Formatter(new StringBuilder()); public ReceiptBuilder() { - f.format("%-15s %5s %10s%n", "Item", "Qty", "Price"); - f.format("%-15s %5s %10s%n", "----", "---", "-----"); + f.format( + "%-15s %5s %10s%n", "Item", "Qty", "Price"); + f.format( + "%-15s %5s %10s%n", "----", "---", "-----"); } public void add(String name, int qty, double price) { f.format("%-15.15s %5d %10.2f%n", name, qty, price); total += price * qty; } public String build() { - f.format("%-15s %5s %10.2f%n", "Tax", "", total*0.06); + f.format("%-15s %5s %10.2f%n", "Tax", "", + total * 0.06); f.format("%-15s %5s %10s%n", "", "", "-----"); f.format("%-15s %5s %10.2f%n", "Total", "", total * 1.06); return f.toString(); } public static void main(String[] args) { - ReceiptBuilder receiptBuilder = new ReceiptBuilder(); + ReceiptBuilder receiptBuilder = + new ReceiptBuilder(); receiptBuilder.add("Jack's Magic Beans", 4, 4.25); receiptBuilder.add("Princess Peas", 3, 5.1); - receiptBuilder.add("Three Bears Porridge", 1, 14.29); + receiptBuilder.add( + "Three Bears Porridge", 1, 14.29); System.out.println(receiptBuilder.build()); } } diff --git a/strings/Replacing.java b/strings/Replacing.java index a098b90ba..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. @@ -14,7 +14,8 @@ public static void main(String[] args) { } /* Output: Then, when you have located the shrubbery, you must cut -down the mightiest tree in the forest... with... a herring! -Then, when you have found the banana, you must cut down the -mightiest banana in the forest... with... a banana! +down the mightiest tree in the forest...with... a +herring! +Then, when you have found the banana, you must cut down +the mightiest banana in the forest...with... a banana! */ diff --git a/strings/ReplacingStringTokenizer.java b/strings/ReplacingStringTokenizer.java index 0722af334..9c2bee8ad 100644 --- a/strings/ReplacingStringTokenizer.java +++ b/strings/ReplacingStringTokenizer.java @@ -1,17 +1,19 @@ // 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.*; public class ReplacingStringTokenizer { public static void main(String[] args) { - String input = "But I'm not dead yet! I feel happy!"; + String input = + "But I'm not dead yet! I feel happy!"; StringTokenizer stoke = new StringTokenizer(input); while(stoke.hasMoreElements()) System.out.print(stoke.nextToken() + " "); System.out.println(); - System.out.println(Arrays.toString(input.split(" "))); + System.out.println( + Arrays.toString(input.split(" "))); Scanner scanner = new Scanner(input); while(scanner.hasNext()) System.out.print(scanner.next() + " "); 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 da9320a63..15533b973 100644 --- a/strings/SimpleRead.java +++ b/strings/SimpleRead.java @@ -1,19 +1,20 @@ // 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.*; public class SimpleRead { - public static BufferedReader input = new BufferedReader( - new StringReader("Sir Robin of Camelot\n22 1.61803")); + public static BufferedReader input = + new BufferedReader(new StringReader( + "Sir Robin of Camelot\n22 1.61803")); public static void main(String[] args) { try { System.out.println("What is your name?"); String name = input.readLine(); System.out.println(name); - System.out.println( - "How old are you? What is your favorite double?"); + System.out.println("How old are you? " + + "What is your favorite double?"); System.out.println("(input: )"); String numbers = input.readLine(); System.out.println(numbers); 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 ab91ea6d8..f22ea1a37 100644 --- a/strings/Splitting.java +++ b/strings/Splitting.java @@ -1,14 +1,14 @@ // 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.*; public class Splitting { public static String knights = - "Then, when you have found the shrubbery, you must " + - "cut down the mightiest tree in the forest... " + - "with... a herring!"; + "Then, when you have found the shrubbery, " + + "you must cut down the mightiest tree in the " + + "forest...with... a herring!"; public static void split(String regex) { System.out.println( Arrays.toString(knights.split(regex))); @@ -16,16 +16,17 @@ public static void split(String regex) { public static void main(String[] args) { split(" "); // Doesn't have to contain regex chars split("\\W+"); // Non-word characters - split("n\\W+"); // 'n' followed by non-word characters + split("n\\W+"); // 'n' followed by non-words } } /* Output: -[Then,, when, you, have, found, the, shrubbery,, you, must, -cut, down, the, mightiest, tree, in, the, forest..., -with..., a, herring!] -[Then, when, you, have, found, the, shrubbery, you, must, -cut, down, the, mightiest, tree, in, the, forest, with, a, -herring] -[The, whe, you have found the shrubbery, you must cut dow, -the mightiest tree i, the forest... with... a herring!] +[Then,, when, you, have, found, the, shrubbery,, you, +must, cut, down, the, mightiest, tree, in, the, +forest...with..., a, herring!] +[Then, when, you, have, found, the, shrubbery, you, +must, cut, down, the, mightiest, tree, in, the, forest, +with, a, herring] +[The, whe, you have found the shrubbery, you must cut +dow, the mightiest tree i, the forest...with... a +herring!] */ diff --git a/strings/StartEnd.java b/strings/StartEnd.java index 371b7d3dd..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.*; @@ -8,7 +8,8 @@ public class StartEnd { public static String input = "As long as there is injustice, whenever a\n" + "Targathian baby cries out, wherever a distress\n" + - "signal sounds among the stars ... We'll be there.\n"+ + "signal sounds among the stars " + + "... We'll be there.\n"+ "This fine ship, and this fine crew ...\n" + "Never give up! Never surrender!"; private static class Display { @@ -60,7 +61,8 @@ public static void main(String[] args) { T\w+ find() 'Targathian' start = 0 end = 10 lookingAt() start = 0 end = 10 -input : signal sounds among the stars ... We'll be there. +input : signal sounds among the stars ... We'll be +there. \w*ere\w* find() 'there' start = 43 end = 48 input : This fine ship, and this fine crew ... 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 133967972..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.*; @@ -18,14 +18,14 @@ public class TheReplacements { String s = Files.lines( Paths.get("TheReplacements.java")) .collect(Collectors.joining("\n")); - // Match the specially commented block of text above: + // Match specially commented block of text above: Matcher mInput = Pattern.compile( "/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s); if(mInput.find()) s = mInput.group(1); // Captured by parentheses // Replace two or more spaces with a single space: s = s.replaceAll(" {2,}", " "); - // Replace one or more spaces at the beginning of each + // Replace 1+ spaces at the beginning of each // line with no spaces. Must enable MULTILINE mode: s = s.replaceAll("(?m)^ +", ""); System.out.println(s); @@ -36,7 +36,8 @@ public class TheReplacements { // Process the find information as you // perform the replacements: while(m.find()) - m.appendReplacement(sbuf, m.group().toUpperCase()); + m.appendReplacement( + sbuf, m.group().toUpperCase()); // Put in the remainder of the text: m.appendTail(sbuf); System.out.println(sbuf); 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 3e80ce9ce..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.*; @@ -13,7 +13,8 @@ public Turtle(String name, Formatter f) { this.f = f; } public void move(int x, int y) { - f.format("%s The Turtle is at (%d,%d)%n", name, x, y); + f.format("%s The Turtle is at (%d,%d)%n", + name, x, y); } public static void main(String[] args) { PrintStream outAlias = System.out; diff --git a/strings/UsingStringBuilder.java b/strings/UsingStringBuilder.java index b7002a72e..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.*; @@ -30,8 +30,8 @@ public static void main(String[] args) { } } /* Output: -[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9, -78, 98, 61, 20, 58, 16, 40, 11, 22, 4] -[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9, -78, 98, 61, 20, 58, 16, 40, 11, 22, 4] +[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, +9, 78, 98, 61, 20, 58, 16, 40, 11, 22, 4] +[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, +9, 78, 98, 61, 20, 58, 16, 40, 11, 22, 4] */ 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 860c620bb..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/Shapes.java b/typeinfo/Shapes.java deleted file mode 100644 index e5f3243e6..000000000 --- a/typeinfo/Shapes.java +++ /dev/null @@ -1,38 +0,0 @@ -// typeinfo/Shapes.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.stream.*; - -abstract class Shape { - void draw() { System.out.println(this + ".draw()"); } - @Override - public abstract String toString(); -} - -class Circle extends Shape { - @Override - public String toString() { return "Circle"; } -} - -class Square extends Shape { - @Override - public String toString() { return "Square"; } -} - -class Triangle extends Shape { - @Override - public String toString() { return "Triangle"; } -} - -public class Shapes { - public static void main(String[] args) { - Stream.of(new Circle(), new Square(), new Triangle()) - .forEach(Shape::draw); - } -} -/* Output: -Circle.draw() -Square.draw() -Triangle.draw() -*/ diff --git a/typeinfo/pets/LiteralPetCreator.java b/typeinfo/pets/LiteralPetCreator.java deleted file mode 100644 index b0ac27bde..000000000 --- a/typeinfo/pets/LiteralPetCreator.java +++ /dev/null @@ -1,37 +0,0 @@ -// typeinfo/pets/LiteralPetCreator.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 class literals -// {java typeinfo.pets.LiteralPetCreator} -package typeinfo.pets; -import java.util.*; - -public class LiteralPetCreator extends PetCreator { - // No try block needed. - @SuppressWarnings("unchecked") - public static - final List> ALL_TYPES = - Collections.unmodifiableList(Arrays.asList( - Pet.class, Dog.class, Cat.class, Rodent.class, - Mutt.class, Pug.class, EgyptianMau.class, - Manx.class, Cymric.class, Rat.class, - Mouse.class, Hamster.class)); - // Types for random creation: - private static final List> TYPES = - ALL_TYPES.subList(ALL_TYPES.indexOf(Mutt.class), - ALL_TYPES.size()); - @Override - public List> types() { - return TYPES; - } - public static void main(String[] args) { - System.out.println(TYPES); - } -} -/* 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] -*/ 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 7c4f73a99..000000000 --- a/typeinfo/toys/GenericToyTest.java +++ /dev/null @@ -1,21 +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/update_extracted_example_output.py b/update_extracted_example_output.py deleted file mode 100644 index 3e21c2830..000000000 --- a/update_extracted_example_output.py +++ /dev/null @@ -1,35 +0,0 @@ -#! py -3 -# Requires Python 3.5 -# Updates generated output into extracted Java programs in "On Java 8" -from pathlib import Path -import pprint -import sys - -def remove_output(javatext): - result = "" - for line in javatext.splitlines(): - if "/* Output:" not in line: - result += line.rstrip() + "\n" - else: - return result - -def update_file(outfile): - print(str(outfile)) - javafile = outfile.with_suffix(".java") - if not javafile.exists(): - print(str(outfile) + " has no javafile") - sys.exit(1) - javatext = javafile.read_text() - if "/* Output:" not in javatext: - print(str(javafile) + " has no /* Output:") - sys.exit(1) - new_output = outfile.read_text() - new_javatext = remove_output(javatext) + new_output - javafile.write_text(new_javatext) - -if __name__ == '__main__': - if len(sys.argv) > 1: - update_file(Path(sys.argv[1])) - else: - for outfile in Path(".").rglob("*.p1"): - update_file(outfile) 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 42e6eb648..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 @@ -8,12 +8,13 @@ public class Assert2 { public static void main(String[] args) { - assert false: "Here's a message saying what happened"; + assert false: + "Here's a message saying what happened"; } } /* Output: ___[ Error Output ]___ -Exception in thread "main" java.lang.AssertionError: Here's -a message saying what happened +Exception in thread "main" java.lang.AssertionError: +Here's a message saying what happened at Assert2.main(Assert2.java:8) */ diff --git a/validating/BadMicroBenchmark.java b/validating/BadMicroBenchmark.java index 6a4cf7259..5e1ddbd7c 100644 --- a/validating/BadMicroBenchmark.java +++ b/validating/BadMicroBenchmark.java @@ -1,8 +1,8 @@ // 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. -// {ValidateByHand} +// {ExcludeFromTravisCI} import java.util.*; import onjava.Timer; @@ -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 0318edf60..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: 1360 -setAll: 125 -parallelSetAll: 75 -setAll: 17 +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 0fd8ff257..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. @@ -33,7 +33,8 @@ public static void main(String[] args) { System.out.println(e.getMessage()); } try { - verifyNotNull(s, "Shouldn't be null: %s", "arg s"); + verifyNotNull( + s, "Shouldn't be null: %s", "arg s"); } catch(VerifyException e) { System.out.println(e.getMessage()); } diff --git a/validating/GuavaPreconditions.java b/validating/GuavaPreconditions.java index fe06c574f..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 @@ -93,19 +93,18 @@ public static void main(String[] args) { null NullPointerException Robert -IndexOutOfBoundsException: index (6) must be less -than size (6) +IndexOutOfBoundsException: index (6) must be less than +size (6) Bob -IndexOutOfBoundsException: index (6) must be less -than size (3) +IndexOutOfBoundsException: index (6) must be less than +size (3) null NullPointerException Robert Success Bob -IndexOutOfBoundsException: index (6) -must not be greater -than size (3) +IndexOutOfBoundsException: index (6) must not be +greater than size (3) null NullPointerException Hieronymus @@ -113,15 +112,14 @@ than size (3) Hieronymus Success Hieronymus -IndexOutOfBoundsException: end index (11) -must not be greater -than size (10) +IndexOutOfBoundsException: end index (11) must not be +greater than size (10) Hieronymus -IndexOutOfBoundsException: start index (-1) -must not be negative +IndexOutOfBoundsException: start index (-1) must not be +negative Hieronymus -IndexOutOfBoundsException: end index (6) -must not be less than start index (7) +IndexOutOfBoundsException: end index (6) must not be +less than start index (7) null NullPointerException */ 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 9b1bd607a..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 @@ -23,5 +23,6 @@ public void go() { Exception in thread "main" java.lang.AssertionError: Loaded.go() at Loaded.go(LoaderAssertions.java:15) - at LoaderAssertions.main(LoaderAssertions.java:9) + at +LoaderAssertions.main(LoaderAssertions.java:9) */ 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 19214175e..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: -2016-08-22T14:33:01.951 +2021-01-24T08:49:37.658 [main] TRACE SLF4JLevels - Hello -2016-08-22T14:33:01.954 +2021-01-24T08:49:37.661 [main] DEBUG SLF4JLevels - Logging -2016-08-22T14:33:01.954 +2021-01-24T08:49:37.661 [main] INFO SLF4JLevels - Using -2016-08-22T14:33:01.955 +2021-01-24T08:49:37.661 [main] WARN SLF4JLevels - the SLF4J -2016-08-22T14:33:01.955 +2021-01-24T08:49:37.661 [main] ERROR SLF4JLevels - Facade */ diff --git a/validating/SLF4JLogging.java b/validating/SLF4JLogging.java index fc39e0ede..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: -2016-08-22T14:42:44.177 +2021-01-24T08:49:38.496 [main] INFO SLF4JLogging - hello logging */ diff --git a/validating/SimpleDebugging.java b/validating/SimpleDebugging.java index 476dcb9d8..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,15 +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:16) - at SimpleDebugging.foo2(SimpleDebugging.java:10) - at SimpleDebugging.foo1(SimpleDebugging.java:6) - at SimpleDebugging.main(SimpleDebugging.java:19) -*/ 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 eb96d230c..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; @@ -11,7 +11,7 @@ public class CircularQueueTest { private int i = 0; @BeforeEach public void initialize() { - while(i < 5) // Preload with some data + while(i < 5) // Pre-load with some data queue.put(Integer.toString(i++)); } // Support methods: 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); }); }