diff --git a/.gitignore b/.gitignore
index abe3365fc..48292956e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,6 +49,7 @@ Generated.txt
*-results.txt
*-out.txt
OutputErrors.txt
+report.txt
failures
People.xml
annotations/Test0.txt
@@ -71,9 +72,40 @@ io/X.file
/files/Cheese.txt
/files/StreamInAndOut.txt
-/.gradle/
+.gradle
/*.iml
/.idea/
/serialization/Blip3.serialized
/serialization/Blips.serialized
+
+build/
+buildSrc/
+
+/compression/test.gz
+/compression/test.zip
+/iostreams/BasicFileOutput.dat
+/iostreams/Data.txt
+/iostreams/FileOutputShortcut.dat
+/iostreams/rtest.dat
+/logging/LogToFile.xml
+/logging/LogToFile2.txt
+/logging/MultipleHandlers.xml
+/logging/MultipleHandlers2.xml
+/logging/java0.log
+/logging/java1.log
+/logging/java2.log
+/newio/TransferTo.txt
+/newio/data2.txt
+/newio/file.txt
+/newio/test.dat
+/newio/test.txt
+/serialization/CADState.dat
+/serialization/worm.dat
+/serialization/Logon.dat
+/serialization/X.file
+/standardio/Redirecting.txt
+/threads/PSP2.txt
+/threads/primes.txt
+_*
+config.py
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 48faf18b4..000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-language: java
-jdk:
- - oraclejdk8
-install: true
-script: ./gradlew run
diff --git a/.travisXX.yml b/.travisXX.yml
new file mode 100644
index 000000000..54fee6592
--- /dev/null
+++ b/.travisXX.yml
@@ -0,0 +1,8 @@
+language: java
+jdk:
+ - oraclejdk11
+install: true
+script:
+ - ./gradlew --no-daemon --stacktrace run
+# - ./gradlew --parallel --stacktrace run
+# - ./gradlew --parallel --stacktrace :validating:jmh
diff --git a/Ant-Clean.xml b/Ant-Clean.xml
deleted file mode 100644
index b15cb6f14..000000000
--- a/Ant-Clean.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-
-
-
- For this file to be included in all build.xml files
- at all directory levels, the single entries with the
- "**/" syntax must be used everywhere.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Ant-Common.xml b/Ant-Common.xml
deleted file mode 100644
index 43ef0b064..000000000
--- a/Ant-Common.xml
+++ /dev/null
@@ -1,216 +0,0 @@
-
-
-
-
-
-
- Ant build.xml for the source code for chapter ${chapter}
- Bruce Eckel On Java
- Code available at https://github.com/BruceEckel/OnJava-Examples
- See installation instructions in README.md
- See copyright notice in CopyRight.txt
-
- Ant available from http://ant.apache.org
-
- To see options, type: ant -p
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- [${chapter}] java @{cls} @{arguments}
- [${chapter}] java @{cls} @{arguments}
-
-
-
-
- [${chapter}] Finished: java @{cls} @{arguments}
- @{msg}
- --------------------------------
-
-
-
-
-
-
-
-
-
-
-
-
-
- [${chapter}] java @{cls} @{arguments}
- [${chapter}] java @{cls} @{arguments}
-
-
-
- [${chapter}] Finished: java @{cls} @{arguments}
- @{msg}
- --------------------------------
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Copyright.txt b/Copyright.txt
index 2b0c56fec..8eb3289e0 100644
--- a/Copyright.txt
+++ b/Copyright.txt
@@ -1,5 +1,5 @@
// Copyright.txt
-This computer source code is Copyright ©2016 MindView LLC
+This computer source code is Copyright ©2021 MindView LLC.
All Rights Reserved.
Permission to use, copy, modify, and distribute this
@@ -16,7 +16,7 @@ personal and commercial software programs.
2. Permission is granted to use the Source Code without
modification in classroom situations, including in
presentation materials, provided that the book "On
-Java" is cited as the origin.
+Java 8" is cited as the origin.
3. Permission to incorporate the Source Code into printed
media may be obtained by contacting:
@@ -64,9 +64,9 @@ ENHANCEMENTS, OR MODIFICATIONS.
Please note that MindView LLC maintains a Web site which
is the sole distribution point for electronic copies of the
-Source Code, https://github.com/BruceEckel/OnJava-Examples,
+Source Code, https://github.com/BruceEckel/OnJava8-examples,
where it is freely available under the terms stated above.
If you think you've found an error in the Source Code,
please submit a correction at:
-https://github.com/BruceEckel/OnJava-Examples/issues
+https://github.com/BruceEckel/OnJava8-examples/issues
diff --git a/HelloDate.java b/HelloDate.java
deleted file mode 100644
index dce03d0ba..000000000
--- a/HelloDate.java
+++ /dev/null
@@ -1,12 +0,0 @@
-// HelloDate.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.
-import java.util.*;
-
-public class HelloDate {
- public static void main(String[] args) {
- System.out.println("Hello, it's: ");
- System.out.println(new Date());
- }
-}
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
new file mode 100644
index 000000000..ad462ebc0
--- /dev/null
+++ b/README.md
@@ -0,0 +1,375 @@
+# Examples for *On Java 8* by Bruce Eckel
+
+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.
+
+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:
+
+`gradlew run`
+
+If you are on a Unix/Linux based system, you must select the local directory for all commands, for example:
+
+`./gradlew run`
+
+To only compile everything, the command is:
+
+`gradlew compileJava`
+
+To compile only a single chapter (including dependencies), use for example:
+
+`gradlew :strings:compileJava`
+
+To run only a single chapter, say:
+
+`gradlew :strings:run`
+
+Gradle can also be used to run a single program. Here, we run the **ReplacingStringTokenizer.java**
+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:
+
+`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.
+
+You can learn about other options by just typing `gradlew` with no arguments.
+
+# Appendix C: Troubleshooting
+
+If any terminology or processes described here remain unclear to you, you can
+usually find explanations or answers through [Google](https://www.google.com/).
+For more specific issues or problems, try
+[StackOverflow](http://stackoverflow.com/). Sometimes you can find installation
+instructions on [YouTube](https://www.youtube.com/).
+
+Sometimes a Gradle build will be unable to connect to the internet and download
+the necessary components, producing an error message containing:
+
+```
+javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
+```
+
+Normally this means you have multiple Java installations on your machine
+(applications built with Java ordinarily install their own version of Java), and
+somehow the `cacerts` security file is interfering with the `cacerts` file for
+the Java you have installed. It can be difficult to know which `cacerts` file is
+interfering with yours. The brute-force approach is to search for all the
+`cacerts` files on your machine and begin uninstalling the associated
+applications---or in some cases, simply removing the directory containing the
+`cacerts` file---until the Gradle build begins to work. You might also need to
+adjust some environment variables and/or your path. Once you get the Gradle
+build working successfully, you should be able to reinstall any applications you
+removed in the process.
diff --git a/annotations/AUComposition.java b/annotations/AUComposition.java
new file mode 100644
index 000000000..94d51e607
--- /dev/null
+++ b/annotations/AUComposition.java
@@ -0,0 +1,30 @@
+// 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/java/main/annotations/AUComposition.class}
+package annotations;
+import onjava.atunit.*;
+import onjava.*;
+
+public class AUComposition {
+ AtUnitExample1 testObject = new AtUnitExample1();
+ @Test
+ boolean tMethodOne() {
+ return testObject.methodOne()
+ .equals("This is methodOne");
+ }
+ @Test
+ boolean tMethodTwo() {
+ return testObject.methodTwo() == 2;
+ }
+}
+/* Output:
+annotations.AUComposition
+ . tMethodOne
+ . tMethodTwo This is methodTwo
+
+OK (2 tests)
+*/
diff --git a/annotations/AUExternalTest.java b/annotations/AUExternalTest.java
new file mode 100644
index 000000000..71c8f2f4b
--- /dev/null
+++ b/annotations/AUExternalTest.java
@@ -0,0 +1,29 @@
+// 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/java/main/annotations/AUExternalTest.class}
+package annotations;
+import onjava.atunit.*;
+import onjava.*;
+
+public class
+AUExternalTest extends AtUnitExample1 {
+ @Test
+ boolean tMethodOne() {
+ return methodOne().equals("This is methodOne");
+ }
+ @Test
+ boolean tMethodTwo() {
+ return methodTwo() == 2;
+ }
+}
+/* Output:
+annotations.AUExternalTest
+ . tMethodOne
+ . tMethodTwo This is methodTwo
+
+OK (2 tests)
+*/
diff --git a/annotations/AtUnitComposition.java b/annotations/AtUnitComposition.java
deleted file mode 100644
index 714d9b789..000000000
--- a/annotations/AtUnitComposition.java
+++ /dev/null
@@ -1,31 +0,0 @@
-// annotations/AtUnitComposition.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.
-// Creating non-embedded tests
-package annotations;
-import onjava.atunit.*;
-import onjava.*;
-
-public class AtUnitComposition {
- AtUnitExample1 testObject = new AtUnitExample1();
- @Test boolean _methodOne() {
- return
- testObject.methodOne().equals("This is methodOne");
- }
- @Test boolean _methodTwo() {
- return testObject.methodTwo() == 2;
- }
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitComposition.class");
- }
-}
-/* Output:
-annotations.AtUnitComposition
- . _methodOne
- . _methodTwo This is methodTwo
-
-OK (2 tests)
-*/
diff --git a/annotations/AtUnitExample1.java b/annotations/AtUnitExample1.java
index 3987752b5..de4cc6c64 100644
--- a/annotations/AtUnitExample1.java
+++ b/annotations/AtUnitExample1.java
@@ -1,7 +1,9 @@
// annotations/AtUnitExample1.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {java onjava.atunit.AtUnit
+// build/classes/java/main/annotations/AtUnitExample1.class}
package annotations;
import onjava.atunit.*;
import onjava.*;
@@ -14,18 +16,20 @@ public int methodTwo() {
System.out.println("This is methodTwo");
return 2;
}
- @Test boolean methodOneTest() {
+ @Test
+ boolean methodOneTest() {
return methodOne().equals("This is methodOne");
}
- @Test boolean m2() { return methodTwo() == 2; }
- @Test private boolean m3() { return true; }
+ @Test
+ boolean m2() { return methodTwo() == 2; }
+ @Test
+ private boolean m3() { return true; }
// Shows output for failure:
- @Test boolean failureTest() { return false; }
- @Test boolean anotherDisappointment() { return false; }
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitExample1.class");
+ @Test
+ boolean failureTest() { return false; }
+ @Test
+ boolean anotherDisappointment() {
+ return false;
}
}
/* Output:
@@ -33,9 +37,9 @@ public int methodTwo() {
. anotherDisappointment (failed)
. methodOneTest
. failureTest (failed)
- . m3
. m2 This is methodTwo
+ . m3
(5 tests)
>>> 2 FAILURES <<<
diff --git a/annotations/AtUnitExample2.java b/annotations/AtUnitExample2.java
index 467e61c12..855c33133 100644
--- a/annotations/AtUnitExample2.java
+++ b/annotations/AtUnitExample2.java
@@ -1,8 +1,10 @@
// annotations/AtUnitExample2.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Assertions and exceptions can be used in @Tests
+// {java onjava.atunit.AtUnit
+// build/classes/java/main/annotations/AtUnitExample2.class}
package annotations;
import java.io.*;
import onjava.atunit.*;
@@ -16,37 +18,37 @@ public int methodTwo() {
System.out.println("This is methodTwo");
return 2;
}
- @Test void assertExample() {
+ @Test
+ void assertExample() {
assert methodOne().equals("This is methodOne");
}
- @Test void assertFailureExample() {
+ @Test
+ void assertFailureExample() {
assert 1 == 2: "What a surprise!";
}
- @Test void exceptionExample() throws IOException {
- new FileInputStream("nofile.txt"); // Throws
+ @Test
+ void exceptionExample() throws IOException {
+ try(FileInputStream fis =
+ new FileInputStream("nofile.txt")) {} // Throws
}
- @Test boolean assertAndReturn() {
+ @Test
+ boolean assertAndReturn() {
// Assertion with message:
assert methodTwo() == 2: "methodTwo must equal 2";
return methodOne().equals("This is methodOne");
}
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitExample2.class");
- }
}
/* Output:
annotations.AtUnitExample2
- . assertFailureExample java.lang.AssertionError: What a
-surprise!
+ . assertFailureExample java.lang.AssertionError: What
+a surprise!
(failed)
. assertExample
- . assertAndReturn This is methodTwo
-
. exceptionExample java.io.FileNotFoundException:
nofile.txt (The system cannot find the file specified)
(failed)
+ . assertAndReturn This is methodTwo
+
(4 tests)
>>> 2 FAILURES <<<
diff --git a/annotations/AtUnitExample3.java b/annotations/AtUnitExample3.java
index f81eeb53b..ed1a93911 100644
--- a/annotations/AtUnitExample3.java
+++ b/annotations/AtUnitExample3.java
@@ -1,7 +1,9 @@
// annotations/AtUnitExample3.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {java onjava.atunit.AtUnit
+// build/classes/java/main/annotations/AtUnitExample3.class}
package annotations;
import onjava.atunit.*;
import onjava.*;
@@ -17,19 +19,18 @@ public int methodTwo() {
System.out.println("This is methodTwo");
return 2;
}
- @TestObjectCreate static AtUnitExample3 create() {
+ @TestObjectCreate
+ static AtUnitExample3 create() {
return new AtUnitExample3(47);
}
- @Test boolean initialization() { return n == 47; }
- @Test boolean methodOneTest() {
+ @Test
+ boolean initialization() { return n == 47; }
+ @Test
+ boolean methodOneTest() {
return methodOne().equals("This is methodOne");
}
- @Test boolean m2() { return methodTwo() == 2; }
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitExample3.class");
- }
+ @Test
+ boolean m2() { return methodTwo() == 2; }
}
/* Output:
annotations.AtUnitExample3
diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java
index 2c446ce04..23bc21efb 100644
--- a/annotations/AtUnitExample4.java
+++ b/annotations/AtUnitExample4.java
@@ -1,7 +1,10 @@
// annotations/AtUnitExample4.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {java onjava.atunit.AtUnit
+// build/classes/java/main/annotations/AtUnitExample4.class}
+// {VisuallyInspectOutput}
package annotations;
import java.util.*;
import onjava.atunit.*;
@@ -13,63 +16,68 @@ public class AtUnitExample4 {
"middle, and then thin again at the far end.";
private String word;
private Random rand = new Random(); // Time-based seed
- public AtUnitExample4(String word) { this.word = word; }
+ public AtUnitExample4(String word) {
+ this.word = word;
+ }
public String getWord() { return word; }
public String scrambleWord() {
- List chars =
- Arrays.asList(ConvertTo.boxed(word.toCharArray()));
+ List chars = Arrays.asList(
+ ConvertTo.boxed(word.toCharArray()));
Collections.shuffle(chars, rand);
StringBuilder result = new StringBuilder();
for(char ch : chars)
result.append(ch);
return result.toString();
}
- @TestProperty static List input =
+ @TestProperty
+ static List input =
Arrays.asList(theory.split(" "));
@TestProperty
- static Iterator words = input.iterator();
- @TestObjectCreate static AtUnitExample4 create() {
+ static Iterator words = input.iterator();
+ @TestObjectCreate
+ static AtUnitExample4 create() {
if(words.hasNext())
return new AtUnitExample4(words.next());
else
return null;
}
- @Test boolean words() {
+ @Test
+ boolean words() {
System.out.println("'" + getWord() + "'");
return getWord().equals("are");
}
- @Test boolean scramble1() {
- // Change to specific seed to get verifiable results:
+ @Test
+ boolean scramble1() {
+ // Use specific seed to get verifiable results:
rand = new Random(47);
System.out.println("'" + getWord() + "'");
String scrambled = scrambleWord();
System.out.println(scrambled);
return scrambled.equals("lAl");
}
- @Test boolean scramble2() {
+ @Test
+ boolean scramble2() {
rand = new Random(74);
System.out.println("'" + getWord() + "'");
String scrambled = scrambleWord();
System.out.println(scrambled);
return scrambled.equals("tsaeborornussu");
}
- public static void
- main(String[] args) throws Exception {
- System.out.println("starting");
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitExample4.class");
- }
}
/* Output:
-starting
annotations.AtUnitExample4
- . scramble1 'All'
-lAl
-
- . scramble2 'brontosauruses'
-tsaeborornussu
-
- . words 'are'
+ . words 'All'
+(failed)
+ . scramble1 'brontosauruses'
+ntsaueorosurbs
+(failed)
+ . scramble2 'are'
+are
+(failed)
+(3 tests)
-OK (3 tests)
+>>> 3 FAILURES <<<
+ annotations.AtUnitExample4: words
+ annotations.AtUnitExample4: scramble1
+ annotations.AtUnitExample4: scramble2
*/
diff --git a/annotations/AtUnitExample5.java b/annotations/AtUnitExample5.java
index 88370d683..4e4ceb4f4 100644
--- a/annotations/AtUnitExample5.java
+++ b/annotations/AtUnitExample5.java
@@ -1,7 +1,9 @@
// annotations/AtUnitExample5.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {java onjava.atunit.AtUnit
+// build/classes/java/main/annotations/AtUnitExample5.class}
package annotations;
import java.io.*;
import onjava.atunit.*;
@@ -9,12 +11,16 @@
public class AtUnitExample5 {
private String text;
- public AtUnitExample5(String text) { this.text = text; }
- @Override
- public String toString() { return text; }
- @TestProperty static PrintWriter output;
- @TestProperty static int counter;
- @TestObjectCreate static AtUnitExample5 create() {
+ public AtUnitExample5(String text) {
+ this.text = text;
+ }
+ @Override public String toString() { return text; }
+ @TestProperty
+ static PrintWriter output;
+ @TestProperty
+ static int counter;
+ @TestObjectCreate
+ static AtUnitExample5 create() {
String id = Integer.toString(counter++);
try {
output = new PrintWriter("Test" + id + ".txt");
@@ -23,36 +29,34 @@ public class AtUnitExample5 {
}
return new AtUnitExample5(id);
}
- @TestObjectCleanup static void
- cleanup(AtUnitExample5 tobj) {
+ @TestObjectCleanup
+ static void cleanup(AtUnitExample5 tobj) {
System.out.println("Running cleanup");
output.close();
}
- @Test boolean test1() {
+ @Test
+ boolean test1() {
output.print("test1");
return true;
}
- @Test boolean test2() {
+ @Test
+ boolean test2() {
output.print("test2");
return true;
}
- @Test boolean test3() {
+ @Test
+ boolean test3() {
output.print("test3");
return true;
}
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitExample5.class");
- }
}
/* Output:
annotations.AtUnitExample5
. test1
-Running cleanup
- . test2
Running cleanup
. test3
+Running cleanup
+ . test2
Running cleanup
OK (3 tests)
*/
diff --git a/annotations/AtUnitExternalTest.java b/annotations/AtUnitExternalTest.java
deleted file mode 100644
index 2016e0db9..000000000
--- a/annotations/AtUnitExternalTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-// annotations/AtUnitExternalTest.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.
-// Creating non-embedded tests
-package annotations;
-import onjava.atunit.*;
-import onjava.*;
-
-public class AtUnitExternalTest extends AtUnitExample1 {
- @Test boolean _methodOne() {
- return methodOne().equals("This is methodOne");
- }
- @Test boolean _methodTwo() { return methodTwo() == 2; }
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit AtUnitExternalTest.class");
- }
-}
-/* Output:
-annotations.AtUnitExternalTest
- . _methodTwo This is methodTwo
-
- . _methodOne
-OK (2 tests)
-*/
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 3d72063f1..5b6e7541a 100644
--- a/annotations/HashSetTest.java
+++ b/annotations/HashSetTest.java
@@ -1,7 +1,9 @@
// annotations/HashSetTest.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {java onjava.atunit.AtUnit
+// build/classes/java/main/annotations/HashSetTest.class}
package annotations;
import java.util.*;
import onjava.atunit.*;
@@ -9,28 +11,26 @@
public class HashSetTest {
HashSet testObject = new HashSet<>();
- @Test void initialization() {
+ @Test
+ void initialization() {
assert testObject.isEmpty();
}
- @Test void _contains() {
+ @Test
+ void tContains() {
testObject.add("one");
assert testObject.contains("one");
}
- @Test void _remove() {
+ @Test
+ void tRemove() {
testObject.add("one");
testObject.remove("one");
assert testObject.isEmpty();
}
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit HashSetTest.class");
- }
}
/* Output:
annotations.HashSetTest
+ . tContains
. initialization
- . _contains
- . _remove
+ . tRemove
OK (3 tests)
*/
diff --git a/annotations/PasswordUtils.java b/annotations/PasswordUtils.java
index 46c17e0aa..549412696 100644
--- a/annotations/PasswordUtils.java
+++ b/annotations/PasswordUtils.java
@@ -1,7 +1,7 @@
// annotations/PasswordUtils.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class PasswordUtils {
@@ -12,7 +12,8 @@ public boolean validatePassword(String passwd) {
}
@UseCase(id = 48)
public String encryptPassword(String passwd) {
- return new StringBuilder(passwd).reverse().toString();
+ return new StringBuilder(passwd)
+ .reverse().toString();
}
@UseCase(id = 49, description =
"New passwords can't equal previously used ones")
diff --git a/annotations/SimulatingNull.java b/annotations/SimulatingNull.java
index 263052be2..af1282f88 100644
--- a/annotations/SimulatingNull.java
+++ b/annotations/SimulatingNull.java
@@ -1,12 +1,12 @@
// annotations/SimulatingNull.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SimulatingNull {
- public int id() default -1;
- public String description() default "";
+ int id() default -1;
+ String description() default "";
}
diff --git a/annotations/StackL.java b/annotations/StackL.java
index 4ae80f9ee..246454c25 100644
--- a/annotations/StackL.java
+++ b/annotations/StackL.java
@@ -1,8 +1,8 @@
// annotations/StackL.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-// A stack built on a linkedList
+// Visit http://OnJava8.com for more book information.
+// A stack built on a LinkedList
package annotations;
import java.util.*;
diff --git a/annotations/StackLStringTest.java b/annotations/StackLStringTest.java
deleted file mode 100644
index 364038e6b..000000000
--- a/annotations/StackLStringTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-// annotations/StackLStringTest.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.
-// Applying @Unit to generics
-package annotations;
-import onjava.atunit.*;
-import onjava.*;
-
-public class StackLStringTest extends StackL {
- @Test void _push() {
- push("one");
- assert top().equals("one");
- push("two");
- assert top().equals("two");
- }
- @Test void _pop() {
- push("one");
- push("two");
- assert pop().equals("two");
- assert pop().equals("one");
- }
- @Test void _top() {
- push("A");
- push("B");
- assert top().equals("B");
- assert top().equals("B");
- }
- public static void
- main(String[] args) throws Exception {
- OSExecute.command("java -cp .. " +
- "onjava.atunit.AtUnit StackLStringTest.class");
- }
-}
-/* Output:
-annotations.StackLStringTest
- . _top
- . _push
- . _pop
-OK (3 tests)
-*/
diff --git a/annotations/StackLStringTst.java b/annotations/StackLStringTst.java
new file mode 100644
index 000000000..b7d8250f7
--- /dev/null
+++ b/annotations/StackLStringTst.java
@@ -0,0 +1,42 @@
+// 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/java/main/annotations/StackLStringTst.class}
+package annotations;
+import onjava.atunit.*;
+import onjava.*;
+
+public class
+StackLStringTst extends StackL {
+ @Test
+ void tPush() {
+ push("one");
+ assert top().equals("one");
+ push("two");
+ assert top().equals("two");
+ }
+ @Test
+ void tPop() {
+ push("one");
+ push("two");
+ assert pop().equals("two");
+ assert pop().equals("one");
+ }
+ @Test
+ void tTop() {
+ push("A");
+ push("B");
+ assert top().equals("B");
+ assert top().equals("B");
+ }
+}
+/* Output:
+annotations.StackLStringTst
+ . tPop
+ . tTop
+ . tPush
+OK (3 tests)
+*/
diff --git a/annotations/Testable.java b/annotations/Testable.java
index 369f2768c..b23d0e620 100644
--- a/annotations/Testable.java
+++ b/annotations/Testable.java
@@ -1,7 +1,7 @@
// annotations/Testable.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
package annotations;
import onjava.atunit.*;
@@ -9,5 +9,6 @@ public class Testable {
public void execute() {
System.out.println("Executing..");
}
- @Test void testExecute() { execute(); }
+ @Test
+ void testExecute() { execute(); }
}
diff --git a/annotations/UseCase.java b/annotations/UseCase.java
index c59a14633..c65735185 100644
--- a/annotations/UseCase.java
+++ b/annotations/UseCase.java
@@ -1,12 +1,12 @@
// annotations/UseCase.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
- public int id();
- public String description() default "no description";
+ int id();
+ String description() default "no description";
}
diff --git a/annotations/UseCaseTracker.java b/annotations/UseCaseTracker.java
index 91da32e58..53cc92795 100644
--- a/annotations/UseCaseTracker.java
+++ b/annotations/UseCaseTracker.java
@@ -1,9 +1,10 @@
// annotations/UseCaseTracker.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import java.lang.reflect.*;
+// Visit http://OnJava8.com for more book information.
import java.util.*;
+import java.util.stream.*;
+import java.lang.reflect.*;
public class UseCaseTracker {
public static void
@@ -11,28 +12,26 @@ public class UseCaseTracker {
for(Method m : cl.getDeclaredMethods()) {
UseCase uc = m.getAnnotation(UseCase.class);
if(uc != null) {
- System.out.println("Found Use Case:" + uc.id() +
- " " + uc.description());
- useCases.remove(new Integer(uc.id()));
+ System.out.println("Found Use Case " +
+ uc.id() + "\n " + uc.description());
+ useCases.remove(Integer.valueOf(uc.id()));
}
}
- for(int i : useCases) {
- System.out.println(
- "Warning: Missing use case-" + i);
- }
+ useCases.forEach(i ->
+ System.out.println("Missing use case " + i));
}
public static void main(String[] args) {
- // <* Can't use Arrays.asList() for some reason *>
- List useCases = new ArrayList<>();
- Collections.addAll(useCases, 47, 48, 49, 50);
+ List useCases = IntStream.range(47, 51)
+ .boxed().collect(Collectors.toList());
trackUseCases(useCases, PasswordUtils.class);
}
}
/* 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
-Warning: Missing use case-50
+Found Use Case 49
+ New passwords can't equal previously used ones
+Found Use Case 48
+ no description
+Found Use Case 47
+ Passwords must contain at least one numeric
+Missing use case 50
*/
diff --git a/annotations/build.xml b/annotations/build.xml
deleted file mode 100644
index c530c3fab..000000000
--- a/annotations/build.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/annotations/database/Constraints.java b/annotations/database/Constraints.java
index b16105e54..5631f52e9 100644
--- a/annotations/database/Constraints.java
+++ b/annotations/database/Constraints.java
@@ -1,7 +1,7 @@
// annotations/database/Constraints.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
package annotations.database;
import java.lang.annotation.*;
diff --git a/annotations/database/DBTable.java b/annotations/database/DBTable.java
index 2ff972fb6..3d345d990 100644
--- a/annotations/database/DBTable.java
+++ b/annotations/database/DBTable.java
@@ -1,12 +1,12 @@
// annotations/database/DBTable.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
package annotations.database;
import java.lang.annotation.*;
@Target(ElementType.TYPE) // Applies to classes only
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
- public String name() default "";
+ String name() default "";
}
diff --git a/annotations/database/Member.java b/annotations/database/Member.java
index f7b5bf347..ae5723ac8 100644
--- a/annotations/database/Member.java
+++ b/annotations/database/Member.java
@@ -1,7 +1,7 @@
// annotations/database/Member.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
package annotations.database;
@DBTable(name = "MEMBER")
@@ -11,12 +11,13 @@ public class Member {
@SQLInteger Integer age;
@SQLString(value = 30,
constraints = @Constraints(primaryKey = true))
- String handle;
+ String reference;
static int memberCount;
- public String getHandle() { return handle; }
+ public String getReference() { return reference; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
- @Override
- public String toString() { return handle; }
+ @Override public String toString() {
+ return reference;
+ }
public Integer getAge() { return age; }
}
diff --git a/annotations/database/SQLInteger.java b/annotations/database/SQLInteger.java
index cffcb86b0..4df1e7dd6 100644
--- a/annotations/database/SQLInteger.java
+++ b/annotations/database/SQLInteger.java
@@ -1,7 +1,7 @@
// annotations/database/SQLInteger.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
package annotations.database;
import java.lang.annotation.*;
diff --git a/annotations/database/SQLString.java b/annotations/database/SQLString.java
index fbb6195aa..c452d1e95 100644
--- a/annotations/database/SQLString.java
+++ b/annotations/database/SQLString.java
@@ -1,7 +1,7 @@
// annotations/database/SQLString.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
package annotations.database;
import java.lang.annotation.*;
diff --git a/annotations/database/TableCreator.java b/annotations/database/TableCreator.java
index ebd70bdd1..d2be7c5e1 100644
--- a/annotations/database/TableCreator.java
+++ b/annotations/database/TableCreator.java
@@ -1,9 +1,10 @@
// annotations/database/TableCreator.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Reflection-based annotation processor
-// {Args: annotations.database.Member}
+// {java annotations.database.TableCreator
+// annotations.database.Member}
package annotations.database;
import java.lang.annotation.*;
import java.lang.reflect.*;
@@ -13,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) {
@@ -21,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();
@@ -65,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";
@@ -81,22 +85,22 @@ 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),
AGE INT,
- HANDLE VARCHAR(30) PRIMARY KEY);
+ REFERENCE VARCHAR(30) PRIMARY KEY);
*/
diff --git a/annotations/database/Uniqueness.java b/annotations/database/Uniqueness.java
index 2ede0e41b..7959fe700 100644
--- a/annotations/database/Uniqueness.java
+++ b/annotations/database/Uniqueness.java
@@ -1,11 +1,11 @@
// annotations/database/Uniqueness.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Sample of nested annotations
package annotations.database;
public @interface Uniqueness {
Constraints constraints()
- default @Constraints(unique = true);
+ default @Constraints(unique = true);
}
diff --git a/annotations/ifx/ExtractInterface.java b/annotations/ifx/ExtractInterface.java
index 68c320380..c823fe9ca 100644
--- a/annotations/ifx/ExtractInterface.java
+++ b/annotations/ifx/ExtractInterface.java
@@ -1,7 +1,7 @@
// annotations/ifx/ExtractInterface.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// javac-based annotation processing
package annotations.ifx;
import java.lang.annotation.*;
@@ -9,5 +9,5 @@
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface ExtractInterface {
- public String interfaceName() default "-!!-";
+ String interfaceName() default "-!!-";
}
diff --git a/annotations/ifx/IfaceExtractorProcessor.java b/annotations/ifx/IfaceExtractorProcessor.java
index a0e92df97..fae22607c 100644
--- a/annotations/ifx/IfaceExtractorProcessor.java
+++ b/annotations/ifx/IfaceExtractorProcessor.java
@@ -1,7 +1,7 @@
// annotations/ifx/IfaceExtractorProcessor.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// javac-based annotation processing
package annotations.ifx;
import javax.annotation.processing.*;
@@ -9,6 +9,7 @@
import javax.lang.model.element.*;
import javax.lang.model.util.*;
import java.util.*;
+import java.util.stream.*;
import java.io.*;
@SupportedAnnotationTypes(
@@ -20,14 +21,14 @@ public class IfaceExtractorProcessor
interfaceMethods = new ArrayList<>();
Elements elementUtils;
private ProcessingEnvironment processingEnv;
- @Override public void
- init(ProcessingEnvironment processingEnv) {
+ @Override public void init(
+ ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
elementUtils = processingEnv.getElementUtils();
}
- @Override public boolean
- process(Set extends TypeElement> annotations,
- RoundEnvironment env) {
+ @Override public boolean process(
+ Set extends TypeElement> annotations,
+ RoundEnvironment env) {
for(Element elem:env.getElementsAnnotatedWith(
ExtractInterface.class)) {
String interfaceName = elem.getAnnotation(
@@ -50,9 +51,11 @@ public class IfaceExtractorProcessor
}
private void
writeInterfaceFile(String interfaceName) {
- try(Writer writer = processingEnv.getFiler()
- .createSourceFile(interfaceName)
- .openWriter()) {
+ try(
+ Writer writer = processingEnv.getFiler()
+ .createSourceFile(interfaceName)
+ .openWriter()
+ ) {
String packageName = elementUtils
.getPackageOf(interfaceMethods
.get(0)).toString();
@@ -64,7 +67,7 @@ public class IfaceExtractorProcessor
ExecutableElement method =
(ExecutableElement)elem;
String signature = " public ";
- signature += method.getReturnType()+" ";
+ signature += method.getReturnType() + " ";
signature += method.getSimpleName();
signature += createArgList(
method.getParameters());
@@ -78,15 +81,9 @@ public class IfaceExtractorProcessor
}
private String createArgList(
List extends VariableElement> parameters) {
- if(parameters.size() == 0)
- return "()";
- String args = "(";
- for(VariableElement p : parameters) {
- args += p.asType() + " ";
- args += p.getSimpleName() + ", ";
- }
- args = args.substring(0, args.length() - 2);
- args += ")";
- return args;
+ String args = parameters.stream()
+ .map(p -> p.asType() + " " + p.getSimpleName())
+ .collect(Collectors.joining(", "));
+ return "(" + args + ")";
}
}
diff --git a/annotations/ifx/Multiplier.java b/annotations/ifx/Multiplier.java
index d66270f27..25678fd5a 100644
--- a/annotations/ifx/Multiplier.java
+++ b/annotations/ifx/Multiplier.java
@@ -1,8 +1,9 @@
// annotations/ifx/Multiplier.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// javac-based annotation processing
+// {java annotations.ifx.Multiplier}
package annotations.ifx;
@ExtractInterface(interfaceName="IMultiplier")
diff --git a/annotations/simplest/Simple.java b/annotations/simplest/Simple.java
index 7e1b8ce96..101b7900a 100644
--- a/annotations/simplest/Simple.java
+++ b/annotations/simplest/Simple.java
@@ -1,7 +1,7 @@
// annotations/simplest/Simple.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// A bare-bones annotation
package annotations.simplest;
import java.lang.annotation.Retention;
diff --git a/annotations/simplest/SimpleProcessor.java b/annotations/simplest/SimpleProcessor.java
index b42f2d6ef..1dda51955 100644
--- a/annotations/simplest/SimpleProcessor.java
+++ b/annotations/simplest/SimpleProcessor.java
@@ -1,7 +1,7 @@
// annotations/simplest/SimpleProcessor.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// A bare-bones annotation processor
package annotations.simplest;
import javax.annotation.processing.*;
@@ -14,9 +14,9 @@
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SimpleProcessor
extends AbstractProcessor {
- @Override public boolean
- process(Set extends TypeElement> annotations,
- RoundEnvironment env) {
+ @Override public boolean process(
+ Set extends TypeElement> annotations,
+ RoundEnvironment env) {
for(TypeElement t : annotations)
System.out.println(t);
for(Element el :
diff --git a/annotations/simplest/SimpleTest.java b/annotations/simplest/SimpleTest.java
index 2e0caf5de..e97d5871e 100644
--- a/annotations/simplest/SimpleTest.java
+++ b/annotations/simplest/SimpleTest.java
@@ -1,8 +1,9 @@
// annotations/simplest/SimpleTest.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Test the "Simple" annotation
+// {java annotations.simplest.SimpleTest}
package annotations.simplest;
@Simple
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index 013d861cd..000000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-build_script:
- - gradlew.bat runconsole --stacktrace
-
-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 01c768c5b..a6dea2c2e 100644
--- a/arrays/AlphabeticSearch.java
+++ b/arrays/AlphabeticSearch.java
@@ -1,8 +1,8 @@
// arrays/AlphabeticSearch.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-// Searching with a Comparator
+// Visit http://OnJava8.com for more book information.
+// Searching with a Comparator import
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
@@ -12,17 +12,18 @@ public static void main(String[] args) {
String[] sa = new Rand.String().array(30);
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
show(sa);
- int index = Arrays.binarySearch(sa, sa[10],
- String.CASE_INSENSITIVE_ORDER);
+ int index = Arrays.binarySearch(sa,
+ sa[10], String.CASE_INSENSITIVE_ORDER);
System.out.println(
- "Index: "+ index + "\n"+ sa[index]);
+ "Index: "+ index + "\n"+ sa[index]);
}
}
/* Output:
-[bkIna, cQrGs, cXZJo, dLsmw, eGZMm, EqUCB, gwsqP, hKcxr,
-HLGEa, HqXum, HxxHv, JMRoE, JmzMs, Mesbt, MNvqe, nyGcF,
-ogoYW, OneOE, OWZnT, RFJQA, rUkZP, sgqia, slJrL, suEcU,
-uTpnX, vpfFv, WHkjU, xxEAJ, YNzbr, zDyCy]
+[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
-HxxHv
+gmeinne
*/
diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java
index 52fa0ff4e..b5dc136f8 100644
--- a/arrays/ArrayCopying.java
+++ b/arrays/ArrayCopying.java
@@ -1,7 +1,7 @@
// arrays/ArrayCopying.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Demonstrate Arrays.copy() and Arrays.copyOf()
import java.util.*;
import onjava.*;
@@ -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);
@@ -49,32 +48,32 @@ public static void main(String[] args) {
Arrays.setAll(d, Sub::new);
// Produce Sup[] from Sub[]:
Sup[] b =
- Arrays.copyOf(d, d.length, Sup[].class); // (4)
+ Arrays.copyOf(d, d.length, Sup[].class); // [4]
show(b);
// This "downcast" works fine:
Sub[] d2 =
- Arrays.copyOf(b, b.length, Sub[].class); // (5)
+ Arrays.copyOf(b, b.length, Sub[].class); // [5]
show(d2);
// Bad "downcast" compiles but throws exception:
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);
}
}
}
/* Output:
-a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
-a1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
-a2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
-a2 = [0, 1, 2, 3, 4, 5, 6]
-a2 = [0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0]
-a4 = [4, 5, 6, 7, 8, 9, 10, 11]
+a1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
+a1: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
+a2: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
+a2: [0, 1, 2, 3, 4, 5, 6]
+a2: [0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0]
+a4: [4, 5, 6, 7, 8, 9, 10, 11]
[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6]
[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6]
java.lang.ArrayStoreException
diff --git a/arrays/ArrayOfGenericType.java b/arrays/ArrayOfGenericType.java
index bd89ffddf..6c2df8468 100644
--- a/arrays/ArrayOfGenericType.java
+++ b/arrays/ArrayOfGenericType.java
@@ -1,14 +1,14 @@
// arrays/ArrayOfGenericType.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
public class ArrayOfGenericType {
T[] array; // OK
@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 b205e82b5..8040dfa1f 100644
--- a/arrays/ArrayOfGenerics.java
+++ b/arrays/ArrayOfGenerics.java
@@ -1,7 +1,7 @@
// arrays/ArrayOfGenerics.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class ArrayOfGenerics {
@@ -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 2107cae9d..c313d9a29 100644
--- a/arrays/ArrayOptions.java
+++ b/arrays/ArrayOptions.java
@@ -1,7 +1,7 @@
// arrays/ArrayOptions.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Initialization & re-assignment of arrays
import java.util.*;
import static onjava.ArrayShow.*;
@@ -9,7 +9,7 @@
public class ArrayOptions {
public static void main(String[] args) {
// Arrays of objects:
- BerylliumSphere[] a; // Local uninitialized variable
+ BerylliumSphere[] a; // Uninitialized local
BerylliumSphere[] b = new BerylliumSphere[5];
// The references inside the array are
diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java
index 2868744b9..deae72faf 100644
--- a/arrays/ArraySearching.java
+++ b/arrays/ArraySearching.java
@@ -1,7 +1,7 @@
// arrays/ArraySearching.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Using Arrays.binarySearch()
import java.util.*;
import onjava.*;
@@ -9,8 +9,8 @@
public class ArraySearching {
public static void main(String[] args) {
- Rand.int_ rand = new Rand.int_();
- int[] a = new Rand.int_().array(25);
+ Rand.Pint rand = new Rand.Pint();
+ int[] a = new Rand.Pint().array(25);
Arrays.sort(a);
show("Sorted array", a);
while(true) {
diff --git a/arrays/AssemblingMultidimensionalArrays.java b/arrays/AssemblingMultidimensionalArrays.java
index 5667961f7..945c338e4 100644
--- a/arrays/AssemblingMultidimensionalArrays.java
+++ b/arrays/AssemblingMultidimensionalArrays.java
@@ -1,7 +1,7 @@
// arrays/AssemblingMultidimensionalArrays.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Creating multidimensional arrays
import java.util.*;
diff --git a/arrays/AutoboxingArrays.java b/arrays/AutoboxingArrays.java
index 08cbe7133..d8601627c 100644
--- a/arrays/AutoboxingArrays.java
+++ b/arrays/AutoboxingArrays.java
@@ -1,7 +1,7 @@
// arrays/AutoboxingArrays.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class AutoboxingArrays {
@@ -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/BadMicroBenchmark.java b/arrays/BadMicroBenchmark.java
deleted file mode 100644
index 765df060d..000000000
--- a/arrays/BadMicroBenchmark.java
+++ /dev/null
@@ -1,21 +0,0 @@
-// arrays/BadMicroBenchmark.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.
-import java.util.*;
-import static onjava.TimeIt.*;
-
-public class BadMicroBenchmark {
- static final int SIZE = 20_000_000;
- public static void main(String[] args) {
- long[] la = new long[SIZE];
- System.out.print("setAll: ");
- timeIt(() -> Arrays.setAll(la, n -> n));
- System.out.print("parallelSetAll: ");
- timeIt(() -> Arrays.parallelSetAll(la, n -> n));
- }
-}
-/* Output:
-setAll: 27
-parallelSetAll: 53
-*/
diff --git a/arrays/BadMicroBenchmark2.java b/arrays/BadMicroBenchmark2.java
deleted file mode 100644
index b4db07002..000000000
--- a/arrays/BadMicroBenchmark2.java
+++ /dev/null
@@ -1,22 +0,0 @@
-// arrays/BadMicroBenchmark2.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.
-// Reversing the test order
-import java.util.*;
-import static onjava.TimeIt.*;
-
-public class BadMicroBenchmark2 {
- static final int SIZE = 20_000_000;
- public static void main(String[] args) {
- long[] la = new long[SIZE];
- System.out.print("parallelSetAll: ");
- timeIt(() -> Arrays.parallelSetAll(la, n -> n));
- System.out.print("setAll: ");
- timeIt(() -> Arrays.setAll(la, n -> n));
- }
-}
-/* Output:
-parallelSetAll: 38
-setAll: 63
-*/
diff --git a/arrays/BadMicroBenchmark3.java b/arrays/BadMicroBenchmark3.java
deleted file mode 100644
index aea7532c6..000000000
--- a/arrays/BadMicroBenchmark3.java
+++ /dev/null
@@ -1,34 +0,0 @@
-// arrays/BadMicroBenchmark3.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.
-// Relying on a common resource
-import java.util.*;
-import static onjava.TimeIt.*;
-
-public class BadMicroBenchmark3 {
- static final int SIZE = 20_000_000;
- public static void main(String[] args) {
- long[] la = new long[SIZE];
- Random r = new Random();
- System.out.print("parallelSetAll: ");
- timeIt(() ->
- Arrays.parallelSetAll(la, n -> r.nextLong()));
- System.out.print("setAll: ");
- timeIt(() ->
- Arrays.setAll(la, n -> r.nextLong()));
- SplittableRandom sr = new SplittableRandom();
- System.out.print("parallelSetAll: ");
- timeIt(() ->
- Arrays.parallelSetAll(la, n -> sr.nextLong()));
- System.out.print("setAll: ");
- timeIt(() ->
- Arrays.setAll(la, n -> sr.nextLong()));
- }
-}
-/* Output:
-parallelSetAll: 5150
-setAll: 649
-parallelSetAll: 277
-setAll: 246
-*/
diff --git a/arrays/CollectionComparison.java b/arrays/CollectionComparison.java
index 51ae19ade..b5f0b1132 100644
--- a/arrays/CollectionComparison.java
+++ b/arrays/CollectionComparison.java
@@ -1,7 +1,7 @@
// arrays/CollectionComparison.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
@@ -9,13 +9,15 @@
class BerylliumSphere {
private static long counter;
private final long id = counter++;
- @Override
- public String toString() { return "Sphere " + id; }
+ @Override public String toString() {
+ return "Sphere " + id;
+ }
}
public class CollectionComparison {
public static void main(String[] args) {
- BerylliumSphere[] spheres = new BerylliumSphere[10];
+ BerylliumSphere[] spheres =
+ new BerylliumSphere[10];
for(int i = 0; i < 5; i++)
spheres[i] = new BerylliumSphere();
show(spheres);
@@ -38,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 70a1587e1..8d7e82a33 100644
--- a/arrays/CompType.java
+++ b/arrays/CompType.java
@@ -1,7 +1,7 @@
// arrays/CompType.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Implementing Comparable in a class
import java.util.*;
import java.util.function.*;
@@ -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,16 +39,16 @@ public static void main(String[] args) {
}
}
/* Output:
-before sorting:
-[[i = 58, j = 55], [i = 93, j = 61], [i = 61, j = 29]
-, [i = 68, j = 0], [i = 22, j = 7], [i = 88, j = 28]
-, [i = 51, j = 89], [i = 9, j = 78], [i = 98, j = 61]
-, [i = 20, j = 58], [i = 16, j = 40], [i = 11, j = 22]
+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 = 9, j = 78], [i = 11, j = 22], [i = 16, j = 40]
-, [i = 20, j = 58], [i = 22, j = 7], [i = 51, j = 89]
-, [i = 58, j = 55], [i = 61, j = 29], [i = 68, j = 0]
-, [i = 88, j = 28], [i = 93, j = 61], [i = 98, j = 61]
+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 85abb45a8..fbe385879 100644
--- a/arrays/ComparatorTest.java
+++ b/arrays/ComparatorTest.java
@@ -1,13 +1,14 @@
// arrays/ComparatorTest.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Implementing a Comparator for a class
import java.util.*;
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,16 +24,16 @@ public static void main(String[] args) {
}
}
/* Output:
-before sorting:
-[[i = 58, j = 55], [i = 93, j = 61], [i = 61, j = 29]
-, [i = 68, j = 0], [i = 22, j = 7], [i = 88, j = 28]
-, [i = 51, j = 89], [i = 9, j = 78], [i = 98, j = 61]
-, [i = 20, j = 58], [i = 16, j = 40], [i = 11, j = 22]
+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 = 68, j = 0], [i = 22, j = 7], [i = 11, j = 22]
-, [i = 88, j = 28], [i = 61, j = 29], [i = 16, j = 40]
-, [i = 58, j = 55], [i = 20, j = 58], [i = 93, j = 61]
-, [i = 98, j = 61], [i = 9, j = 78], [i = 51, j = 89]
+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 bbdcdfe30..c97c22d04 100644
--- a/arrays/ComparingArrays.java
+++ b/arrays/ComparingArrays.java
@@ -1,14 +1,14 @@
// arrays/ComparingArrays.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Using Arrays.equals()
import java.util.*;
import onjava.*;
public class ComparingArrays {
public static final int SZ = 15;
- static String[][] TwoDArray() {
+ static String[][] twoDArray() {
String[][] md = new String[5][];
Arrays.setAll(md, n -> new String[n]);
for(int i = 0; i < md.length; i++)
@@ -35,7 +35,7 @@ public static void main(String[] args) {
System.out.println(
"a1w == a2w: " + Arrays.equals(a1w, a2w));
- String[][] md1 = TwoDArray(), md2 = TwoDArray();
+ String[][] md1 = twoDArray(), md2 = twoDArray();
System.out.println(Arrays.deepToString(md1));
System.out.println("deepEquals(md1, md2): " +
Arrays.deepEquals(md1, md2));
@@ -52,9 +52,11 @@ public static void main(String[] args) {
a1 == a2: false
a1w == a2w: true
a1w == a2w: false
-[[], [YNzbrny], [YNzbrny, GcFOWZn], [YNzbrny, GcFOWZn, TcQrGse], [YNzbrny, GcFOWZn, TcQrGse, GZMmJMR]]
+[[], [btpenpc], [btpenpc, cuxszgv], [btpenpc, cuxszgv,
+gmeinne], [btpenpc, cuxszgv, gmeinne, eloztdv]]
deepEquals(md1, md2): true
md1 == md2: false
-[[], [YNzbrny], [YNzbrny, GcFOWZn], [YNzbrny, GcFOWZn, TcQrGse], [YNzbrny, #$#$#$#, TcQrGse, GZMmJMR]]
+[[], [btpenpc], [btpenpc, cuxszgv], [btpenpc, cuxszgv,
+gmeinne], [btpenpc, #$#$#$#, gmeinne, eloztdv]]
deepEquals(md1, md2): false
*/
diff --git a/arrays/CountUpward.java b/arrays/CountUpward.java
index 490995837..3ac361c86 100644
--- a/arrays/CountUpward.java
+++ b/arrays/CountUpward.java
@@ -1,7 +1,7 @@
// arrays/CountUpward.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*;
import static onjava.ArrayShow.*;
@@ -19,5 +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 9c27d8323..b7445dfdb 100644
--- a/arrays/FillingArrays.java
+++ b/arrays/FillingArrays.java
@@ -1,7 +1,7 @@
// arrays/FillingArrays.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Using Arrays.fill()
import java.util.*;
import static onjava.ArrayShow.*;
@@ -42,14 +42,14 @@ public static void main(String[] args) {
}
}
/* Output:
-a1 = [true, true, true, true, true, true]
-a2 = [11, 11, 11, 11, 11, 11]
-a3 = [x, x, x, x, x, x]
-a4 = [17, 17, 17, 17, 17, 17]
-a5 = [19, 19, 19, 19, 19, 19]
-a6 = [23, 23, 23, 23, 23, 23]
-a7 = [29.0, 29.0, 29.0, 29.0, 29.0, 29.0]
-a8 = [47.0, 47.0, 47.0, 47.0, 47.0, 47.0]
-a9 = [Hello, Hello, Hello, Hello, Hello, Hello]
-a9 = [Hello, Hello, Hello, World, World, Hello]
+a1: [true, true, true, true, true, true]
+a2: [11, 11, 11, 11, 11, 11]
+a3: [x, x, x, x, x, x]
+a4: [17, 17, 17, 17, 17, 17]
+a5: [19, 19, 19, 19, 19, 19]
+a6: [23, 23, 23, 23, 23, 23]
+a7: [29.0, 29.0, 29.0, 29.0, 29.0, 29.0]
+a8: [47.0, 47.0, 47.0, 47.0, 47.0, 47.0]
+a9: [Hello, Hello, Hello, Hello, Hello, Hello]
+a9: [Hello, Hello, Hello, World, World, Hello]
*/
diff --git a/arrays/IceCream.java b/arrays/IceCreamFlavors.java
similarity index 66%
rename from arrays/IceCream.java
rename to arrays/IceCreamFlavors.java
index 7ee32d7b7..1be802edd 100644
--- a/arrays/IceCream.java
+++ b/arrays/IceCreamFlavors.java
@@ -1,12 +1,12 @@
-// arrays/IceCream.java
-// (c)2016 MindView LLC: see Copyright.txt
+// arrays/IceCreamFlavors.java
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Returning arrays from methods
import java.util.*;
import static onjava.ArrayShow.*;
-public class IceCream {
+public class IceCreamFlavors {
private static SplittableRandom rand =
new SplittableRandom(47);
static final String[] FLAVORS = {
@@ -35,11 +35,11 @@ public static void main(String[] args) {
}
}
/* Output:
-[Rum Raisin, Mint Chip, Mocha Almond Fudge]
-[Chocolate, Strawberry, Mocha Almond Fudge]
-[Strawberry, Mint Chip, Mocha Almond Fudge]
-[Rum Raisin, Vanilla Fudge Swirl, Mud Pie]
-[Vanilla Fudge Swirl, Chocolate, Mocha Almond Fudge]
-[Praline Cream, Strawberry, Mocha Almond Fudge]
-[Mocha Almond Fudge, Strawberry, Mint Chip]
+[Praline Cream, Mint Chip, Vanilla Fudge Swirl]
+[Strawberry, Vanilla Fudge Swirl, Mud Pie]
+[Chocolate, Strawberry, Vanilla Fudge Swirl]
+[Rum Raisin, Praline Cream, Chocolate]
+[Mint Chip, Rum Raisin, Mocha Almond Fudge]
+[Mocha Almond Fudge, Mud Pie, Vanilla Fudge Swirl]
+[Mocha Almond Fudge, Mud Pie, Mint Chip]
*/
diff --git a/arrays/ModifyExisting.java b/arrays/ModifyExisting.java
index 3db997b11..0c33b8d19 100644
--- a/arrays/ModifyExisting.java
+++ b/arrays/ModifyExisting.java
@@ -1,7 +1,7 @@
// arrays/ModifyExisting.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
@@ -11,11 +11,12 @@ 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);
}
}
/* Output:
-[0.73, 0.53, 0.16, 0.19, 0.52, 0.27, 0.26]
-[0.0073, 0.0053, 0.0016, 0.0019, 0.0052, 0.0027, 0.0026]
+[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99]
+[0.0483, 0.028900000000000002, 0.028999999999999998,
+0.0197, 0.0301, 0.0018, 0.009899999999999999]
*/
diff --git a/arrays/MultiDimWrapperArray.java b/arrays/MultiDimWrapperArray.java
index 9c6c927a2..5055a1cbf 100644
--- a/arrays/MultiDimWrapperArray.java
+++ b/arrays/MultiDimWrapperArray.java
@@ -1,7 +1,7 @@
// arrays/MultiDimWrapperArray.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Multidimensional arrays of "wrapper" objects
import java.util.*;
@@ -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 465e5ea25..8c91e7b5a 100644
--- a/arrays/MultidimensionalObjectArrays.java
+++ b/arrays/MultidimensionalObjectArrays.java
@@ -1,7 +1,7 @@
// arrays/MultidimensionalObjectArrays.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class MultidimensionalObjectArrays {
@@ -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 1162f60fa..ffebf2b6f 100644
--- a/arrays/MultidimensionalPrimitiveArray.java
+++ b/arrays/MultidimensionalPrimitiveArray.java
@@ -1,7 +1,7 @@
// arrays/MultidimensionalPrimitiveArray.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class MultidimensionalPrimitiveArray {
diff --git a/arrays/Prefix1.java b/arrays/ParallelPrefix1.java
similarity index 68%
rename from arrays/Prefix1.java
rename to arrays/ParallelPrefix1.java
index fa3629a3c..243753168 100644
--- a/arrays/Prefix1.java
+++ b/arrays/ParallelPrefix1.java
@@ -1,21 +1,21 @@
-// arrays/Prefix1.java
-// (c)2016 MindView LLC: see Copyright.txt
+// arrays/ParallelPrefix1.java
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
-public class Prefix1 {
+public class ParallelPrefix1 {
public static void main(String[] args) {
- int[] nums = new Count.int_().array(10);
+ int[] nums = new Count.Pint().array(10);
show(nums);
System.out.println(Arrays.stream(nums)
.reduce(Integer::sum).getAsInt());
Arrays.parallelPrefix(nums, Integer::sum);
show(nums);
System.out.println(Arrays.stream(
- new Count.int_().array(6))
+ new Count.Pint().array(6))
.reduce(Integer::sum).getAsInt());
}
}
diff --git a/arrays/Prefix2.java b/arrays/ParallelPrefix2.java
similarity index 72%
rename from arrays/Prefix2.java
rename to arrays/ParallelPrefix2.java
index 645482697..c7963fe83 100644
--- a/arrays/Prefix2.java
+++ b/arrays/ParallelPrefix2.java
@@ -1,12 +1,12 @@
-// arrays/Prefix2.java
-// (c)2016 MindView LLC: see Copyright.txt
+// arrays/ParallelPrefix2.java
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
-public class Prefix2 {
+public class ParallelPrefix2 {
public static void main(String[] args) {
String[] strings = new Rand.String(1).array(8);
show(strings);
diff --git a/arrays/ParallelPrefix.java b/arrays/ParallelPrefix3.java
similarity index 64%
rename from arrays/ParallelPrefix.java
rename to arrays/ParallelPrefix3.java
index 104ebfdc5..88d32916e 100644
--- a/arrays/ParallelPrefix.java
+++ b/arrays/ParallelPrefix3.java
@@ -1,11 +1,12 @@
-// arrays/ParallelPrefix.java
-// (c)2016 MindView LLC: see Copyright.txt
+// arrays/ParallelPrefix3.java
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {ExcludeFromTravisCI}
import java.util.*;
-public class ParallelPrefix {
- static final int SIZE = 20_000_000;
+public class ParallelPrefix3 {
+ static final int SIZE = 10_000_000;
public static void main(String[] args) {
long[] nums = new long[SIZE];
Arrays.setAll(nums, n -> n);
@@ -18,5 +19,5 @@ public static void main(String[] args) {
/* Output:
First 20: 190
First 200: 19900
-All: 199999990000000
+All: 49999995000000
*/
diff --git a/arrays/ParallelSetAll.java b/arrays/ParallelSetAll.java
index c17a0225f..787d2daf9 100644
--- a/arrays/ParallelSetAll.java
+++ b/arrays/ParallelSetAll.java
@@ -1,21 +1,21 @@
// arrays/ParallelSetAll.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
public class ParallelSetAll {
- static final int SIZE = 20_000_000;
+ static final int SIZE = 10_000_000;
static void intArray() {
int[] ia = new int[SIZE];
- Arrays.setAll(ia, new Rand.int_()::get);
- Arrays.parallelSetAll(ia, new Rand.int_()::get);
+ Arrays.setAll(ia, new Rand.Pint()::get);
+ Arrays.parallelSetAll(ia, new Rand.Pint()::get);
}
static void longArray() {
long[] la = new long[SIZE];
- Arrays.setAll(la, new Rand.long_()::get);
- Arrays.parallelSetAll(la, new Rand.long_()::get);
+ Arrays.setAll(la, new Rand.Plong()::get);
+ Arrays.parallelSetAll(la, new Rand.Plong()::get);
}
public static void main(String[] args) {
intArray();
diff --git a/arrays/ParallelSort.java b/arrays/ParallelSort.java
deleted file mode 100644
index 4b724c80f..000000000
--- a/arrays/ParallelSort.java
+++ /dev/null
@@ -1,26 +0,0 @@
-// arrays/ParallelSort.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.
-import java.util.*;
-import java.time.*;
-import onjava.*;
-import static onjava.TimeIt.*;
-
-public class ParallelSort {
- static final int SZ = 10_000_000;
- public static void main(String[] args) {
- int[] ia1 = new Rand.int_().array(SZ);
- int[] ia2 = Arrays.copyOf(ia1, ia1.length);
- System.out.print("sort(): ");
- long millis1 = timeIt(() -> Arrays.sort(ia1));
- System.out.print("parallelSort(): ");
- long millis2 = timeIt(() -> Arrays.parallelSort(ia2));
- System.out.println(millis1/millis2);
- }
-}
-/* Output:
-sort(): 484
-parallelSort(): 149
-3
-*/
diff --git a/arrays/ParameterizedArrayType.java b/arrays/ParameterizedArrayType.java
index b8fff08a1..7213afde5 100644
--- a/arrays/ParameterizedArrayType.java
+++ b/arrays/ParameterizedArrayType.java
@@ -1,7 +1,7 @@
// arrays/ParameterizedArrayType.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
class ClassParameter {
public T[] f(T[] arg) { return arg; }
diff --git a/arrays/PythonLists.py b/arrays/PythonLists.py
index 2d8ed47e8..3ed60ee91 100644
--- a/arrays/PythonLists.py
+++ b/arrays/PythonLists.py
@@ -1,7 +1,7 @@
# arrays/PythonLists.py
-# (c)2016 MindView LLC: see Copyright.txt
+# (c)2021 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.
+# Visit http://OnJava8.com for more book information.
aList = [1, 2, 3, 4, 5]
print(type(aList)) #
@@ -14,13 +14,13 @@
print(aSlice) # [3, 4]
class MyList(list): # Inherit from list
- # Define a method, 'this' pointer is explicit:
+ # Define a method; 'this' pointer is explicit:
def getReversed(self):
reversed = self[:] # Copy list using slices
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 78125295c..dfae93d64 100644
--- a/arrays/RaggedArray.java
+++ b/arrays/RaggedArray.java
@@ -1,7 +1,7 @@
// arrays/RaggedArray.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class RaggedArray {
@@ -14,14 +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, 13], [14], [15, 16, 17, 18]], [[19, 20, 21],
-[22, 23, 24], [25], []], [[26], [], [27]]]
+[[[1], []], [[2, 3, 4, 5], [6]], [[7, 8, 9], [10, 11,
+12], []]]
*/
diff --git a/arrays/Reverse.java b/arrays/Reverse.java
index 729cf395b..0f2719cec 100644
--- a/arrays/Reverse.java
+++ b/arrays/Reverse.java
@@ -1,7 +1,7 @@
// arrays/Reverse.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// The Collections.reverseOrder() Comparator
import java.util.*;
import onjava.*;
@@ -17,16 +17,16 @@ public static void main(String[] args) {
}
}
/* Output:
-before sorting:
-[[i = 58, j = 55], [i = 93, j = 61], [i = 61, j = 29]
-, [i = 68, j = 0], [i = 22, j = 7], [i = 88, j = 28]
-, [i = 51, j = 89], [i = 9, j = 78], [i = 98, j = 61]
-, [i = 20, j = 58], [i = 16, j = 40], [i = 11, j = 22]
+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 = 98, j = 61], [i = 93, j = 61], [i = 88, j = 28]
-, [i = 68, j = 0], [i = 61, j = 29], [i = 58, j = 55]
-, [i = 51, j = 89], [i = 22, j = 7], [i = 20, j = 58]
-, [i = 16, j = 40], [i = 11, j = 22], [i = 9, j = 78]
+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 698fc0c3d..072975b00 100644
--- a/arrays/SimpleSetAll.java
+++ b/arrays/SimpleSetAll.java
@@ -1,20 +1,21 @@
// arrays/SimpleSetAll.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import static onjava.ArrayShow.*;
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 9808bdaad..b30ed6d44 100644
--- a/arrays/StreamFromArray.java
+++ b/arrays/StreamFromArray.java
@@ -1,7 +1,7 @@
// arrays/StreamFromArray.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
@@ -14,7 +14,7 @@ public static void main(String[] args) {
.map(ss -> ss + "!")
.forEach(System.out::println);
- int[] ia = new Rand.int_().array(10);
+ int[] ia = new Rand.Pint().array(10);
Arrays.stream(ia)
.skip(3)
.limit(5)
@@ -32,7 +32,7 @@ public static void main(String[] args) {
//- Arrays.stream(new float[10]);
// For the other types you must use wrapped arrays:
- float[] fa = new Rand.float_().array(10);
+ float[] fa = new Rand.Pfloat().array(10);
Arrays.stream(ConvertTo.boxed(fa));
Arrays.stream(new Rand.Float().array(10));
}
diff --git a/arrays/StringSorting.java b/arrays/StringSorting.java
index bbdac6df9..aef57048d 100644
--- a/arrays/StringSorting.java
+++ b/arrays/StringSorting.java
@@ -1,7 +1,7 @@
// arrays/StringSorting.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Sorting an array of Strings
import java.util.*;
import onjava.*;
@@ -20,16 +20,20 @@ public static void main(String[] args) {
}
}
/* Output:
-Before sort: [YNzbr, nyGcF, OWZnT, cQrGs, eGZMm, JMRoE,
-suEcU, OneOE, dLsmw, HLGEa, hKcxr, EqUCB, bkIna, Mesbt,
-WHkjU, rUkZP, gwsqP, zDyCy, RFJQA, HxxHv]
-After sort: [EqUCB, HLGEa, HxxHv, JMRoE, Mesbt, OWZnT,
-OneOE, RFJQA, WHkjU, YNzbr, bkIna, cQrGs, dLsmw, eGZMm,
-gwsqP, hKcxr, nyGcF, rUkZP, suEcU, zDyCy]
-Reverse sort: [zDyCy, suEcU, rUkZP, nyGcF, hKcxr, gwsqP,
-eGZMm, dLsmw, cQrGs, bkIna, YNzbr, WHkjU, RFJQA, OneOE,
-OWZnT, Mesbt, JMRoE, HxxHv, HLGEa, EqUCB]
-Case-insensitive sort: [bkIna, cQrGs, dLsmw, eGZMm, EqUCB,
-gwsqP, hKcxr, HLGEa, HxxHv, JMRoE, Mesbt, nyGcF, OneOE,
-OWZnT, RFJQA, rUkZP, suEcU, WHkjU, YNzbr, zDyCy]
+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 1970be8bb..8b8f849a5 100644
--- a/arrays/TestConvertTo.java
+++ b/arrays/TestConvertTo.java
@@ -1,65 +1,65 @@
// arrays/TestConvertTo.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import onjava.*;
import static onjava.ArrayShow.*;
import static onjava.ConvertTo.*;
public class TestConvertTo {
- static final int size = 6;
+ static final int SIZE = 6;
public static void main(String[] args) {
- Boolean[] a1 = new Boolean[size];
+ Boolean[] a1 = new Boolean[SIZE];
Arrays.setAll(a1, new Rand.Boolean()::get);
boolean[] a1p = primitive(a1);
show("a1p", a1p);
Boolean[] a1b = boxed(a1p);
show("a1b", a1b);
- Byte[] a2 = new Byte[size];
+ Byte[] a2 = new Byte[SIZE];
Arrays.setAll(a2, new Rand.Byte()::get);
byte[] a2p = primitive(a2);
show("a2p", a2p);
Byte[] a2b = boxed(a2p);
show("a2b", a2b);
- Character[] a3 = new Character[size];
+ Character[] a3 = new Character[SIZE];
Arrays.setAll(a3, new Rand.Character()::get);
char[] a3p = primitive(a3);
show("a3p", a3p);
Character[] a3b = boxed(a3p);
show("a3b", a3b);
- Short[] a4 = new Short[size];
+ Short[] a4 = new Short[SIZE];
Arrays.setAll(a4, new Rand.Short()::get);
short[] a4p = primitive(a4);
show("a4p", a4p);
Short[] a4b = boxed(a4p);
show("a4b", a4b);
- Integer[] a5 = new Integer[size];
+ Integer[] a5 = new Integer[SIZE];
Arrays.setAll(a5, new Rand.Integer()::get);
int[] a5p = primitive(a5);
show("a5p", a5p);
Integer[] a5b = boxed(a5p);
show("a5b", a5b);
- Long[] a6 = new Long[size];
+ Long[] a6 = new Long[SIZE];
Arrays.setAll(a6, new Rand.Long()::get);
long[] a6p = primitive(a6);
show("a6p", a6p);
Long[] a6b = boxed(a6p);
show("a6b", a6b);
- Float[] a7 = new Float[size];
+ Float[] a7 = new Float[SIZE];
Arrays.setAll(a7, new Rand.Float()::get);
float[] a7p = primitive(a7);
show("a7p", a7p);
Float[] a7b = boxed(a7p);
show("a7b", a7b);
- Double[] a8 = new Double[size];
+ Double[] a8 = new Double[SIZE];
Arrays.setAll(a8, new Rand.Double()::get);
double[] a8p = primitive(a8);
show("a8p", a8p);
diff --git a/arrays/TestCount.java b/arrays/TestCount.java
index 909f6fb11..b6b3e7b8d 100644
--- a/arrays/TestCount.java
+++ b/arrays/TestCount.java
@@ -1,7 +1,7 @@
// arrays/TestCount.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Test counting generators
import java.util.*;
import java.util.stream.*;
@@ -15,82 +15,109 @@ public static void main(String[] args) {
Boolean[] a1 = new Boolean[SZ];
Arrays.setAll(a1, new Count.Boolean()::get);
show(a1);
- show(Stream.generate(new Count.Boolean())
- .limit(SZ + 1).toArray());
- show(new Count.Boolean().array(SZ + 2));
- show(new Count.boolean_().array(SZ + 3));
+ a1 = Stream.generate(new Count.Boolean())
+ .limit(SZ + 1).toArray(Boolean[]::new);
+ show(a1);
+ a1 = new Count.Boolean().array(SZ + 2);
+ show(a1);
+ boolean[] a1b =
+ new Count.Pboolean().array(SZ + 3);
+ show(a1b);
System.out.println("Byte");
Byte[] a2 = new Byte[SZ];
Arrays.setAll(a2, new Count.Byte()::get);
show(a2);
- show(Stream.generate(new Count.Byte())
- .limit(SZ + 1).toArray());
- show(new Count.Byte().array(SZ + 2));
- show(new Count.byte_().array(SZ + 3));
+ a2 = Stream.generate(new Count.Byte())
+ .limit(SZ + 1).toArray(Byte[]::new);
+ show(a2);
+ a2 = new Count.Byte().array(SZ + 2);
+ show(a2);
+ byte[] a2b = new Count.Pbyte().array(SZ + 3);
+ show(a2b);
System.out.println("Character");
Character[] a3 = new Character[SZ];
Arrays.setAll(a3, new Count.Character()::get);
show(a3);
- show(Stream.generate(new Count.Character())
- .limit(SZ + 1).toArray());
- show(new Count.Character().array(SZ + 2));
- show(new Count.char_().array(SZ + 3));
+ a3 = Stream.generate(new Count.Character())
+ .limit(SZ + 1).toArray(Character[]::new);
+ show(a3);
+ a3 = new Count.Character().array(SZ + 2);
+ show(a3);
+ char[] a3b = new Count.Pchar().array(SZ + 3);
+ show(a3b);
System.out.println("Short");
Short[] a4 = new Short[SZ];
Arrays.setAll(a4, new Count.Short()::get);
show(a4);
- show(Stream.generate(new Count.Short())
- .limit(SZ + 1).toArray());
- show(new Count.Short().array(SZ + 2));
- show(new Count.short_().array(SZ + 3));
+ a4 = Stream.generate(new Count.Short())
+ .limit(SZ + 1).toArray(Short[]::new);
+ show(a4);
+ a4 = new Count.Short().array(SZ + 2);
+ show(a4);
+ short[] a4b = new Count.Pshort().array(SZ + 3);
+ show(a4b);
System.out.println("Integer");
int[] a5 = new int[SZ];
Arrays.setAll(a5, new Count.Integer()::get);
show(a5);
- show(Stream.generate(new Count.Integer())
- .limit(SZ + 1).toArray());
- show(new Count.Integer().array(SZ + 2));
- a5 = IntStream.generate(new Count.int_())
+ Integer[] a5b =
+ Stream.generate(new Count.Integer())
+ .limit(SZ + 1).toArray(Integer[]::new);
+ show(a5b);
+ a5b = new Count.Integer().array(SZ + 2);
+ show(a5b);
+ a5 = IntStream.generate(new Count.Pint())
.limit(SZ + 1).toArray();
show(a5);
- show(new Count.int_().array(SZ + 3));
+ a5 = new Count.Pint().array(SZ + 3);
+ show(a5);
System.out.println("Long");
long[] a6 = new long[SZ];
Arrays.setAll(a6, new Count.Long()::get);
show(a6);
- show(Stream.generate(new Count.Long())
- .limit(SZ + 1).toArray());
- show(new Count.Long().array(SZ + 2));
- a6 = LongStream.generate(new Count.long_())
+ Long[] a6b = Stream.generate(new Count.Long())
+ .limit(SZ + 1).toArray(Long[]::new);
+ show(a6b);
+ a6b = new Count.Long().array(SZ + 2);
+ show(a6b);
+ a6 = LongStream.generate(new Count.Plong())
.limit(SZ + 1).toArray();
show(a6);
- show(new Count.long_().array(SZ + 3));
+ a6 = new Count.Plong().array(SZ + 3);
+ show(a6);
System.out.println("Float");
Float[] a7 = new Float[SZ];
Arrays.setAll(a7, new Count.Float()::get);
show(a7);
- show(Stream.generate(new Count.Float())
- .limit(SZ + 1).toArray());
- show(new Count.Float().array(SZ + 2));
- show(new Count.float_().array(SZ + 3));
+ a7 = Stream.generate(new Count.Float())
+ .limit(SZ + 1).toArray(Float[]::new);
+ show(a7);
+ a7 = new Count.Float().array(SZ + 2);
+ show(a7);
+ float[] a7b = new Count.Pfloat().array(SZ + 3);
+ show(a7b);
System.out.println("Double");
double[] a8 = new double[SZ];
Arrays.setAll(a8, new Count.Double()::get);
show(a8);
- show(Stream.generate(new Count.Double())
- .limit(SZ + 1).toArray());
- show(new Count.Double().array(SZ + 2));
- a8 = DoubleStream.generate(new Count.double_())
+ Double[] a8b =
+ Stream.generate(new Count.Double())
+ .limit(SZ + 1).toArray(Double[]::new);
+ show(a8b);
+ a8b = new Count.Double().array(SZ + 2);
+ show(a8b);
+ a8 = DoubleStream.generate(new Count.Pdouble())
.limit(SZ + 1).toArray();
show(a8);
- show(new Count.double_().array(SZ + 3));
+ a8 = new Count.Pdouble().array(SZ + 3);
+ show(a8);
}
}
/* Output:
diff --git a/arrays/TestRand.java b/arrays/TestRand.java
index 56ee188e6..45d248ade 100644
--- a/arrays/TestRand.java
+++ b/arrays/TestRand.java
@@ -1,7 +1,7 @@
// arrays/TestRand.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Test random generators
import java.util.*;
import java.util.stream.*;
@@ -15,96 +15,127 @@ public static void main(String[] args) {
Boolean[] a1 = new Boolean[SZ];
Arrays.setAll(a1, new Rand.Boolean()::get);
show(a1);
- show(Stream.generate(new Rand.Boolean())
- .limit(SZ + 1).toArray());
- show(new Rand.Boolean().array(SZ + 2));
- show(new Rand.boolean_().array(SZ + 3));
+ a1 = Stream.generate(new Rand.Boolean())
+ .limit(SZ + 1).toArray(Boolean[]::new);
+ show(a1);
+ a1 = new Rand.Boolean().array(SZ + 2);
+ show(a1);
+ boolean[] a1b =
+ new Rand.Pboolean().array(SZ + 3);
+ show(a1b);
System.out.println("Byte");
Byte[] a2 = new Byte[SZ];
Arrays.setAll(a2, new Rand.Byte()::get);
show(a2);
- show(Stream.generate(new Rand.Byte())
- .limit(SZ + 1).toArray());
- show(new Rand.Byte().array(SZ + 2));
- show(new Rand.byte_().array(SZ + 3));
+ a2 = Stream.generate(new Rand.Byte())
+ .limit(SZ + 1).toArray(Byte[]::new);
+ show(a2);
+ a2 = new Rand.Byte().array(SZ + 2);
+ show(a2);
+ byte[] a2b = new Rand.Pbyte().array(SZ + 3);
+ show(a2b);
System.out.println("Character");
Character[] a3 = new Character[SZ];
Arrays.setAll(a3, new Rand.Character()::get);
show(a3);
- show(Stream.generate(new Rand.Character())
- .limit(SZ + 1).toArray());
- show(new Rand.Character().array(SZ + 2));
- show(new Rand.char_().array(SZ + 3));
+ a3 = Stream.generate(new Rand.Character())
+ .limit(SZ + 1).toArray(Character[]::new);
+ show(a3);
+ a3 = new Rand.Character().array(SZ + 2);
+ show(a3);
+ char[] a3b = new Rand.Pchar().array(SZ + 3);
+ show(a3b);
System.out.println("Short");
Short[] a4 = new Short[SZ];
Arrays.setAll(a4, new Rand.Short()::get);
show(a4);
- show(Stream.generate(new Rand.Short())
- .limit(SZ + 1).toArray());
- show(new Rand.Short().array(SZ + 2));
- show(new Rand.short_().array(SZ + 3));
+ a4 = Stream.generate(new Rand.Short())
+ .limit(SZ + 1).toArray(Short[]::new);
+ show(a4);
+ a4 = new Rand.Short().array(SZ + 2);
+ show(a4);
+ short[] a4b = new Rand.Pshort().array(SZ + 3);
+ show(a4b);
System.out.println("Integer");
int[] a5 = new int[SZ];
Arrays.setAll(a5, new Rand.Integer()::get);
show(a5);
- show(Stream.generate(new Rand.Integer())
- .limit(SZ + 1).toArray());
- show(new Rand.Integer().array(SZ + 2));
- a5 = IntStream.generate(new Rand.int_())
+ Integer[] a5b =
+ Stream.generate(new Rand.Integer())
+ .limit(SZ + 1).toArray(Integer[]::new);
+ show(a5b);
+ a5b = new Rand.Integer().array(SZ + 2);
+ show(a5b);
+ a5 = IntStream.generate(new Rand.Pint())
.limit(SZ + 1).toArray();
show(a5);
- show(new Rand.int_().array(SZ + 3));
+ a5 = new Rand.Pint().array(SZ + 3);
+ show(a5);
System.out.println("Long");
long[] a6 = new long[SZ];
Arrays.setAll(a6, new Rand.Long()::get);
show(a6);
- show(Stream.generate(new Rand.Long())
- .limit(SZ + 1).toArray());
- show(new Rand.Long().array(SZ + 2));
- a6 = LongStream.generate(new Rand.long_())
+ Long[] a6b = Stream.generate(new Rand.Long())
+ .limit(SZ + 1).toArray(Long[]::new);
+ show(a6b);
+ a6b = new Rand.Long().array(SZ + 2);
+ show(a6b);
+ a6 = LongStream.generate(new Rand.Plong())
.limit(SZ + 1).toArray();
show(a6);
- show(new Rand.long_().array(SZ + 3));
+ a6 = new Rand.Plong().array(SZ + 3);
+ show(a6);
System.out.println("Float");
Float[] a7 = new Float[SZ];
Arrays.setAll(a7, new Rand.Float()::get);
show(a7);
- show(Stream.generate(new Rand.Float())
- .limit(SZ + 1).toArray());
- show(new Rand.Float().array(SZ + 2));
- show(new Rand.float_().array(SZ + 3));
+ a7 = Stream.generate(new Rand.Float())
+ .limit(SZ + 1).toArray(Float[]::new);
+ show(a7);
+ a7 = new Rand.Float().array(SZ + 2);
+ show(a7);
+ float[] a7b = new Rand.Pfloat().array(SZ + 3);
+ show(a7b);
System.out.println("Double");
double[] a8 = new double[SZ];
Arrays.setAll(a8, new Rand.Double()::get);
show(a8);
- show(Stream.generate(new Rand.Double())
- .limit(SZ + 1).toArray());
- show(new Rand.Double().array(SZ + 2));
- a8 = DoubleStream.generate(new Rand.double_())
- .limit(SZ + 2).toArray();
+ Double[] a8b =
+ Stream.generate(new Rand.Double())
+ .limit(SZ + 1).toArray(Double[]::new);
+ show(a8b);
+ a8b = new Rand.Double().array(SZ + 2);
+ show(a8b);
+ a8 = DoubleStream.generate(new Rand.Pdouble())
+ .limit(SZ + 1).toArray();
+ show(a8);
+ a8 = new Rand.Pdouble().array(SZ + 3);
show(a8);
- show(new Rand.double_().array(SZ + 3));
System.out.println("String");
String[] s = new String[SZ - 1];
Arrays.setAll(s, new Rand.String()::get);
show(s);
- show(Stream.generate(new Rand.String())
- .limit(SZ).toArray());
- show(new Rand.String().array(SZ + 1));
+ s = Stream.generate(new Rand.String())
+ .limit(SZ).toArray(String[]::new);
+ show(s);
+ s = new Rand.String().array(SZ + 1);
+ show(s);
Arrays.setAll(s, new Rand.String(4)::get);
show(s);
- show(Stream.generate(new Rand.String(4))
- .limit(SZ).toArray());
- show(new Rand.String(4).array(SZ + 1));
+ s = Stream.generate(new Rand.String(4))
+ .limit(SZ).toArray(String[]::new);
+ show(s);
+ s = new Rand.String(4).array(SZ + 1);
+ show(s);
}
}
/* Output:
@@ -149,13 +180,13 @@ public static void main(String[] args) {
[4.83, 2.89, 2.9, 1.97, 3.01]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99]
-[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99]
+[4.83, 2.89, 2.9, 1.97, 3.01, 0.18]
[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99, 8.28]
String
[btpenpc, cuxszgv, gmeinne, eloztdv]
[btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc]
[btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc, ygpoalk]
-[btpe, npcc, uxsz, gvgm]
+[btpe, npcc, uxsz, gvgm, einn, eelo]
[btpe, npcc, uxsz, gvgm, einn]
[btpe, npcc, uxsz, gvgm, einn, eelo]
*/
diff --git a/arrays/ThreeDWithNew.java b/arrays/ThreeDWithNew.java
index ca175fa29..f1ab3393a 100644
--- a/arrays/ThreeDWithNew.java
+++ b/arrays/ThreeDWithNew.java
@@ -1,7 +1,7 @@
// arrays/ThreeDWithNew.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class ThreeDWithNew {
diff --git a/arrays/build.xml b/arrays/build.xml
deleted file mode 100644
index 97d2372da..000000000
--- a/arrays/build.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/arrays/jmh/ParallelSort.java b/arrays/jmh/ParallelSort.java
new file mode 100644
index 000000000..64ff004d3
--- /dev/null
+++ b/arrays/jmh/ParallelSort.java
@@ -0,0 +1,25 @@
+// arrays/jmh/ParallelSort.java
+// (c)2021 MindView 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;
+import java.util.*;
+import onjava.*;
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ParallelSort {
+ private long[] la;
+ @Setup
+ public void setup() {
+ la = new Rand.Plong().array(100_000);
+ }
+ @Benchmark
+ public void sort() {
+ Arrays.sort(la);
+ }
+ @Benchmark
+ public void parallelSort() {
+ Arrays.parallelSort(la);
+ }
+}
diff --git a/assertions/Assert2.java b/assertions/Assert2.java
deleted file mode 100644
index 0549ede0e..000000000
--- a/assertions/Assert2.java
+++ /dev/null
@@ -1,20 +0,0 @@
-// assertions/Assert2.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.
-// Assert with an information-expression
-// {JVMArgs: -ea}
-// {ThrowsException}
-
-public class Assert2 {
- public static void main(String[] args) {
- 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
- at Assert2.main(Assert2.java:8)
-___[ Exception is Expected ]___
-*/
diff --git a/assertions/Queue.java b/assertions/Queue.java
deleted file mode 100644
index 8d6b43567..000000000
--- a/assertions/Queue.java
+++ /dev/null
@@ -1,236 +0,0 @@
-// assertions/Queue.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.
-// Demonstration of Design by Contract (DbC)
-// combined with white-box unit testing
-// (Install libraries from www.junit.org)
-import java.util.*;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-
-public class Queue {
- private Object[] data;
- private int
- in = 0, // Next available storage space
- out = 0; // Next gettable object
- // Has it wrapped around the circular queue?
- private boolean wrapped = false;
- public static class
- QueueException extends RuntimeException {
- public QueueException(String why) { super(why); }
- }
- public Queue(int size) {
- data = new Object[size];
- // Must be true after construction:
- assert invariant();
- }
- public boolean empty() {
- return !wrapped && in == out;
- }
- public boolean full() {
- return wrapped && in == out;
- }
- public void put(Object item) {
- precondition(item != null, "put() null item");
- precondition(!full(), "put() into full Queue");
- assert invariant();
- data[in++] = item;
- if(in >= data.length) {
- in = 0;
- wrapped = true;
- }
- assert invariant();
- }
- public Object get() {
- precondition(!empty(), "get() from empty Queue");
- assert invariant();
- Object returnVal = data[out];
- data[out] = null;
- out++;
- if(out >= data.length) {
- out = 0;
- wrapped = false;
- }
- assert postcondition(
- returnVal != null, "Null item in Queue");
- assert invariant();
- return returnVal;
- }
- // Design-by-contract support methods:
- private static void
- precondition(boolean cond, String msg) {
- if(!cond) throw new QueueException(msg);
- }
- private static boolean
- postcondition(boolean cond, String msg) {
- if(!cond) throw new QueueException(msg);
- return true;
- }
- private boolean invariant() {
- // Guarantee that no null values are in the
- // region of 'data' that holds objects:
- for(int i = out; i != in; i = (i + 1) % data.length)
- if(data[i] == null)
- throw new QueueException("null in queue");
- // Guarantee that only null values are outside the
- // region of 'data' that holds objects:
- if(full()) return true;
- for(int i = in; i != out; i = (i + 1) % data.length)
- if(data[i] != null)
- throw new QueueException(
- "non-null outside of queue range: " + dump());
- return true;
- }
- private String dump() {
- return "in = " + in +
- ", out = " + out +
- ", full() = " + full() +
- ", empty() = " + empty() +
- ", queue = " + Arrays.asList(data);
- }
- // JUnit testing.
- // As an inner class, this has access to privates:
- public static class WhiteBoxTest {
- private Queue queue = new Queue(10);
- private int i = 0;
- public WhiteBoxTest() {
- while(i < 5) // Preload with some data
- queue.put("" + i++);
- }
- // Support methods:
- private void showFullness() {
- assertTrue(queue.full());
- assertFalse(queue.empty());
- // Dump is private, white-box testing allows access:
- System.out.println(queue.dump());
- }
- private void showEmptiness() {
- assertFalse(queue.full());
- assertTrue(queue.empty());
- System.out.println(queue.dump());
- }
- @Test
- public void full() {
- System.out.println("testFull");
- System.out.println(queue.dump());
- System.out.println(queue.get());
- System.out.println(queue.get());
- while(!queue.full())
- queue.put("" + i++);
- String msg = "";
- try {
- queue.put("");
- } catch(QueueException e) {
- msg = e.getMessage();
- System.out.println(msg);
- }
- assertEquals(msg, "put() into full Queue");
- showFullness();
- }
- @Test
- public void empty() {
- System.out.println("testEmpty");
- while(!queue.empty())
- System.out.println(queue.get());
- String msg = "";
- try {
- queue.get();
- } catch(QueueException e) {
- msg = e.getMessage();
- System.out.println(msg);
- }
- assertEquals(msg, "get() from empty Queue");
- showEmptiness();
- }
- @Test
- public void nullPut() {
- System.out.println("testNullPut");
- String msg = "";
- try {
- queue.put(null);
- } catch(QueueException e) {
- msg = e.getMessage();
- System.out.println(msg);
- }
- assertEquals(msg, "put() null item");
- }
- @Test
- public void circularity() {
- System.out.println("testCircularity");
- while(!queue.full())
- queue.put("" + i++);
- showFullness();
- // White-box testing accesses private field:
- assertTrue(queue.wrapped);
- while(!queue.empty())
- System.out.println(queue.get());
- showEmptiness();
- while(!queue.full())
- queue.put("" + i++);
- showFullness();
- while(!queue.empty())
- System.out.println(queue.get());
- showEmptiness();
- }
- }
- public static void main(String[] args) {
- org.junit.runner.JUnitCore.runClasses(
- Queue.WhiteBoxTest.class);
- }
-}
-/* Output:
-testNullPut
-put() null item
-testCircularity
-in = 0, out = 0, full() = true, empty() = false, queue =
-[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-0
-1
-2
-3
-4
-5
-6
-7
-8
-9
-in = 0, out = 0, full() = false, empty() = true, queue =
-[null, null, null, null, null, null, null, null, null,
-null]
-in = 0, out = 0, full() = true, empty() = false, queue =
-[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
-10
-11
-12
-13
-14
-15
-16
-17
-18
-19
-in = 0, out = 0, full() = false, empty() = true, queue =
-[null, null, null, null, null, null, null, null, null,
-null]
-testFull
-in = 5, out = 0, full() = false, empty() = false, queue =
-[0, 1, 2, 3, 4, null, null, null, null, null]
-0
-1
-put() into full Queue
-in = 2, out = 2, full() = true, empty() = false, queue =
-[10, 11, 2, 3, 4, 5, 6, 7, 8, 9]
-testEmpty
-0
-1
-2
-3
-4
-get() from empty Queue
-in = 5, out = 5, full() = false, empty() = true, queue =
-[null, null, null, null, null, null, null, null, null,
-null]
-*/
diff --git a/assertions/build.xml b/assertions/build.xml
deleted file mode 100644
index e15e1e215..000000000
--- a/assertions/build.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index 3c70412b1..b4feb13d5 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,61 +1,23 @@
-repositories {
- mavenLocal()
- mavenCentral()
- maven {
- url 'http://maven-eclipse.github.io/maven'
- }
-}
-
-// these java plugin settings don't really need to be specified since ant does the actual build, but it makes things nicer in an IDE that understands gradle projects
-apply plugin: 'java'
-
-sourceCompatibility = '1.8'
-targetCompatibility = '1.8'
-
-sourceSets {
- main {
- java {
- srcDirs 'annotations', 'arrays', 'assertions', 'com', 'compression', 'concurrency', 'containers', 'containersindepth', 'control', 'debugging', 'enums', 'exceptions', 'files', 'functional', 'generics', 'hiding', 'housekeeping', 'innerclasses', 'interfaces', 'iostreams', 'logging', 'network', 'newio', 'objects', 'onjava', 'operators', 'patterns', 'polymorphism', 'preferences', 'references', 'remote', 'reuse', 'serialization', 'standardio', 'staticchecking', 'streams', 'strings', 'swt', 'typeinfo', 'ui', 'unittesting'
+buildscript {
+ repositories {
+ maven {
+ url 'https://plugins.gradle.org/m2/'
}
}
-}
-
-// fix for a xom / xalan transitive dependency issue: http://stackoverflow.com/a/23870656/77409
-configurations.all {
- resolutionStrategy {
- force 'xml-apis:xml-apis:1.0.b2'
+ dependencies {
+ classpath 'me.champeau.gradle:jmh-gradle-plugin:0.5.2'
}
}
+apply plugin: 'com.mindviewinc.example-output-verification'
-dependencies {
- compile 'org.eclipse.swt:org.eclipse.swt.win32.win32.x86:4.4.2'
- compile 'org.eclipse.swt:org.eclipse.swt.win32.win32.x86_64:4.4.2'
- compile 'org.eclipse.swt:org.eclipse.swt.gtk.linux.x86:4.4.2'
- compile 'org.eclipse.swt:org.eclipse.swt.gtk.linux.x86_64:4.4.2'
- compile 'org.eclipse.swt:org.eclipse.swt.cocoa.macosx.x86_64:4.4.2'
- compile 'junit:junit:4.12'
- compile 'com.io7m.xom:xom:1.2.10'
-}
-
-// this sets the classpath that ant uses to include the dependency jars
-ant.properties['java.class.path'] = sourceSets.main.compileClasspath.getAsPath()
-
-// import the ant build and override a few task names
-ant.importBuild('build.xml') { antTaskName ->
- if (antTaskName == 'build') 'ant-build' // rename ant's build task to ant-build so it doesn't override the gradle task with that name
- else if (antTaskName == 'clean') 'ant-clean' // rename ant's clean task to ant-clean so it doesn't override the gradle task with that name
- else antTaskName
-}
-
-// this task is already defined by gradle so we need to tell it to call the ant clean task
-clean << {
- tasks['ant-clean'].execute()
-}
-
-// this task is already defined by gradle so we need to tell it to call the ant build task
-build << {
- tasks['ant-build'].execute()
+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/findbugs.gradle"
+ apply plugin: 'com.mindviewinc.tagging'
}
-defaultTasks 'run'
\ No newline at end of file
+apply from: 'gradle/subprojects.gradle'
diff --git a/build.xml b/build.xml
deleted file mode 100644
index 1cc30c7c4..000000000
--- a/build.xml
+++ /dev/null
@@ -1,207 +0,0 @@
-
-
-
-
-
-
- Main build.xml for the source code for
- Bruce Eckel On Java
- Code available at https://github.com/BruceEckel/OnJava-Examples
- See installation instructions in README.md
- See copyright notice in CopyRight.txt
-
- Ant available from http://ant.apache.org
-
- To see options, type: ant -p
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/buildSrc/src/main/groovy/com/mindviewinc/plugins/ExampleOutputVerificationPlugin.groovy b/buildSrc/src/main/groovy/com/mindviewinc/plugins/ExampleOutputVerificationPlugin.groovy
new file mode 100644
index 000000000..0a0a213c7
--- /dev/null
+++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/ExampleOutputVerificationPlugin.groovy
@@ -0,0 +1,18 @@
+package com.mindviewinc.plugins
+
+import org.gradle.api.Project
+import org.gradle.api.Plugin
+import org.gradle.api.tasks.Exec
+
+class ExampleOutputVerificationPlugin implements Plugin {
+ void apply(Project project) {
+ project.tasks.create('verify', Exec) {
+ description 'Uses Python tool to verify example output'
+ commandLine 'python', '_verify_output.py'
+ doFirst {
+ println("execute 'gradlew run' first")
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy b/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy
new file mode 100644
index 000000000..518a7d5f2
--- /dev/null
+++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/TaggingPlugin.groovy
@@ -0,0 +1,94 @@
+package com.mindviewinc.plugins
+
+import org.gradle.api.Project
+import org.gradle.api.Plugin
+import org.gradle.api.tasks.JavaExec
+import org.gradle.internal.jvm.Jvm
+
+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
+ 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')) {
+
+ Tags tags = new Tags(file)
+ if(debug && tags.hasTags()) println tags
+
+ // Exclude java sources that will not compile
+ if (tags.willNotCompile
+ || tags.newFeature // Uses a feature introduced after Java 8
+ || (tags.lowLevelAppendix && runningInAppveyor) // Exclude entire lowlevel appendix
+ || (tags.excludeFromAppveyorCI && runningInAppveyor)
+ || (tags.excludeFromTravisCI && runningInTravis)
+ || (tags.excludeFromCI && runningInCI)
+ ) {
+ project.sourceSets.main.java.excludes.add(file.name)
+ } else {
+ JavaExec javaTask = null
+ // Add tasks for java sources with main methods
+ if (tags.hasMainMethod || tags.javaCmd) {
+ javaTask = project.tasks.create(name: tags.fileRoot, type: JavaExec, dependsOn: tags.runFirst) {
+ main = tags.mainClass
+ classpath = project.sourceSets.main.runtimeClasspath
+ args = tags.args
+ jvmArgs = tags.jVMArgs
+ }
+ } else if (tags.javap) {
+ // Create task for running javap
+ javaTask = project.tasks.create(name: "${tags.fileRoot}", type: JavaExec, dependsOn: tags.runFirst) {
+ main = "com.sun.tools.javap.Main"
+ classpath = project.sourceSets.main.runtimeClasspath + project.files(Jvm.current().toolsJar)
+ // Assuming javap represents all the args and there's no need to jVMArgs
+ args tags.javap.split()
+ }
+ }
+
+ if (javaTask) {
+ def baseName = file.name.substring(0, file.name.lastIndexOf('.'))
+ File outFile = new File(file.parentFile, baseName + '.out')
+ File errFile = new File(file.parentFile, baseName + '.err')
+
+ javaTask.configure {
+ ignoreExitValue = tags.excludeFromGradle || tags.throwsException
+ doFirst {
+ if(outFile.exists())
+ outFile.delete()
+ if(tags.outputLine)
+ outFile << tags.outputLine + "\n"
+
+ standardOutput = new TeeOutputStream(new FileOutputStream(outFile, true), System.out)
+ errorOutput = new TeeOutputStream(new FileOutputStream(errFile), System.err)
+ }
+ doLast {
+ if(outFile.size() == 0)
+ outFile.delete()
+ else if(!outFile.text.contains("/* Output:"))
+ outFile.delete()
+ if(errFile.size() == 0) errFile.delete()
+ }
+ }
+
+ if (!tags.excludeFromGradle) {
+ // Only add tasks that we know we can run successfully to the task list
+ createdTasks.add(javaTask)
+ }
+ }
+ }
+ }
+ }
+
+ project.tasks.create('run') {
+ dependsOn createdTasks
+ }
+ }
+}
diff --git a/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy b/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy
new file mode 100644
index 000000000..f61ed4d79
--- /dev/null
+++ b/buildSrc/src/main/groovy/com/mindviewinc/plugins/Tags.groovy
@@ -0,0 +1,126 @@
+package com.mindviewinc.plugins
+
+class Tags {
+ Boolean hasMainMethod = false
+ Boolean willNotCompile = false
+ Boolean excludeFromTravisCI = false
+ Boolean excludeFromAppveyorCI = false
+ Boolean excludeFromCI = false
+ Boolean lowLevelAppendix = false
+ Boolean throwsException = false
+ Boolean errorOutputExpected = false
+ Boolean excludeFromGradle = false
+ Boolean newFeature = false // For language feature introduced after Java 8
+ Boolean ignoreOutput = false // This tag isn't used in the build...
+ String fileRoot
+ String mainClass
+ String javaCmd = null
+ List args = []
+ List jVMArgs = []
+ String javap = null
+ String runFirst = null
+ String outputLine = null
+ private String block
+ def Tags(File file) {
+ block = file.text
+ hasMainMethod = block.contains('main(String[] args)')
+ def firstLine = block.substring(0, block.indexOf("\n"))
+ fileRoot = (firstLine.split("/")[-1] - ".java").trim() // Remove \r if it exists
+ mainClass = fileRoot
+ javaCmd = extract('java')
+ if(javaCmd) {
+ def pieces = javaCmd.split()
+ mainClass = pieces[0]
+ if(pieces.size() > 1)
+ for(p in pieces[1..-1])
+ if(p.startsWith("-"))
+ jVMArgs << p
+ else
+ args << p
+ }
+ willNotCompile = hasTag('WillNotCompile')
+ excludeFromTravisCI = hasTag('ExcludeFromTravisCI')
+ excludeFromAppveyorCI = hasTag('ExcludeFromAppveyorCI')
+ excludeFromCI = hasTag('ExcludeFromCI')
+ lowLevelAppendix = firstLine.contains("// lowlevel/")
+ throwsException = hasTag('ThrowsException')
+ errorOutputExpected = hasTag('ErrorOutputExpected')
+ excludeFromGradle = hasTag('ExcludeFromGradle')
+ newFeature = hasTag('NewFeature')
+ ignoreOutput = hasTag('IgnoreOutput')
+ javap = extract('javap') // Includes only arguments to command
+ runFirst = extract('RunFirst:')
+ outputLine = extractOutputLine()
+ }
+ private def hasTag(String marker) {
+ return block.contains("// {" + marker + "}")
+ }
+ def extractOutputLine() {
+ def matcher = (block =~ /(?m)^(\/\* Output:.*)$/)
+ if (matcher) {
+ return matcher[0][1]
+ } else {
+ return null
+ }
+ }
+ private def extract(String marker) {
+ // Assume some whitespace is after marker
+ if(!block.contains("// {${marker} "))
+ return null
+ def matcher = (block =~ /\/\/ \{${marker}\s+([^}]+)/)
+ if (matcher) {
+ def matched = matcher[0][1].trim()
+ return matched.replaceAll("\n?//", "")
+ } else {
+ println "Searching for: " + matcher
+ println block
+ System.exit(1)
+ }
+ }
+ public boolean hasTags() {
+ return willNotCompile ||
+ excludeFromTravisCI ||
+ excludeFromAppveyorCI ||
+ excludeFromCI ||
+ throwsException ||
+ errorOutputExpected ||
+ excludeFromGradle ||
+ newFeature ||
+ ignoreOutput ||
+ javaCmd ||
+ args ||
+ jVMArgs ||
+ javap ||
+ runFirst
+ }
+ public String toString() {
+ String result = ""
+ block.eachLine{ ln ->
+ if(ln.startsWith("//") || ln.startsWith("package "))
+ result += ln + "\n"
+ }
+ """
+ hasMainMethod
+ willNotCompile
+ excludeFromTravisCI
+ excludeFromAppveyorCI
+ excludeFromCI
+ throwsException
+ errorOutputExpected
+ excludeFromGradle
+ newFeature
+ ignoreOutput
+ fileRoot
+ mainClass
+ javaCmd
+ args
+ jVMArgs
+ javap
+ runFirst
+ """.split().each { str ->
+ if(this[str])
+ result += str + ": " + this[str] + "\n"
+ }
+ result
+ }
+}
diff --git a/buildSrc/src/main/resources/META-INF/gradle-plugins/com.mindviewinc.example-output-verification.properties b/buildSrc/src/main/resources/META-INF/gradle-plugins/com.mindviewinc.example-output-verification.properties
new file mode 100644
index 000000000..7a8a7f57b
--- /dev/null
+++ b/buildSrc/src/main/resources/META-INF/gradle-plugins/com.mindviewinc.example-output-verification.properties
@@ -0,0 +1 @@
+implementation-class=com.mindviewinc.plugins.ExampleOutputVerificationPlugin
\ No newline at end of file
diff --git a/buildSrc/src/main/resources/META-INF/gradle-plugins/com.mindviewinc.tagging.properties b/buildSrc/src/main/resources/META-INF/gradle-plugins/com.mindviewinc.tagging.properties
new file mode 100644
index 000000000..8359e8285
--- /dev/null
+++ b/buildSrc/src/main/resources/META-INF/gradle-plugins/com.mindviewinc.tagging.properties
@@ -0,0 +1 @@
+implementation-class=com.mindviewinc.plugins.TaggingPlugin
\ No newline at end of file
diff --git a/checkstyle.xml b/checkstyle.xml
new file mode 100644
index 000000000..aabea2c45
--- /dev/null
+++ b/checkstyle.xml
@@ -0,0 +1,179 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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 5d7d4a272..ffb8fbf5b 100644
--- a/collections/AdapterMethodIdiom.java
+++ b/collections/AdapterMethodIdiom.java
@@ -1,13 +1,13 @@
// collections/AdapterMethodIdiom.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// The "Adapter Method" idiom uses for-in
// with additional kinds of Iterables
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 9551639ff..13fcdcaf1 100644
--- a/collections/AddingGroups.java
+++ b/collections/AddingGroups.java
@@ -1,7 +1,7 @@
// collections/AddingGroups.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Adding groups of elements to Collection objects
import java.util.*;
diff --git a/collections/ApplesAndOrangesWithGenerics.java b/collections/ApplesAndOrangesWithGenerics.java
index ee5db4f04..674ee7b47 100644
--- a/collections/ApplesAndOrangesWithGenerics.java
+++ b/collections/ApplesAndOrangesWithGenerics.java
@@ -1,7 +1,7 @@
// collections/ApplesAndOrangesWithGenerics.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class ApplesAndOrangesWithGenerics {
diff --git a/collections/ApplesAndOrangesWithoutGenerics.java b/collections/ApplesAndOrangesWithoutGenerics.java
index 649dfbc4d..4cbe23073 100644
--- a/collections/ApplesAndOrangesWithoutGenerics.java
+++ b/collections/ApplesAndOrangesWithoutGenerics.java
@@ -1,7 +1,7 @@
// collections/ApplesAndOrangesWithoutGenerics.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Simple collection use (suppressing compiler warnings)
// {ThrowsException}
import java.util.*;
@@ -24,15 +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(Unknown
-Source)
-___[ Exception is Expected ]___
+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 87177d448..a9660a67c 100644
--- a/collections/ArrayIsNotIterable.java
+++ b/collections/ArrayIsNotIterable.java
@@ -1,7 +1,7 @@
// collections/ArrayIsNotIterable.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class ArrayIsNotIterable {
diff --git a/collections/AsListInference.java b/collections/AsListInference.java
index 1d47b3c50..b25ac8e61 100644
--- a/collections/AsListInference.java
+++ b/collections/AsListInference.java
@@ -1,7 +1,7 @@
// collections/AsListInference.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
class Snow {}
@@ -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
new file mode 100644
index 000000000..a8ea09d01
--- /dev/null
+++ b/collections/CollectionDifferences.java
@@ -0,0 +1,71 @@
+// collections/CollectionDifferences.java
+// (c)2021 MindView LLC: 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.*;
+
+public class CollectionDifferences {
+ public static void main(String[] args) {
+ CollectionMethodDifferences.main(args);
+ }
+}
+/* Output:
+Collection: [add, addAll, clear, contains, containsAll,
+equals, forEach, hashCode, isEmpty, iterator,
+parallelStream, remove, removeAll, removeIf, retainAll,
+size, spliterator, stream, toArray]
+Interfaces in Collection: [Iterable]
+Set extends Collection, adds: []
+Interfaces in Set: [Collection]
+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 TreeSet: [NavigableSet, Cloneable,
+Serializable]
+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]
+Interfaces in LinkedList: [List, Deque, Cloneable,
+Serializable]
+Queue extends Collection, adds: [poll, peek, offer,
+element]
+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]
+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]
+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]
+Interfaces in TreeMap: [NavigableMap, Cloneable,
+Serializable]
+*/
diff --git a/collections/CollectionMethods.java b/collections/CollectionMethods.java
deleted file mode 100644
index 7339f93af..000000000
--- a/collections/CollectionMethods.java
+++ /dev/null
@@ -1,67 +0,0 @@
-// collections/CollectionMethods.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.
-import onjava.*;
-
-public class CollectionMethods {
- public static void main(String[] args) {
- CollectionMethodDifferences.main(args);
- }
-}
-/* Output:
-Collection: [add, addAll, clear, contains, containsAll,
-equals, forEach, hashCode, isEmpty, iterator,
-parallelStream, remove, removeAll, removeIf, retainAll,
-size, spliterator, stream, toArray]
-Interfaces in Collection: [Iterable]
-Set extends Collection, adds: []
-Interfaces in Set: [Collection]
-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 TreeSet: [NavigableSet, Cloneable,
-Serializable]
-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]
-Interfaces in LinkedList: [List, Deque, Cloneable,
-Serializable]
-Queue extends Collection, adds: [poll, peek, offer,
-element]
-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]
-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]
-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]
-Interfaces in TreeMap: [NavigableMap, Cloneable,
-Serializable]
-*/
diff --git a/collections/CollectionSequence.java b/collections/CollectionSequence.java
index a444be712..ea0e45740 100644
--- a/collections/CollectionSequence.java
+++ b/collections/CollectionSequence.java
@@ -1,21 +1,19 @@
// collections/CollectionSequence.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 470da4a27..2aaf7e95a 100644
--- a/collections/CrossCollectionIteration.java
+++ b/collections/CrossCollectionIteration.java
@@ -1,8 +1,8 @@
// collections/CrossCollectionIteration.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 8eb85f072..e8aa755d0 100644
--- a/collections/CrossCollectionIteration2.java
+++ b/collections/CrossCollectionIteration2.java
@@ -1,8 +1,8 @@
// collections/CrossCollectionIteration2.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 3b083bdaa..6098e4cfc 100644
--- a/collections/EnvironmentVariables.java
+++ b/collections/EnvironmentVariables.java
@@ -1,7 +1,8 @@
// collections/EnvironmentVariables.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
+// {VisuallyInspectOutput}
import java.util.*;
public class EnvironmentVariables {
@@ -12,4 +13,3 @@ public static void main(String[] args) {
}
}
}
-/* Output: (Execute to see) */
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 b37f17666..15ea9bb3a 100644
--- a/collections/ForInCollections.java
+++ b/collections/ForInCollections.java
@@ -1,7 +1,7 @@
// collections/ForInCollections.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// All collections work with for-in
import java.util.*;
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 37853d37d..3462e0b76 100644
--- a/collections/GenericsAndUpcasting.java
+++ b/collections/GenericsAndUpcasting.java
@@ -1,7 +1,7 @@
// collections/GenericsAndUpcasting.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
class GrannySmith extends Apple {}
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 eda990c20..fdb50a588 100644
--- a/collections/InterfaceVsIterator.java
+++ b/collections/InterfaceVsIterator.java
@@ -1,8 +1,8 @@
// collections/InterfaceVsIterator.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 8f1d43faf..1e64d783a 100644
--- a/collections/IterableClass.java
+++ b/collections/IterableClass.java
@@ -1,19 +1,18 @@
// collections/IterableClass.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Anything Iterable works with for-in
import java.util.*;
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 3e794e817..489c699f2 100644
--- a/collections/LinkedListFeatures.java
+++ b/collections/LinkedListFeatures.java
@@ -1,14 +1,14 @@
// collections/LinkedListFeatures.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 68c32664c..12fb6b4f1 100644
--- a/collections/ListFeatures.java
+++ b/collections/ListFeatures.java
@@ -1,14 +1,14 @@
// collections/ListFeatures.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 0754768f8..4967f5260 100644
--- a/collections/ListIteration.java
+++ b/collections/ListIteration.java
@@ -1,16 +1,17 @@
// collections/ListIteration.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 c4ea6f0eb..d7357a6ed 100644
--- a/collections/MapOfList.java
+++ b/collections/MapOfList.java
@@ -1,13 +1,14 @@
// collections/MapOfList.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// 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"),
@@ -20,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")));
}
@@ -38,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 9c3fd86e7..ef50e40ab 100644
--- a/collections/ModifyingArraysAsList.java
+++ b/collections/ModifyingArraysAsList.java
@@ -1,7 +1,7 @@
// collections/ModifyingArraysAsList.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class ModifyingArraysAsList {
diff --git a/collections/MultiIterableClass.java b/collections/MultiIterableClass.java
index 00f4245fb..3c5e7ae26 100644
--- a/collections/MultiIterableClass.java
+++ b/collections/MultiIterableClass.java
@@ -1,7 +1,7 @@
// collections/MultiIterableClass.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Adding several Adapter Methods
import java.util.*;
@@ -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 5ca490cfc..dc8678274 100644
--- a/collections/NonCollectionSequence.java
+++ b/collections/NonCollectionSequence.java
@@ -1,20 +1,19 @@
// collections/NonCollectionSequence.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 e229ff8ba..dc64bf574 100644
--- a/collections/PetMap.java
+++ b/collections/PetMap.java
@@ -1,8 +1,8 @@
// collections/PetMap.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 c5d75af45..c324722a9 100644
--- a/collections/PrintingCollections.java
+++ b/collections/PrintingCollections.java
@@ -1,12 +1,13 @@
// collections/PrintingCollections.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// 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 3527e97a2..0e0f553ef 100644
--- a/collections/PriorityQueueDemo.java
+++ b/collections/PriorityQueueDemo.java
@@ -1,7 +1,7 @@
// collections/PriorityQueueDemo.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class PriorityQueueDemo {
@@ -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 066decc24..a7d30c1c4 100644
--- a/collections/QueueDemo.java
+++ b/collections/QueueDemo.java
@@ -1,7 +1,7 @@
// collections/QueueDemo.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Upcasting to a Queue from a LinkedList
import java.util.*;
diff --git a/collections/SetOfInteger.java b/collections/SetOfInteger.java
index 2135fea7e..92a403e6c 100644
--- a/collections/SetOfInteger.java
+++ b/collections/SetOfInteger.java
@@ -1,7 +1,7 @@
// collections/SetOfInteger.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class SetOfInteger {
@@ -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 4d0201b8f..50a06bc20 100644
--- a/collections/SetOfString.java
+++ b/collections/SetOfString.java
@@ -1,7 +1,7 @@
// collections/SetOfString.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class SetOfString {
diff --git a/collections/SetOperations.java b/collections/SetOperations.java
index 72a2f98ce..485588b6c 100644
--- a/collections/SetOperations.java
+++ b/collections/SetOperations.java
@@ -1,7 +1,7 @@
// collections/SetOperations.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class SetOperations {
@@ -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 8fb2347e2..6dcf73b24 100644
--- a/collections/SimpleCollection.java
+++ b/collections/SimpleCollection.java
@@ -1,7 +1,7 @@
// collections/SimpleCollection.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class SimpleCollection {
diff --git a/collections/SimpleIteration.java b/collections/SimpleIteration.java
index 071339ca1..089774963 100644
--- a/collections/SimpleIteration.java
+++ b/collections/SimpleIteration.java
@@ -1,13 +1,13 @@
// collections/SimpleIteration.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import typeinfo.pets.*;
+// Visit http://OnJava8.com for more book information.
+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 139a74695..af6222aac 100644
--- a/collections/SortedSetOfString.java
+++ b/collections/SortedSetOfString.java
@@ -1,7 +1,7 @@
// collections/SortedSetOfString.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
public class SortedSetOfString {
diff --git a/collections/StackCollision.java b/collections/StackCollision.java
index 82b6d57cf..7914e3496 100644
--- a/collections/StackCollision.java
+++ b/collections/StackCollision.java
@@ -1,14 +1,14 @@
// collections/StackCollision.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
public class StackCollision {
public static void main(String[] args) {
onjava.Stack stack = new onjava.Stack<>();
for(String s : "My dog has fleas".split(" "))
stack.push(s);
- while(!stack.empty())
+ while(!stack.isEmpty())
System.out.print(stack.pop() + " ");
System.out.println();
java.util.Stack stack2 =
diff --git a/collections/StackTest.java b/collections/StackTest.java
index c873b1686..54005700a 100644
--- a/collections/StackTest.java
+++ b/collections/StackTest.java
@@ -1,15 +1,15 @@
// collections/StackTest.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
-import onjava.*;
+// Visit http://OnJava8.com for more book information.
+import java.util.*;
public class StackTest {
public static void main(String[] args) {
- Stack stack = new Stack<>();
+ Deque stack = new ArrayDeque<>();
for(String s : "My dog has fleas".split(" "))
stack.push(s);
- while(!stack.empty())
+ while(!stack.isEmpty())
System.out.print(stack.pop() + " ");
}
}
diff --git a/collections/StackTest2.java b/collections/StackTest2.java
new file mode 100644
index 000000000..148a834a8
--- /dev/null
+++ b/collections/StackTest2.java
@@ -0,0 +1,18 @@
+// collections/StackTest2.java
+// (c)2021 MindView LLC: 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.*;
+
+public class StackTest2 {
+ public static void main(String[] args) {
+ Stack stack = new Stack<>();
+ for(String s : "My dog has fleas".split(" "))
+ stack.push(s);
+ while(!stack.isEmpty())
+ System.out.print(stack.pop() + " ");
+ }
+}
+/* Output:
+fleas has dog My
+*/
diff --git a/collections/Statistics.java b/collections/Statistics.java
index 862b17d08..a3ece359e 100644
--- a/collections/Statistics.java
+++ b/collections/Statistics.java
@@ -1,7 +1,7 @@
// collections/Statistics.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Simple demonstration of HashMap
import java.util.*;
@@ -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 f8c3b096d..e39a9b882 100644
--- a/collections/UniqueWords.java
+++ b/collections/UniqueWords.java
@@ -1,15 +1,15 @@
// collections/UniqueWords.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.nio.file.*;
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 584fa6506..780ddb3f1 100644
--- a/collections/UniqueWordsAlphabetic.java
+++ b/collections/UniqueWordsAlphabetic.java
@@ -1,7 +1,7 @@
// collections/UniqueWordsAlphabetic.java
-// (c)2016 MindView LLC: see Copyright.txt
+// (c)2021 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.
+// Visit http://OnJava8.com for more book information.
// Producing an alphabetic listing
import java.util.*;
import java.nio.file.*;
@@ -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/collections/build.xml b/collections/build.xml
deleted file mode 100644
index b5ffcc1ae..000000000
--- a/collections/build.xml
+++ /dev/null
@@ -1,90 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/collectionsindepth/CanonicalMapping.java b/collectionsindepth/CanonicalMapping.java
deleted file mode 100644
index a1b241ac5..000000000
--- a/collectionsindepth/CanonicalMapping.java
+++ /dev/null
@@ -1,52 +0,0 @@
-// collectionsindepth/CanonicalMapping.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.
-// 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 ident.hashCode(); }
- @Override
- public boolean equals(Object r) {
- return r instanceof Element &&
- ident.equals(((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); }
-}
-
-public class CanonicalMapping {
- 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 = new WeakHashMap<>();
- for(int i = 0; i < size; i++) {
- Key k = new Key(Integer.toString(i));
- Value v = new Value(Integer.toString(i));
- if(i % 3 == 0)
- keys[i] = k; // Save as "real" references
- map.put(k, v);
- }
- System.gc();
- }
-}
diff --git a/collectionsindepth/CollectionMethods.java b/collectionsindepth/CollectionMethods.java
deleted file mode 100644
index a25e43585..000000000
--- a/collectionsindepth/CollectionMethods.java
+++ /dev/null
@@ -1,88 +0,0 @@
-// collectionsindepth/CollectionMethods.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.
-// Things you can do with all Collections
-import java.util.*;
-import onjava.*;
-
-public class CollectionMethods {
- public static void main(String[] args) {
- Collection c = new ArrayList<>();
- c.addAll(Countries.names(6));
- c.add("ten");
- c.add("eleven");
- System.out.println(c);
- // Make an array from the List:
- Object[] array = c.toArray();
- // Make a String array from the List:
- String[] str = c.toArray(new String[0]);
- // Find max and min elements; this means
- // different things depending on the way
- // the Comparable interface is implemented:
- System.out.println(
- "Collections.max(c) = " + Collections.max(c));
- System.out.println(
- "Collections.min(c) = " + Collections.min(c));
- // Add a Collection to another Collection
- Collection c2 = new ArrayList<>();
- c2.addAll(Countries.names(6));
- c.addAll(c2);
- System.out.println(c);
- c.remove(Countries.DATA[0][0]);
- System.out.println(c);
- c.remove(Countries.DATA[1][0]);
- System.out.println(c);
- // Remove all components that are
- // in the argument collection:
- c.removeAll(c2);
- System.out.println(c);
- c.addAll(c2);
- System.out.println(c);
- // Is an element in this Collection?
- String val = Countries.DATA[3][0];
- System.out.println(
- "c.contains(" + val + ") = " + c.contains(val));
- // Is a Collection in this Collection?
- System.out.println(
- "c.containsAll(c2) = " + c.containsAll(c2));
- Collection c3 =
- ((List)c).subList(3, 5);
- // Keep all the elements that are in both
- // c2 and c3 (an intersection of sets):
- c2.retainAll(c3);
- System.out.println(c2);
- // Throw away all the elements
- // in c2 that also appear in c3:
- c2.removeAll(c3);
- System.out.println("c2.isEmpty() = " + c2.isEmpty());
- c = new ArrayList<>();
- c.addAll(Countries.names(6));
- System.out.println(c);
- c.clear(); // Remove all elements
- System.out.println("after c.clear():" + c);
- }
-}
-/* Output:
-[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI,
-ten, eleven]
-Collections.max(c) = ten
-Collections.min(c) = ALGERIA
-[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI,
-ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA
-FASO, BURUNDI]
-[ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten,
-eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO,
-BURUNDI]
-[BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven,
-ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
-[ten, eleven]
-[ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA
-FASO, BURUNDI]
-c.contains(BOTSWANA) = true
-c.containsAll(c2) = true
-[ANGOLA, BENIN]
-c2.isEmpty() = true
-[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI]
-after c.clear():[]
-*/
diff --git a/collectionsindepth/DequeTest.java b/collectionsindepth/DequeTest.java
deleted file mode 100644
index dca46926d..000000000
--- a/collectionsindepth/DequeTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-// collectionsindepth/DequeTest.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.
-import onjava.*;
-
-public class DequeTest {
- static void fillTest(Deque deque) {
- for(int i = 20; i < 27; i++)
- deque.addFirst(i);
- for(int i = 50; i < 55; i++)
- deque.addLast(i);
- }
- public static void main(String[] args) {
- Deque di = new Deque<>();
- fillTest(di);
- System.out.println(di);
- while(di.size() != 0)
- System.out.print(di.removeFirst() + " ");
- System.out.println();
- fillTest(di);
- while(di.size() != 0)
- System.out.print(di.removeLast() + " ");
- }
-}
-/* Output:
-[26, 25, 24, 23, 22, 21, 20, 50, 51, 52, 53, 54]
-26 25 24 23 22 21 20 50 51 52 53 54
-54 53 52 51 50 20 21 22 23 24 25 26
-*/
diff --git a/collectionsindepth/FilledCollectionGeneration.java b/collectionsindepth/FilledCollectionGeneration.java
deleted file mode 100644
index 22458de99..000000000
--- a/collectionsindepth/FilledCollectionGeneration.java
+++ /dev/null
@@ -1,23 +0,0 @@
-// collectionsindepth/FilledCollectionGeneration.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.
-// Using the Suppliers defined in the Arrays chapter
-import java.util.*;
-import onjava.*;
-
-public class FilledCollectionGeneration {
- public static void main(String[] args) {
- System.out.println(new ArrayList<>(
- FilledCollection.list( // Convenience method
- new Rand.String(9), 10)));
- System.out.println(new HashSet<>(
- new FilledCollection<>(
- new Rand.Integer(), 10)));
- }
-}
-/* Output:
-[YNzbrnyGc, FOWZnTcQr, GseGZMmJM, RoEsuEcUO, neOEdLsmw,
-HLGEahKcx, rEqUCBbkI, naMesbtWH, kjUrUkZPg, wsqPzDyCy]
-[2017, 8037, 871, 7882, 6090, 4779, 299, 573, 4367, 3455]
-*/
diff --git a/collectionsindepth/FilledCollectionTest.java b/collectionsindepth/FilledCollectionTest.java
deleted file mode 100644
index 4f707b4ff..000000000
--- a/collectionsindepth/FilledCollectionTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-// collectionsindepth/FilledCollectionTest.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.
-import java.util.*;
-import java.util.function.*;
-import onjava.*;
-
-class Government implements Supplier {
- String[] foundation = ("strange women lying in ponds " +
- "distributing swords is no basis for a system of " +
- "government").split(" ");
- private int index;
- @Override
- public String get() { return foundation[index++]; }
-}
-
-public class FilledCollectionTest {
- public static void main(String[] args) {
- Set set = new LinkedHashSet<>(
- new FilledCollection<>(new Government(), 15));
- // Using the convenience method:
- set.addAll(
- FilledCollection.list(new Government(), 15));
- System.out.println(set);
- }
-}
-/* Output:
-[strange, women, lying, in, ponds, distributing, swords,
-is, no, basis, for, a, system, of, government]
-*/
diff --git a/collectionsindepth/FillingLists.java b/collectionsindepth/FillingLists.java
deleted file mode 100644
index 37f7b1bdd..000000000
--- a/collectionsindepth/FillingLists.java
+++ /dev/null
@@ -1,31 +0,0 @@
-// collectionsindepth/FillingLists.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.
-// The Collections.fill() & Collections.nCopies() methods
-import java.util.*;
-
-class StringAddress {
- private String s;
- public StringAddress(String s) { this.s = s; }
- @Override
- public String toString() {
- return super.toString() + " " + s;
- }
-}
-
-public class FillingLists {
- public static void main(String[] args) {
- List list = new ArrayList<>(
- Collections.nCopies(4, new StringAddress("Hello")));
- System.out.println(list);
- Collections.fill(list, new StringAddress("World!"));
- System.out.println(list);
- }
-}
-/* Output:
-[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/collectionsindepth/IndividualTest.java b/collectionsindepth/IndividualTest.java
deleted file mode 100644
index 972fdcc97..000000000
--- a/collectionsindepth/IndividualTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-// collectionsindepth/IndividualTest.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.
-import collections.MapOfList;
-import typeinfo.pets.*;
-import java.util.*;
-
-public class IndividualTest {
- public static void main(String[] args) {
- Set pets = new TreeSet<>();
- for(List extends Pet> lp :
- MapOfList.petPeople.values())
- for(Pet p : lp)
- pets.add(p);
- System.out.println(pets);
- }
-}
-/* Output:
-[Cat Elsie May, Cat Pinkola, Cat Shackleton, Cat Stanford
-aka Stinky el Negro, Cymric Molly, Dog Margrett, Mutt Spot,
-Pug Louie aka Louis Snorkelstein Dupree, Rat Fizzy, Rat
-Freckly, Rat Fuzzy]
-*/
diff --git a/collectionsindepth/ListPerformance.java b/collectionsindepth/ListPerformance.java
deleted file mode 100644
index 51e37eef4..000000000
--- a/collectionsindepth/ListPerformance.java
+++ /dev/null
@@ -1,210 +0,0 @@
-// collectionsindepth/ListPerformance.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.
-// Demonstrates performance differences in Lists
-// {Args: 100 500} Small to keep build testing short
-import java.util.*;
-import onjava.*;
-
-public class ListPerformance {
- static SplittableRandom rand = new SplittableRandom();
- static int reps = 1000;
- static List>> tests =
- new ArrayList<>();
- static List>> qTests =
- new ArrayList<>();
- static {
- tests.add(new Test>("add") {
- @Override
- int test(List list, TestParam tp) {
- int loops = tp.loops;
- int listSize = tp.size;
- for(int i = 0; i < loops; i++) {
- list.clear();
- for(int j = 0; j < listSize; j++)
- list.add(j);
- }
- return loops * listSize;
- }
- });
- tests.add(new Test>("get") {
- @Override
- int test(List list, TestParam tp) {
- int loops = tp.loops * reps;
- int listSize = list.size();
- for(int i = 0; i < loops; i++)
- list.get(rand.nextInt(listSize));
- return loops;
- }
- });
- tests.add(new Test>("set") {
- @Override
- int test(List list, TestParam tp) {
- int loops = tp.loops * reps;
- int listSize = list.size();
- for(int i = 0; i < loops; i++)
- list.set(rand.nextInt(listSize), 47);
- return loops;
- }
- });
- tests.add(new Test>("iteradd") {
- @Override
- int test(List list, TestParam tp) {
- final int LOOPS = 1000000;
- int half = list.size() / 2;
- ListIterator it =
- list.listIterator(half);
- for(int i = 0; i < LOOPS; i++)
- it.add(47);
- return LOOPS;
- }
- });
- tests.add(new Test>("insert") {
- @Override
- int test(List list, TestParam tp) {
- int loops = tp.loops;
- for(int i = 0; i < loops; i++)
- list.add(5, 47); // Minimize random-access cost
- return loops;
- }
- });
- tests.add(new Test>("remove") {
- @Override
- int test(List list, TestParam tp) {
- int loops = tp.loops;
- int size = tp.size;
- for(int i = 0; i < loops; i++) {
- list.clear();
- list.addAll(new CountingIntegerList(size));
- while(list.size() > 5)
- list.remove(5); // Minimize random-access cost
- }
- return loops * size;
- }
- });
- // Tests for queue behavior:
- qTests.add(new Test>("addFirst") {
- @Override
- int test(LinkedList list, TestParam tp) {
- int loops = tp.loops;
- int size = tp.size;
- for(int i = 0; i < loops; i++) {
- list.clear();
- for(int j = 0; j < size; j++)
- list.addFirst(47);
- }
- return loops * size;
- }
- });
- qTests.add(new Test>("addLast") {
- @Override
- int test(LinkedList list, TestParam tp) {
- int loops = tp.loops;
- int size = tp.size;
- for(int i = 0; i < loops; i++) {
- list.clear();
- for(int j = 0; j < size; j++)
- list.addLast(47);
- }
- return loops * size;
- }
- });
- qTests.add(
- new Test>("rmFirst") {
- @Override
- int test(LinkedList list, TestParam tp) {
- int loops = tp.loops;
- int size = tp.size;
- for(int i = 0; i < loops; i++) {
- list.clear();
- list.addAll(new CountingIntegerList(size));
- while(list.size() > 0)
- list.removeFirst();
- }
- return loops * size;
- }
- });
- qTests.add(new Test>("rmLast") {
- @Override
- int test(LinkedList list, TestParam tp) {
- int loops = tp.loops;
- int size = tp.size;
- for(int i = 0; i < loops; i++) {
- list.clear();
- list.addAll(new CountingIntegerList(size));
- while(list.size() > 0)
- list.removeLast();
- }
- return loops * size;
- }
- });
- }
- static class ListTester extends Tester> {
- public ListTester(List collection,
- List>> tests) {
- super(collection, tests);
- }
- // Fill to the appropriate size before each test:
- @Override
- protected List initialize(int size) {
- collection.clear();
- collection.addAll(new CountingIntegerList(size));
- return collection;
- }
- // Convenience method:
- public static void run(List list,
- List>> tests) {
- new ListTester(list, tests).timedTest();
- }
- }
- public static void main(String[] args) {
- if(args.length > 0)
- Tester.defaultParams = TestParam.array(args);
- // Can only do these two tests on an array:
- Tester> arrayTest =
- new Tester>(null,
- tests.subList(1, 3)) {
- // This is called before each test. It
- // produces a non-resizeable array-backed list:
- @Override protected
- List initialize(int size) {
- Integer[] ia = new Integer[size];
- Arrays.setAll(ia, new Count.Integer()::get);
- return Arrays.asList(ia);
- }
- };
- arrayTest.setHeadline("Array as List");
- arrayTest.timedTest();
- Tester.defaultParams= TestParam.array(
- 10, 5000, 100, 5000, 1000, 1000, 10000, 200);
- if(args.length > 0)
- Tester.defaultParams = TestParam.array(args);
- ListTester.run(new ArrayList<>(), tests);
- ListTester.run(new LinkedList<>(), tests);
- ListTester.run(new Vector<>(), tests);
- Tester.fieldWidth = 12;
- Tester> qTest =
- new Tester>(
- new LinkedList<>(), qTests);
- qTest.setHeadline("Queue tests");
- qTest.timedTest();
- }
-}
-/* Output:
---- Array as List ---
- size get set
- 100 19 20
---------------------- ArrayList ---------------------
- size add get set iteradd insert remove
- 100 31 19 21 33 158 114
---------------------- LinkedList ---------------------
- size add get set iteradd insert remove
- 100 30 44 45 77 143 56
------------------------ Vector -----------------------
- size add get set iteradd insert remove
- 100 26 32 33 64 147 67
--------------------- Queue tests --------------------
- size addFirst addLast rmFirst rmLast
- 100 33 71 102 135
-*/
diff --git a/collectionsindepth/MapEntry.java b/collectionsindepth/MapEntry.java
deleted file mode 100644
index c14712c7e..000000000
--- a/collectionsindepth/MapEntry.java
+++ /dev/null
@@ -1,44 +0,0 @@
-// collectionsindepth/MapEntry.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.
-// A simple Map.Entry for sample Map implementations
-import java.util.*;
-
-public class MapEntry implements Map.Entry {
- private K key;
- private V value;
- 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) {
- V result = value;
- value = v;
- return result;
- }
- @Override
- public int hashCode() {
- return (key==null ? 0 : key.hashCode()) ^
- (value==null ? 0 : value.hashCode());
- }
- @Override
- public boolean equals(Object o) {
- if(!(o instanceof MapEntry)) return false;
- @SuppressWarnings("unchecked")
- MapEntry me = (MapEntry)o;
- return
- (key == null ? me.getKey() == null :
- key.equals(me.getKey()))
- &&
- (value == null ? me.getValue() == null :
- value.equals(me.getValue()));
- }
- @Override
- public String toString() { return key + "=" + value; }
-}
diff --git a/collectionsindepth/MapPerformance.java b/collectionsindepth/MapPerformance.java
deleted file mode 100644
index 02aca5d79..000000000
--- a/collectionsindepth/MapPerformance.java
+++ /dev/null
@@ -1,81 +0,0 @@
-// collectionsindepth/MapPerformance.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.
-// Demonstrates performance differences in Maps
-// {Args: 100 5000} Small to keep build testing short
-import java.util.*;
-
-public class MapPerformance {
- static List>> tests =
- new ArrayList<>();
- static {
- tests.add(new Test