Checkstyle and Findbugs changes

Also changed comment callouts from // (1) to // [1]
This commit is contained in:
Bruce Eckel 2016-11-21 12:37:57 -08:00
parent 205b794e48
commit fda0e2dee6
146 changed files with 590 additions and 533 deletions

View File

@ -1,5 +1,5 @@
// Copyright.txt // Copyright.txt
This computer source code is Copyright ©2016 MindView LLC This computer source code is Copyright ©2016 MindView LLC.
All Rights Reserved. All Rights Reserved.
Permission to use, copy, modify, and distribute this 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 2. Permission is granted to use the Source Code without
modification in classroom situations, including in modification in classroom situations, including in
presentation materials, provided that the book "On 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 3. Permission to incorporate the Source Code into printed
media may be obtained by contacting: media may be obtained by contacting:
@ -64,9 +64,9 @@ ENHANCEMENTS, OR MODIFICATIONS.
Please note that MindView LLC maintains a Web site which Please note that MindView LLC maintains a Web site which
is the sole distribution point for electronic copies of the 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. where it is freely available under the terms stated above.
If you think you've found an error in the Source Code, If you think you've found an error in the Source Code,
please submit a correction at: please submit a correction at:
https://github.com/BruceEckel/OnJava-Examples/issues https://github.com/BruceEckel/OnJava8-examples/issues

10
ShowFindbugs.py Normal file
View File

@ -0,0 +1,10 @@
#! py -3
# Requires Python 3.5
# Displays all the Findbugs main.html reports from "On Java 8" on Windows
# Must run "gradlew findbugsMain" first
from pathlib import Path
import os
cmds = ["start " + str(report) for report in Path(".").rglob("main.html")]
(Path(".") / "ShowFindbugs.bat").write_text("\n".join(cmds).strip() + "\n")
os.system("ShowFindbugs.bat")

View File

@ -11,18 +11,18 @@ import onjava.*;
public class AtUnitComposition { public class AtUnitComposition {
AtUnitExample1 testObject = new AtUnitExample1(); AtUnitExample1 testObject = new AtUnitExample1();
@Test boolean _methodOne() { @Test boolean tMethodOne() {
return return
testObject.methodOne().equals("This is methodOne"); testObject.methodOne().equals("This is methodOne");
} }
@Test boolean _methodTwo() { @Test boolean tMethodTwo() {
return testObject.methodTwo() == 2; return testObject.methodTwo() == 2;
} }
} }
/* Output: /* Output:
annotations.AtUnitComposition annotations.AtUnitComposition
. _methodOne . tMethodOne
. _methodTwo This is methodTwo . tMethodTwo This is methodTwo
OK (2 tests) OK (2 tests)
*/ */

View File

@ -10,15 +10,15 @@ import onjava.atunit.*;
import onjava.*; import onjava.*;
public class AtUnitExternalTest extends AtUnitExample1 { public class AtUnitExternalTest extends AtUnitExample1 {
@Test boolean _methodOne() { @Test boolean tMethodOne() {
return methodOne().equals("This is methodOne"); return methodOne().equals("This is methodOne");
} }
@Test boolean _methodTwo() { return methodTwo() == 2; } @Test boolean tMethodTwo() { return methodTwo() == 2; }
} }
/* Output: /* Output:
annotations.AtUnitExternalTest annotations.AtUnitExternalTest
. _methodTwo This is methodTwo . tMethodTwo This is methodTwo
. _methodOne . tMethodOne
OK (2 tests) OK (2 tests)
*/ */

View File

@ -14,11 +14,11 @@ public class HashSetTest {
@Test void initialization() { @Test void initialization() {
assert testObject.isEmpty(); assert testObject.isEmpty();
} }
@Test void _contains() { @Test void tContains() {
testObject.add("one"); testObject.add("one");
assert testObject.contains("one"); assert testObject.contains("one");
} }
@Test void _remove() { @Test void tRemove() {
testObject.add("one"); testObject.add("one");
testObject.remove("one"); testObject.remove("one");
assert testObject.isEmpty(); assert testObject.isEmpty();
@ -26,8 +26,8 @@ public class HashSetTest {
} }
/* Output: /* Output:
annotations.HashSetTest annotations.HashSetTest
. _remove . tRemove
. _contains . tContains
. initialization . initialization
OK (3 tests) OK (3 tests)
*/ */

View File

@ -7,6 +7,6 @@ import java.lang.annotation.*;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface SimulatingNull { public @interface SimulatingNull {
public int id() default -1; int id() default -1;
public String description() default ""; String description() default "";
} }

View File

@ -10,19 +10,19 @@ import onjava.atunit.*;
import onjava.*; import onjava.*;
public class StackLStringTest extends StackL<String> { public class StackLStringTest extends StackL<String> {
@Test void _push() { @Test void tPush() {
push("one"); push("one");
assert top().equals("one"); assert top().equals("one");
push("two"); push("two");
assert top().equals("two"); assert top().equals("two");
} }
@Test void _pop() { @Test void tPop() {
push("one"); push("one");
push("two"); push("two");
assert pop().equals("two"); assert pop().equals("two");
assert pop().equals("one"); assert pop().equals("one");
} }
@Test void _top() { @Test void tTop() {
push("A"); push("A");
push("B"); push("B");
assert top().equals("B"); assert top().equals("B");
@ -31,8 +31,8 @@ public class StackLStringTest extends StackL<String> {
} }
/* Output: /* Output:
annotations.StackLStringTest annotations.StackLStringTest
. _pop . tPop
. _top . tTop
. _push . tPush
OK (3 tests) OK (3 tests)
*/ */

View File

@ -7,6 +7,6 @@ import java.lang.annotation.*;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface UseCase { public @interface UseCase {
public int id(); int id();
public String description() default "no description"; String description() default "no description";
} }

View File

@ -8,5 +8,5 @@ import java.lang.annotation.*;
@Target(ElementType.TYPE) // Applies to classes only @Target(ElementType.TYPE) // Applies to classes only
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface DBTable { public @interface DBTable {
public String name() default ""; String name() default "";
} }

View File

@ -9,5 +9,5 @@ import java.lang.annotation.*;
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
public @interface ExtractInterface { public @interface ExtractInterface {
public String interfaceName() default "-!!-"; String interfaceName() default "-!!-";
} }

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
// Searching with a Comparator // Searching with a Comparator import
import java.util.*; import java.util.*;
import onjava.*; import onjava.*;
import static onjava.ArrayShow.*; import static onjava.ArrayShow.*;
@ -12,18 +12,14 @@ public class AlphabeticSearch {
String[] sa = new Rand.String().array(30); String[] sa = new Rand.String().array(30);
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER); Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
show(sa); show(sa);
int index = Arrays.binarySearch(sa, sa[10], int index = Arrays.binarySearch(sa,
String.CASE_INSENSITIVE_ORDER); sa[10], String.CASE_INSENSITIVE_ORDER);
System.out.println( System.out.println( "Index: "+ index + "\n"+ sa[index]);
"Index: "+ index + "\n"+ sa[index]);
} }
} }
/* Output: /* Output:
[anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv, eloztdv, [anmkkyh, bhmupju, btpenpc, cjwzmmr, cuxszgv,
ewcippc, ezdeklu, fcjpthl, fqmlgsh, gmeinne, hyoubzl, eloztdv, ewcippc, ezdeklu, fcjpthl, fqmlgsh, gmeinne, hyoubzl, jbvlgwc, jlxpqds,
jbvlgwc, jlxpqds, ljlbynx, mvducuj, qgekgly, skddcat, ljlbynx, mvducuj, qgekgly, skddcat, taprwxz, uybypgp, vjsszkn, vniyapk, vqqakbm,
taprwxz, uybypgp, vjsszkn, vniyapk, vqqakbm, vwodhcf, vwodhcf, ydpulcq, ygpoalk, yskvett, zehpfmm, zofmmvm, zrxmclh] Index: 10 gmeinne
ydpulcq, ygpoalk, yskvett, zehpfmm, zofmmvm, zrxmclh]
Index: 10
gmeinne
*/ */

View File

@ -26,21 +26,21 @@ public class ArrayCopying {
int[] a1 = new int[SZ]; int[] a1 = new int[SZ];
Arrays.setAll(a1, new Count.Integer()::get); Arrays.setAll(a1, new Count.Integer()::get);
show("a1", a1); show("a1", a1);
int[] a2 = Arrays.copyOf(a1, a1.length); // (1) int[] a2 = Arrays.copyOf(a1, a1.length); // [1]
// Prove they are distinct arrays: // Prove they are distinct arrays:
Arrays.fill(a1, 1); Arrays.fill(a1, 1);
show("a1", a1); show("a1", a1);
show("a2", a2); show("a2", a2);
// Create a shorter result: // Create a shorter result:
a2 = Arrays.copyOf(a2, a2.length/2); // (2) a2 = Arrays.copyOf(a2, a2.length/2); // [2]
show("a2", a2); show("a2", a2);
// Allocate more space: // Allocate more space:
a2 = Arrays.copyOf(a2, a2.length + 5); a2 = Arrays.copyOf(a2, a2.length + 5);
show("a2", a2); show("a2", a2);
// Also copies wrapped arrays: // Also copies wrapped arrays:
Integer[] a3 = new Integer[SZ]; // (3) Integer[] a3 = new Integer[SZ]; // [3]
Arrays.setAll(a3, new Count.Integer()::get); Arrays.setAll(a3, new Count.Integer()::get);
Integer[] a4 = Arrays.copyOfRange(a3, 4, 12); Integer[] a4 = Arrays.copyOfRange(a3, 4, 12);
show("a4", a4); show("a4", a4);
@ -49,12 +49,12 @@ public class ArrayCopying {
Arrays.setAll(d, Sub::new); Arrays.setAll(d, Sub::new);
// Produce Sup[] from Sub[]: // Produce Sup[] from Sub[]:
Sup[] b = Sup[] b =
Arrays.copyOf(d, d.length, Sup[].class); // (4) Arrays.copyOf(d, d.length, Sup[].class); // [4]
show(b); show(b);
// This "downcast" works fine: // This "downcast" works fine:
Sub[] d2 = Sub[] d2 =
Arrays.copyOf(b, b.length, Sub[].class); // (5) Arrays.copyOf(b, b.length, Sub[].class); // [5]
show(d2); show(d2);
// Bad "downcast" compiles but throws exception: // Bad "downcast" compiles but throws exception:
@ -62,7 +62,7 @@ public class ArrayCopying {
Arrays.setAll(b2, Sup::new); Arrays.setAll(b2, Sup::new);
try { try {
Sub[] d3 = Sub[] d3 =
Arrays.copyOf(b2, b2.length, Sub[].class); // (6) Arrays.copyOf(b2, b2.length, Sub[].class); // [6]
} catch(Exception e) { } catch(Exception e) {
System.out.println(e); System.out.println(e);
} }

View File

@ -9,8 +9,8 @@ import static onjava.ArrayShow.*;
public class ArraySearching { public class ArraySearching {
public static void main(String[] args) { public static void main(String[] args) {
Rand.int_ rand = new Rand.int_(); Rand.Pint rand = new Rand.Pint();
int[] a = new Rand.int_().array(25); int[] a = new Rand.Pint().array(25);
Arrays.sort(a); Arrays.sort(a);
show("Sorted array", a); show("Sorted array", a);
while(true) { while(true) {

View File

@ -8,7 +8,7 @@ import onjava.*;
public class ComparingArrays { public class ComparingArrays {
public static final int SZ = 15; public static final int SZ = 15;
static String[][] TwoDArray() { static String[][] twoDArray() {
String[][] md = new String[5][]; String[][] md = new String[5][];
Arrays.setAll(md, n -> new String[n]); Arrays.setAll(md, n -> new String[n]);
for(int i = 0; i < md.length; i++) for(int i = 0; i < md.length; i++)
@ -35,7 +35,7 @@ public class ComparingArrays {
System.out.println( System.out.println(
"a1w == a2w: " + Arrays.equals(a1w, a2w)); "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(Arrays.deepToString(md1));
System.out.println("deepEquals(md1, md2): " + System.out.println("deepEquals(md1, md2): " +
Arrays.deepEquals(md1, md2)); Arrays.deepEquals(md1, md2));

View File

@ -11,7 +11,7 @@ public class ModifyExisting {
double[] da = new double[7]; double[] da = new double[7];
Arrays.setAll(da, new Rand.Double()::get); Arrays.setAll(da, new Rand.Double()::get);
show(da); show(da);
Arrays.setAll(da, n -> da[n] / 100); // (1) Arrays.setAll(da, n -> da[n] / 100); // [1]
show(da); show(da);
} }
} }

View File

@ -8,14 +8,14 @@ import static onjava.ArrayShow.*;
public class ParallelPrefix1 { public class ParallelPrefix1 {
public static void main(String[] args) { public static void main(String[] args) {
int[] nums = new Count.int_().array(10); int[] nums = new Count.Pint().array(10);
show(nums); show(nums);
System.out.println(Arrays.stream(nums) System.out.println(Arrays.stream(nums)
.reduce(Integer::sum).getAsInt()); .reduce(Integer::sum).getAsInt());
Arrays.parallelPrefix(nums, Integer::sum); Arrays.parallelPrefix(nums, Integer::sum);
show(nums); show(nums);
System.out.println(Arrays.stream( System.out.println(Arrays.stream(
new Count.int_().array(6)) new Count.Pint().array(6))
.reduce(Integer::sum).getAsInt()); .reduce(Integer::sum).getAsInt());
} }
} }

View File

@ -9,13 +9,13 @@ public class ParallelSetAll {
static final int SIZE = 10_000_000; static final int SIZE = 10_000_000;
static void intArray() { static void intArray() {
int[] ia = new int[SIZE]; int[] ia = new int[SIZE];
Arrays.setAll(ia, new Rand.int_()::get); Arrays.setAll(ia, new Rand.Pint()::get);
Arrays.parallelSetAll(ia, new Rand.int_()::get); Arrays.parallelSetAll(ia, new Rand.Pint()::get);
} }
static void longArray() { static void longArray() {
long[] la = new long[SIZE]; long[] la = new long[SIZE];
Arrays.setAll(la, new Rand.long_()::get); Arrays.setAll(la, new Rand.Plong()::get);
Arrays.parallelSetAll(la, new Rand.long_()::get); Arrays.parallelSetAll(la, new Rand.Plong()::get);
} }
public static void main(String[] args) { public static void main(String[] args) {
intArray(); intArray();

View File

@ -14,7 +14,7 @@ public class RaggedArray {
a[i] = new int[rand.nextInt(5)][]; a[i] = new int[rand.nextInt(5)][];
for(int j = 0; j < a[i].length; j++) { for(int j = 0; j < a[i].length; j++) {
a[i][j] = new int[rand.nextInt(5)]; 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)); System.out.println(Arrays.deepToString(a));

View File

@ -22,13 +22,13 @@ public class SimpleSetAll {
int[] ia = new int[SZ]; int[] ia = new int[SZ];
long[] la = new long[SZ]; long[] la = new long[SZ];
double[] da = new double[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(la, n -> n);
Arrays.setAll(da, n -> n); Arrays.setAll(da, n -> n);
show(ia); show(ia);
show(la); show(la);
show(da); show(da);
Arrays.setAll(ia, n -> val++); // (2) Arrays.setAll(ia, n -> val++); // [2]
Arrays.setAll(la, n -> val++); Arrays.setAll(la, n -> val++);
Arrays.setAll(da, n -> val++); Arrays.setAll(da, n -> val++);
show(ia); show(ia);
@ -36,11 +36,11 @@ public class SimpleSetAll {
show(da); show(da);
Bob[] ba = new Bob[SZ]; Bob[] ba = new Bob[SZ];
Arrays.setAll(ba, Bob::new); // (3) Arrays.setAll(ba, Bob::new); // [3]
show(ba); show(ba);
Character[] ca = new Character[SZ]; Character[] ca = new Character[SZ];
Arrays.setAll(ca, SimpleSetAll::getChar); // (4) Arrays.setAll(ca, SimpleSetAll::getChar); // [4]
show(ca); show(ca);
} }
} }

View File

@ -14,7 +14,7 @@ public class StreamFromArray {
.map(ss -> ss + "!") .map(ss -> ss + "!")
.forEach(System.out::println); .forEach(System.out::println);
int[] ia = new Rand.int_().array(10); int[] ia = new Rand.Pint().array(10);
Arrays.stream(ia) Arrays.stream(ia)
.skip(3) .skip(3)
.limit(5) .limit(5)
@ -32,7 +32,7 @@ public class StreamFromArray {
//- Arrays.stream(new float[10]); //- Arrays.stream(new float[10]);
// For the other types you must use wrapped arrays: // 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(ConvertTo.boxed(fa));
Arrays.stream(new Rand.Float().array(10)); Arrays.stream(new Rand.Float().array(10));
} }

View File

@ -8,58 +8,58 @@ import static onjava.ArrayShow.*;
import static onjava.ConvertTo.*; import static onjava.ConvertTo.*;
public class TestConvertTo { public class TestConvertTo {
static final int size = 6; static final int SIZE = 6;
public static void main(String[] args) { public static void main(String[] args) {
Boolean[] a1 = new Boolean[size]; Boolean[] a1 = new Boolean[SIZE];
Arrays.setAll(a1, new Rand.Boolean()::get); Arrays.setAll(a1, new Rand.Boolean()::get);
boolean[] a1p = primitive(a1); boolean[] a1p = primitive(a1);
show("a1p", a1p); show("a1p", a1p);
Boolean[] a1b = boxed(a1p); Boolean[] a1b = boxed(a1p);
show("a1b", a1b); show("a1b", a1b);
Byte[] a2 = new Byte[size]; Byte[] a2 = new Byte[SIZE];
Arrays.setAll(a2, new Rand.Byte()::get); Arrays.setAll(a2, new Rand.Byte()::get);
byte[] a2p = primitive(a2); byte[] a2p = primitive(a2);
show("a2p", a2p); show("a2p", a2p);
Byte[] a2b = boxed(a2p); Byte[] a2b = boxed(a2p);
show("a2b", a2b); show("a2b", a2b);
Character[] a3 = new Character[size]; Character[] a3 = new Character[SIZE];
Arrays.setAll(a3, new Rand.Character()::get); Arrays.setAll(a3, new Rand.Character()::get);
char[] a3p = primitive(a3); char[] a3p = primitive(a3);
show("a3p", a3p); show("a3p", a3p);
Character[] a3b = boxed(a3p); Character[] a3b = boxed(a3p);
show("a3b", a3b); show("a3b", a3b);
Short[] a4 = new Short[size]; Short[] a4 = new Short[SIZE];
Arrays.setAll(a4, new Rand.Short()::get); Arrays.setAll(a4, new Rand.Short()::get);
short[] a4p = primitive(a4); short[] a4p = primitive(a4);
show("a4p", a4p); show("a4p", a4p);
Short[] a4b = boxed(a4p); Short[] a4b = boxed(a4p);
show("a4b", a4b); show("a4b", a4b);
Integer[] a5 = new Integer[size]; Integer[] a5 = new Integer[SIZE];
Arrays.setAll(a5, new Rand.Integer()::get); Arrays.setAll(a5, new Rand.Integer()::get);
int[] a5p = primitive(a5); int[] a5p = primitive(a5);
show("a5p", a5p); show("a5p", a5p);
Integer[] a5b = boxed(a5p); Integer[] a5b = boxed(a5p);
show("a5b", a5b); show("a5b", a5b);
Long[] a6 = new Long[size]; Long[] a6 = new Long[SIZE];
Arrays.setAll(a6, new Rand.Long()::get); Arrays.setAll(a6, new Rand.Long()::get);
long[] a6p = primitive(a6); long[] a6p = primitive(a6);
show("a6p", a6p); show("a6p", a6p);
Long[] a6b = boxed(a6p); Long[] a6b = boxed(a6p);
show("a6b", a6b); show("a6b", a6b);
Float[] a7 = new Float[size]; Float[] a7 = new Float[SIZE];
Arrays.setAll(a7, new Rand.Float()::get); Arrays.setAll(a7, new Rand.Float()::get);
float[] a7p = primitive(a7); float[] a7p = primitive(a7);
show("a7p", a7p); show("a7p", a7p);
Float[] a7b = boxed(a7p); Float[] a7b = boxed(a7p);
show("a7b", a7b); show("a7b", a7b);
Double[] a8 = new Double[size]; Double[] a8 = new Double[SIZE];
Arrays.setAll(a8, new Rand.Double()::get); Arrays.setAll(a8, new Rand.Double()::get);
double[] a8p = primitive(a8); double[] a8p = primitive(a8);
show("a8p", a8p); show("a8p", a8p);

View File

@ -20,7 +20,7 @@ public class TestCount {
show(a1); show(a1);
a1 = new Count.Boolean().array(SZ + 2); a1 = new Count.Boolean().array(SZ + 2);
show(a1); show(a1);
boolean[] a1b = new Count.boolean_().array(SZ + 3); boolean[] a1b = new Count.Pboolean().array(SZ + 3);
show(a1b); show(a1b);
System.out.println("Byte"); System.out.println("Byte");
@ -32,7 +32,7 @@ public class TestCount {
show(a2); show(a2);
a2 = new Count.Byte().array(SZ + 2); a2 = new Count.Byte().array(SZ + 2);
show(a2); show(a2);
byte[] a2b = new Count.byte_().array(SZ + 3); byte[] a2b = new Count.Pbyte().array(SZ + 3);
show(a2b); show(a2b);
System.out.println("Character"); System.out.println("Character");
@ -44,7 +44,7 @@ public class TestCount {
show(a3); show(a3);
a3 = new Count.Character().array(SZ + 2); a3 = new Count.Character().array(SZ + 2);
show(a3); show(a3);
char[] a3b = new Count.char_().array(SZ + 3); char[] a3b = new Count.Pchar().array(SZ + 3);
show(a3b); show(a3b);
System.out.println("Short"); System.out.println("Short");
@ -56,7 +56,7 @@ public class TestCount {
show(a4); show(a4);
a4 = new Count.Short().array(SZ + 2); a4 = new Count.Short().array(SZ + 2);
show(a4); show(a4);
short[] a4b = new Count.short_().array(SZ + 3); short[] a4b = new Count.Pshort().array(SZ + 3);
show(a4b); show(a4b);
System.out.println("Integer"); System.out.println("Integer");
@ -68,10 +68,10 @@ public class TestCount {
show(a5b); show(a5b);
a5b = new Count.Integer().array(SZ + 2); a5b = new Count.Integer().array(SZ + 2);
show(a5b); show(a5b);
a5 = IntStream.generate(new Count.int_()) a5 = IntStream.generate(new Count.Pint())
.limit(SZ + 1).toArray(); .limit(SZ + 1).toArray();
show(a5); show(a5);
a5 = new Count.int_().array(SZ + 3); a5 = new Count.Pint().array(SZ + 3);
show(a5); show(a5);
System.out.println("Long"); System.out.println("Long");
@ -83,10 +83,10 @@ public class TestCount {
show(a6b); show(a6b);
a6b = new Count.Long().array(SZ + 2); a6b = new Count.Long().array(SZ + 2);
show(a6b); show(a6b);
a6 = LongStream.generate(new Count.long_()) a6 = LongStream.generate(new Count.Plong())
.limit(SZ + 1).toArray(); .limit(SZ + 1).toArray();
show(a6); show(a6);
a6 = new Count.long_().array(SZ + 3); a6 = new Count.Plong().array(SZ + 3);
show(a6); show(a6);
System.out.println("Float"); System.out.println("Float");
@ -98,7 +98,7 @@ public class TestCount {
show(a7); show(a7);
a7 = new Count.Float().array(SZ + 2); a7 = new Count.Float().array(SZ + 2);
show(a7); show(a7);
float[] a7b = new Count.float_().array(SZ + 3); float[] a7b = new Count.Pfloat().array(SZ + 3);
show(a7b); show(a7b);
System.out.println("Double"); System.out.println("Double");
@ -110,10 +110,10 @@ public class TestCount {
show(a8b); show(a8b);
a8b = new Count.Double().array(SZ + 2); a8b = new Count.Double().array(SZ + 2);
show(a8b); show(a8b);
a8 = DoubleStream.generate(new Count.double_()) a8 = DoubleStream.generate(new Count.Pdouble())
.limit(SZ + 1).toArray(); .limit(SZ + 1).toArray();
show(a8); show(a8);
a8 = new Count.double_().array(SZ + 3); a8 = new Count.Pdouble().array(SZ + 3);
show(a8); show(a8);
} }
} }

View File

@ -20,7 +20,7 @@ public class TestRand {
show(a1); show(a1);
a1 = new Rand.Boolean().array(SZ + 2); a1 = new Rand.Boolean().array(SZ + 2);
show(a1); show(a1);
boolean[] a1b = new Rand.boolean_().array(SZ + 3); boolean[] a1b = new Rand.Pboolean().array(SZ + 3);
show(a1b); show(a1b);
System.out.println("Byte"); System.out.println("Byte");
@ -32,7 +32,7 @@ public class TestRand {
show(a2); show(a2);
a2 = new Rand.Byte().array(SZ + 2); a2 = new Rand.Byte().array(SZ + 2);
show(a2); show(a2);
byte[] a2b = new Rand.byte_().array(SZ + 3); byte[] a2b = new Rand.Pbyte().array(SZ + 3);
show(a2b); show(a2b);
System.out.println("Character"); System.out.println("Character");
@ -44,7 +44,7 @@ public class TestRand {
show(a3); show(a3);
a3 = new Rand.Character().array(SZ + 2); a3 = new Rand.Character().array(SZ + 2);
show(a3); show(a3);
char[] a3b = new Rand.char_().array(SZ + 3); char[] a3b = new Rand.Pchar().array(SZ + 3);
show(a3b); show(a3b);
System.out.println("Short"); System.out.println("Short");
@ -56,7 +56,7 @@ public class TestRand {
show(a4); show(a4);
a4 = new Rand.Short().array(SZ + 2); a4 = new Rand.Short().array(SZ + 2);
show(a4); show(a4);
short[] a4b = new Rand.short_().array(SZ + 3); short[] a4b = new Rand.Pshort().array(SZ + 3);
show(a4b); show(a4b);
System.out.println("Integer"); System.out.println("Integer");
@ -68,10 +68,10 @@ public class TestRand {
show(a5b); show(a5b);
a5b = new Rand.Integer().array(SZ + 2); a5b = new Rand.Integer().array(SZ + 2);
show(a5b); show(a5b);
a5 = IntStream.generate(new Rand.int_()) a5 = IntStream.generate(new Rand.Pint())
.limit(SZ + 1).toArray(); .limit(SZ + 1).toArray();
show(a5); show(a5);
a5 = new Rand.int_().array(SZ + 3); a5 = new Rand.Pint().array(SZ + 3);
show(a5); show(a5);
System.out.println("Long"); System.out.println("Long");
@ -83,10 +83,10 @@ public class TestRand {
show(a6b); show(a6b);
a6b = new Rand.Long().array(SZ + 2); a6b = new Rand.Long().array(SZ + 2);
show(a6b); show(a6b);
a6 = LongStream.generate(new Rand.long_()) a6 = LongStream.generate(new Rand.Plong())
.limit(SZ + 1).toArray(); .limit(SZ + 1).toArray();
show(a6); show(a6);
a6 = new Rand.long_().array(SZ + 3); a6 = new Rand.Plong().array(SZ + 3);
show(a6); show(a6);
System.out.println("Float"); System.out.println("Float");
@ -98,7 +98,7 @@ public class TestRand {
show(a7); show(a7);
a7 = new Rand.Float().array(SZ + 2); a7 = new Rand.Float().array(SZ + 2);
show(a7); show(a7);
float[] a7b = new Rand.float_().array(SZ + 3); float[] a7b = new Rand.Pfloat().array(SZ + 3);
show(a7b); show(a7b);
System.out.println("Double"); System.out.println("Double");
@ -110,10 +110,10 @@ public class TestRand {
show(a8b); show(a8b);
a8b = new Rand.Double().array(SZ + 2); a8b = new Rand.Double().array(SZ + 2);
show(a8b); show(a8b);
a8 = DoubleStream.generate(new Rand.double_()) a8 = DoubleStream.generate(new Rand.Pdouble())
.limit(SZ + 1).toArray(); .limit(SZ + 1).toArray();
show(a8); show(a8);
a8 = new Rand.double_().array(SZ + 3); a8 = new Rand.Pdouble().array(SZ + 3);
show(a8); show(a8);
System.out.println("String"); System.out.println("String");

View File

@ -12,7 +12,7 @@ public class ParallelSort {
private long[] la; private long[] la;
@Setup @Setup
public void setup() { public void setup() {
la = new Rand.long_().array(100_000); la = new Rand.Plong().array(100_000);
} }
@Benchmark @Benchmark
public void sort() { public void sort() {

View File

@ -12,7 +12,7 @@ extends AbstractCollection<Pet> {
public int size() { return pets.length; } public int size() { return pets.length; }
@Override @Override
public Iterator<Pet> iterator() { public Iterator<Pet> iterator() {
return new Iterator<Pet>() { // (1) return new Iterator<Pet>() { // [1]
private int index = 0; private int index = 0;
@Override @Override
public boolean hasNext() { public boolean hasNext() {

View File

@ -12,7 +12,7 @@ public class Statistics {
for(int i = 0; i < 10000; i++) { for(int i = 0; i < 10000; i++) {
// Produce a number between 0 and 20: // Produce a number between 0 and 20:
int r = rand.nextInt(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); m.put(r, freq == null ? 1 : freq + 1);
} }
System.out.println(m); System.out.println(m);

View File

@ -7,14 +7,14 @@ import static onjava.Range.*;
public class BreakAndContinue { public class BreakAndContinue {
public static void main(String[] args) { public static void main(String[] args) {
for(int i = 0; i < 100; i++) { // (1) for(int i = 0; i < 100; i++) { // [1]
if(i == 74) break; // Out of for loop if(i == 74) break; // Out of for loop
if(i % 9 != 0) continue; // Next iteration if(i % 9 != 0) continue; // Next iteration
System.out.print(i + " "); System.out.print(i + " ");
} }
System.out.println(); System.out.println();
// Using for-in: // Using for-in:
for(int i : range(100)) { // (2) for(int i : range(100)) { // [2]
if(i == 74) break; // Out of for loop if(i == 74) break; // Out of for loop
if(i % 9 != 0) continue; // Next iteration if(i % 9 != 0) continue; // Next iteration
System.out.print(i + " "); System.out.print(i + " ");
@ -22,7 +22,7 @@ public class BreakAndContinue {
System.out.println(); System.out.println();
int i = 0; int i = 0;
// An "infinite loop": // An "infinite loop":
while(true) { // (3) while(true) { // [3]
i++; i++;
int j = i * 27; int j = i * 27;
if(j == 1269) break; // Out of loop if(j == 1269) break; // Out of loop

View File

@ -7,7 +7,7 @@ import java.util.*;
public class ForInFloat { public class ForInFloat {
public static void main(String[] args) { public static void main(String[] args) {
Random rand = new Random(47); Random rand = new Random(47);
float f[] = new float[10]; float[] f = new float[10];
for(int i = 0; i < 10; i++) for(int i = 0; i < 10; i++)
f[i] = rand.nextFloat(); f[i] = rand.nextFloat();
for(float x : f) for(float x : f)

View File

@ -8,7 +8,7 @@ public class IfElse {
static void test(int testval, int target) { static void test(int testval, int target) {
if(testval > target) if(testval > target)
result = +1; result = +1;
else if(testval < target) // (1) else if(testval < target) // [1]
result = -1; result = -1;
else else
result = 0; // Match result = 0; // Match

View File

@ -11,7 +11,7 @@ public class TrafficLight {
Signal color = Signal.RED; Signal color = Signal.RED;
public void change() { public void change() {
switch(color) { switch(color) {
// Note that you don't have to say Signal.RED // Note you don't have to say Signal.RED
// in the case statement: // in the case statement:
case RED: color = Signal.GREEN; case RED: color = Signal.GREEN;
break; break;

View File

@ -22,7 +22,7 @@ class NeedsCleanup2 extends NeedsCleanup {
public class CleanupIdiom { public class CleanupIdiom {
public static void main(String[] args) { public static void main(String[] args) {
// (1): // [1]:
NeedsCleanup nc1 = new NeedsCleanup(); NeedsCleanup nc1 = new NeedsCleanup();
try { try {
// ... // ...
@ -30,7 +30,7 @@ public class CleanupIdiom {
nc1.dispose(); nc1.dispose();
} }
// (2): // [2]:
// If construction cannot fail you can group objects: // If construction cannot fail you can group objects:
NeedsCleanup nc2 = new NeedsCleanup(); NeedsCleanup nc2 = new NeedsCleanup();
NeedsCleanup nc3 = new NeedsCleanup(); NeedsCleanup nc3 = new NeedsCleanup();
@ -41,7 +41,7 @@ public class CleanupIdiom {
nc2.dispose(); nc2.dispose();
} }
// (3): // [3]:
// If construction can fail you must guard each one: // If construction can fail you must guard each one:
try { try {
NeedsCleanup2 nc4 = new NeedsCleanup2(); NeedsCleanup2 nc4 = new NeedsCleanup2();

View File

@ -24,8 +24,8 @@ class RainedOut extends StormException {}
class PopFoul extends Foul {} class PopFoul extends Foul {}
interface Storm { interface Storm {
public void event() throws RainedOut; void event() throws RainedOut;
public void rainHard() throws RainedOut; void rainHard() throws RainedOut;
} }
public public
@ -35,7 +35,7 @@ class StormyInning extends Inning implements Storm {
public StormyInning() public StormyInning()
throws RainedOut, BaseballException {} throws RainedOut, BaseballException {}
public StormyInning(String s) public StormyInning(String s)
throws Foul, BaseballException {} throws BaseballException {}
// Regular methods must conform to base class: // Regular methods must conform to base class:
//- void walk() throws PopFoul {} //Compile error //- void walk() throws PopFoul {} //Compile error
// Interface CANNOT add exceptions to existing // Interface CANNOT add exceptions to existing

View File

@ -13,12 +13,12 @@ public class StreamsAreAutoCloseable {
Stream<String> in = Files.lines( Stream<String> in = Files.lines(
Paths.get("StreamsAreAutoCloseable.java")); Paths.get("StreamsAreAutoCloseable.java"));
PrintWriter outfile = new PrintWriter( PrintWriter outfile = new PrintWriter(
"Results.txt"); // (1) "Results.txt"); // [1]
) { ) {
in.skip(5) in.skip(5)
.limit(1) .limit(1)
.map(String::toLowerCase) .map(String::toLowerCase)
.forEachOrdered(outfile::println); .forEachOrdered(outfile::println);
} // (2) } // [2]
} }
} }

View File

@ -1,10 +1,10 @@
// files/File_System.java // files/FileSystemDemo.java
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
import java.nio.file.*; import java.nio.file.*;
public class File_System { public class FileSystemDemo {
static void show(String id, Object o) { static void show(String id, Object o) {
System.out.println(id + ": " + o); System.out.println(id + ": " + o);
} }

View File

@ -7,11 +7,11 @@ import java.nio.file.*;
public class Writing { public class Writing {
static Random rand = new Random(47); static Random rand = new Random(47);
static final int sz = 1000; static final int SIZE = 1000;
public static void public static void
main(String[] args) throws Exception { main(String[] args) throws Exception {
// Write bytes to a file: // Write bytes to a file:
byte[] bytes = new byte[sz]; byte[] bytes = new byte[SIZE];
rand.nextBytes(bytes); rand.nextBytes(bytes);
Files.write(Paths.get("bytes.dat"), bytes); Files.write(Paths.get("bytes.dat"), bytes);
System.out.println("bytes.dat: " + System.out.println("bytes.dat: " +

View File

@ -5,7 +5,7 @@
import java.util.function.*; import java.util.function.*;
public class AnonymousClosure { public class AnonymousClosure {
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
int i = 0; int i = 0;
// Same rules apply: // Same rules apply:
// i++; // Not "effectively final" // i++; // Not "effectively final"

View File

@ -6,11 +6,11 @@ import java.util.function.*;
public class BiConsumerPermutations { public class BiConsumerPermutations {
static BiConsumer<Integer, Double> bicid = (i, d) -> static BiConsumer<Integer, Double> bicid = (i, d) ->
System.out.format("%d, %f\n", i, d); System.out.format("%d, %f%n", i, d);
static BiConsumer<Double, Integer> bicdi = (d, i) -> static BiConsumer<Double, Integer> bicdi = (d, i) ->
System.out.format("%d, %f\n", i, d); System.out.format("%d, %f%n", i, d);
static BiConsumer<Integer, Long> bicil = (i, l) -> static BiConsumer<Integer, Long> bicil = (i, l) ->
System.out.format("%d, %d\n", i, l); System.out.format("%d, %d%n", i, l);
public static void main(String[] args) { public static void main(String[] args) {
bicid.accept(47, 11.34); bicid.accept(47, 11.34);
bicdi.accept(22.45, 92); bicdi.accept(22.45, 92);

View File

@ -6,7 +6,7 @@ import java.util.function.*;
public class Closure1 { public class Closure1 {
int i; int i;
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
return () -> x + i++; return () -> x + i++;
} }
} }

View File

@ -5,7 +5,7 @@
import java.util.function.*; import java.util.function.*;
public class Closure2 { public class Closure2 {
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
int i = 0; int i = 0;
return () -> x + i; return () -> x + i;
} }

View File

@ -6,7 +6,7 @@
import java.util.function.*; import java.util.function.*;
public class Closure3 { public class Closure3 {
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
int i = 0; int i = 0;
// Neither x++ nor i++ will work: // Neither x++ nor i++ will work:
return () -> x++ + i++; return () -> x++ + i++;

View File

@ -5,7 +5,7 @@
import java.util.function.*; import java.util.function.*;
public class Closure4 { public class Closure4 {
IntSupplier make_fun(final int x) { IntSupplier makeFun(final int x) {
final int i = 0; final int i = 0;
return () -> x + i; return () -> x + i;
} }

View File

@ -6,7 +6,7 @@
import java.util.function.*; import java.util.function.*;
public class Closure5 { public class Closure5 {
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
int i = 0; int i = 0;
i++; i++;
x++; x++;

View File

@ -5,12 +5,12 @@
import java.util.function.*; import java.util.function.*;
public class Closure6 { public class Closure6 {
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
int i = 0; int i = 0;
i++; i++;
x++; x++;
final int i_final = i; final int iFinal = i;
final int x_final = x; final int xFinal = x;
return () -> x_final + i_final; return () -> xFinal + iFinal;
} }
} }

View File

@ -6,7 +6,7 @@
import java.util.function.*; import java.util.function.*;
public class Closure7 { public class Closure7 {
IntSupplier make_fun(int x) { IntSupplier makeFun(int x) {
Integer i = new Integer(0); Integer i = new Integer(0);
i = i + 1; i = i + 1;
return () -> x + i; return () -> x + i;

View File

@ -6,7 +6,7 @@ import java.util.*;
import java.util.function.*; import java.util.function.*;
public class Closure8 { public class Closure8 {
Supplier<List<Integer>> make_fun() { Supplier<List<Integer>> makeFun() {
final List<Integer> ai = new ArrayList<>(); final List<Integer> ai = new ArrayList<>();
ai.add(1); ai.add(1);
return () -> ai; return () -> ai;
@ -14,8 +14,8 @@ public class Closure8 {
public static void main(String[] args) { public static void main(String[] args) {
Closure8 c7 = new Closure8(); Closure8 c7 = new Closure8();
List<Integer> List<Integer>
l1 = c7.make_fun().get(), l1 = c7.makeFun().get(),
l2 = c7.make_fun().get(); l2 = c7.makeFun().get();
System.out.println(l1); System.out.println(l1);
System.out.println(l2); System.out.println(l2);
l1.add(42); l1.add(42);

View File

@ -7,7 +7,7 @@ import java.util.*;
import java.util.function.*; import java.util.function.*;
public class Closure9 { public class Closure9 {
Supplier<List<Integer>> make_fun() { Supplier<List<Integer>> makeFun() {
List<Integer> ai = new ArrayList<>(); List<Integer> ai = new ArrayList<>();
ai = new ArrayList<>(); // Reassignment ai = new ArrayList<>(); // Reassignment
return () -> ai; return () -> ai;

View File

@ -25,9 +25,9 @@ interface Make2Args {
public class CtorReference { public class CtorReference {
public static void main(String[] args) { public static void main(String[] args) {
MakeNoArgs mna = Dog::new; // (1) MakeNoArgs mna = Dog::new; // [1]
Make1Arg m1a = Dog::new; // (2) Make1Arg m1a = Dog::new; // [2]
Make2Args m2a = Dog::new; // (3) Make2Args m2a = Dog::new; // [3]
Dog dn = mna.make(); Dog dn = mna.make();
Dog d1 = m1a.make("Comet"); Dog d1 = m1a.make("Comet");

View File

@ -12,12 +12,12 @@ public class CurryingAndPartials {
public static void main(String[] args) { public static void main(String[] args) {
// Curried function: // Curried function:
Function<String, Function<String, String>> sum = Function<String, Function<String, String>> sum =
a -> b -> a + b; // (1) a -> b -> a + b; // [1]
System.out.println(uncurried("Hi ", "Ho")); System.out.println(uncurried("Hi ", "Ho"));
Function<String, String> Function<String, String>
hi = sum.apply("Hi "); // (2) hi = sum.apply("Hi "); // [2]
System.out.println(hi.apply("Ho")); System.out.println(hi.apply("Ho"));
// Partial application: // Partial application:

View File

@ -17,15 +17,15 @@ interface Multi {
public class LambdaExpressions { public class LambdaExpressions {
static Body bod = h -> h + " No Parens!"; // (1) static Body bod = h -> h + " No Parens!"; // [1]
static Body bod2 = (h) -> h + " More details"; // (2) static Body bod2 = (h) -> h + " More details"; // [2]
static Description desc = () -> "Short info"; // (3) static Description desc = () -> "Short info"; // [3]
static Multi mult = (h, n) -> h + n; // (4) static Multi mult = (h, n) -> h + n; // [4]
static Description moreLines = () -> { // (5) static Description moreLines = () -> { // [5]
System.out.println("moreLines()"); System.out.println("moreLines()");
return "from moreLines()"; return "from moreLines()";
}; };

View File

@ -4,44 +4,44 @@
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
import java.util.*; import java.util.*;
interface Callable { // (1) interface Callable { // [1]
void call(String s); void call(String s);
} }
class Describe { class Describe {
void show(String msg) { // (2) void show(String msg) { // [2]
System.out.println(msg); System.out.println(msg);
} }
} }
public class MethodReferences { public class MethodReferences {
static void hello(String name) { // (3) static void hello(String name) { // [3]
System.out.println("Hello, " + name); System.out.println("Hello, " + name);
} }
static class Description { static class Description {
String about; String about;
public Description(String desc) { about = desc; } public Description(String desc) { about = desc; }
void help(String msg) { // (4) void help(String msg) { // [4]
System.out.println(about + " " + msg); System.out.println(about + " " + msg);
} }
} }
static class Helper { static class Helper {
static void assist(String msg) { // (5) static void assist(String msg) { // [5]
System.out.println(msg); System.out.println(msg);
} }
} }
public static void main(String[] args) { public static void main(String[] args) {
Describe d = new Describe(); Describe d = new Describe();
Callable c = d::show; // (6) Callable c = d::show; // [6]
c.call("call()"); // (7) c.call("call()"); // [7]
c = MethodReferences::hello; // (8) c = MethodReferences::hello; // [8]
c.call("Bob"); c.call("Bob");
c = new Description("valuable")::help; // (9) c = new Description("valuable")::help; // [9]
c.call("information"); c.call("information");
c = Helper::assist; // (10) c = Helper::assist; // [10]
c.call("Help!"); c.call("Help!");
} }
} }

View File

@ -11,16 +11,16 @@ class This {
} }
interface TwoArgs { interface TwoArgs {
void call2(This _this, int i, double d); void call2(This athis, int i, double d);
} }
interface ThreeArgs { interface ThreeArgs {
void call3(This _this, int i, double d, String s); void call3(This athis, int i, double d, String s);
} }
interface FourArgs { interface FourArgs {
void call4( void call4(
This _this, int i, double d, String s, char c); This athis, int i, double d, String s, char c);
} }
public class MultiUnbound { public class MultiUnbound {
@ -28,9 +28,9 @@ public class MultiUnbound {
TwoArgs twoargs = This::two; TwoArgs twoargs = This::two;
ThreeArgs threeargs = This::three; ThreeArgs threeargs = This::three;
FourArgs fourargs = This::four; FourArgs fourargs = This::four;
This _this = new This(); This athis = new This();
twoargs.call2(_this, 11, 3.14); twoargs.call2(athis, 11, 3.14);
threeargs.call3(_this, 11, 3.14, "Three"); threeargs.call3(athis, 11, 3.14, "Three");
fourargs.call4(_this, 11, 3.14, "Four", 'Z'); fourargs.call4(athis, 11, 3.14, "Four", 'Z');
} }
} }

View File

@ -5,11 +5,11 @@
import java.util.function.*; import java.util.function.*;
interface interface
FuncSS extends Function<String, String> {} // (1) FuncSS extends Function<String, String> {} // [1]
public class ProduceFunction { public class ProduceFunction {
static FuncSS produce() { static FuncSS produce() {
return s -> s.toLowerCase(); // (2) return s -> s.toLowerCase(); // [2]
} }
public static void main(String[] args) { public static void main(String[] args) {
FuncSS f = produce(); FuncSS f = produce();

View File

@ -7,9 +7,9 @@ import java.util.function.*;
public class SharedStorage { public class SharedStorage {
public static void main(String[] args) { public static void main(String[] args) {
Closure1 c1 = new Closure1(); Closure1 c1 = new Closure1();
IntSupplier f1 = c1.make_fun(0); IntSupplier f1 = c1.makeFun(0);
IntSupplier f2 = c1.make_fun(0); IntSupplier f2 = c1.makeFun(0);
IntSupplier f3 = c1.make_fun(0); IntSupplier f3 = c1.makeFun(0);
System.out.println(f1.getAsInt()); System.out.println(f1.getAsInt());
System.out.println(f2.getAsInt()); System.out.println(f2.getAsInt());
System.out.println(f3.getAsInt()); System.out.println(f3.getAsInt());

View File

@ -23,7 +23,7 @@ public class Strategize {
Strategy strategy; Strategy strategy;
String msg; String msg;
Strategize(String msg) { Strategize(String msg) {
strategy = new Soft(); // (1) strategy = new Soft(); // [1]
this.msg = msg; this.msg = msg;
} }
void communicate() { void communicate() {
@ -34,19 +34,19 @@ public class Strategize {
} }
public static void main(String[] args) { public static void main(String[] args) {
Strategy[] strategies = { Strategy[] strategies = {
new Strategy() { // (2) new Strategy() { // [2]
public String approach(String msg) { public String approach(String msg) {
return msg.toUpperCase() + "!"; return msg.toUpperCase() + "!";
} }
}, },
msg -> msg.substring(0, 5), // (3) msg -> msg.substring(0, 5), // [3]
Unrelated::twice // (4) Unrelated::twice // [4]
}; };
Strategize s = new Strategize("Hello there"); Strategize s = new Strategize("Hello there");
s.communicate(); s.communicate();
for(Strategy newStrategy : strategies) { for(Strategy newStrategy : strategies) {
s.changeStrategy(newStrategy); // (5) s.changeStrategy(newStrategy); // [5]
s.communicate(); // (6) s.communicate(); // [6]
} }
} }
} }

View File

@ -18,10 +18,10 @@ interface TransformX {
public class UnboundMethodReference { public class UnboundMethodReference {
public static void main(String[] args) { public static void main(String[] args) {
// MakeString ms = X::f; // (1) // MakeString ms = X::f; // [1]
TransformX sp = X::f; TransformX sp = X::f;
X x = new X(); X x = new X();
System.out.println(sp.transform(x)); // (2) System.out.println(sp.transform(x)); // [2]
System.out.println(x.f()); // Same effect System.out.println(x.f()); // Same effect
} }
} }

View File

@ -6,19 +6,19 @@
import typeinfo.pets.*; import typeinfo.pets.*;
import java.util.function.*; import java.util.function.*;
class PerformingDog_ extends Dog { class PerformingDogA extends Dog {
public void speak() { System.out.println("Woof!"); } public void speak() { System.out.println("Woof!"); }
public void sit() { System.out.println("Sitting"); } public void sit() { System.out.println("Sitting"); }
public void reproduce() {} public void reproduce() {}
} }
class Robot_ { class RobotA {
public void speak() { System.out.println("Click!"); } public void speak() { System.out.println("Click!"); }
public void sit() { System.out.println("Clank!"); } public void sit() { System.out.println("Clank!"); }
public void oilChange() {} public void oilChange() {}
} }
class Communicate_ { class CommunicateA {
public static <P> void perform(P performer, public static <P> void perform(P performer,
Consumer<P> action1, Consumer<P> action2) { Consumer<P> action1, Consumer<P> action2) {
action1.accept(performer); action1.accept(performer);
@ -28,11 +28,11 @@ class Communicate_ {
public class DogsAndRobotMethodReferences { public class DogsAndRobotMethodReferences {
public static void main(String[] args) { public static void main(String[] args) {
Communicate_.perform(new PerformingDog_(), CommunicateA.perform(new PerformingDogA(),
PerformingDog_::speak, PerformingDog_::sit); PerformingDogA::speak, PerformingDogA::sit);
Communicate_.perform(new Robot_(), CommunicateA.perform(new RobotA(),
Robot_::speak, Robot_::sit); RobotA::speak, RobotA::sit);
Communicate_.perform(new Mime(), CommunicateA.perform(new Mime(),
Mime::walkAgainstTheWind, Mime::pushInvisibleWalls); Mime::walkAgainstTheWind, Mime::pushInvisibleWalls);
} }
} }

View File

@ -13,12 +13,12 @@ class MixinProxy implements InvocationHandler {
public MixinProxy(Tuple2<Object, Class<?>>... pairs) { public MixinProxy(Tuple2<Object, Class<?>>... pairs) {
delegatesByMethod = new HashMap<>(); delegatesByMethod = new HashMap<>();
for(Tuple2<Object, Class<?>> pair : pairs) { for(Tuple2<Object, Class<?>> pair : pairs) {
for(Method method : pair._2.getMethods()) { for(Method method : pair.a2.getMethods()) {
String methodName = method.getName(); String methodName = method.getName();
// The first interface in the map // The first interface in the map
// implements the method. // implements the method.
if(!delegatesByMethod.containsKey(methodName)) if(!delegatesByMethod.containsKey(methodName))
delegatesByMethod.put(methodName, pair._1); delegatesByMethod.put(methodName, pair.a1);
} }
} }
} }
@ -33,10 +33,10 @@ class MixinProxy implements InvocationHandler {
public static Object newInstance(Tuple2... pairs) { public static Object newInstance(Tuple2... pairs) {
Class[] interfaces = new Class[pairs.length]; Class[] interfaces = new Class[pairs.length];
for(int i = 0; i < pairs.length; i++) { for(int i = 0; i < pairs.length; i++) {
interfaces[i] = (Class)pairs[i]._2; interfaces[i] = (Class)pairs[i].a2;
} }
ClassLoader cl = ClassLoader cl =
pairs[0]._1.getClass().getClassLoader(); pairs[0].a1.getClass().getClassLoader();
return Proxy.newProxyInstance( return Proxy.newProxyInstance(
cl, interfaces, new MixinProxy(pairs)); cl, interfaces, new MixinProxy(pairs));
} }

View File

@ -13,7 +13,7 @@ public class GenericsAndCovariance {
// flist.add(new Fruit()); // flist.add(new Fruit());
// flist.add(new Object()); // flist.add(new Object());
flist.add(null); // Legal but uninteresting flist.add(null); // Legal but uninteresting
// We know that it returns at least Fruit: // We know it returns at least Fruit:
Fruit f = flist.get(0); Fruit f = flist.get(0);
} }
} }

View File

@ -2,6 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
import java.util.Objects;
public class Holder<T> { public class Holder<T> {
private T value; private T value;
@ -10,8 +11,14 @@ public class Holder<T> {
public void set(T val) { value = val; } public void set(T val) { value = val; }
public T get() { return value; } public T get() { return value; }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object o) {
return value.equals(obj); if (o == this) return true;
return o instanceof Holder &&
Objects.equals(value, ((Holder)o).value);
}
@Override
public int hashCode() {
return Objects.hash(value);
} }
public static void main(String[] args) { public static void main(String[] args) {
Holder<Apple> apple = new Holder<>(new Apple()); Holder<Apple> apple = new Holder<>(new Apple());
@ -32,5 +39,5 @@ public class Holder<T> {
/* Output: /* Output:
java.lang.ClassCastException: Apple cannot be cast to java.lang.ClassCastException: Apple cannot be cast to
Orange Orange
true false
*/ */

View File

@ -36,7 +36,7 @@ public class PrimitiveGenericTest {
new String[5], new Rand.String(9)); new String[5], new Rand.String(9));
System.out.println(Arrays.toString(strings)); System.out.println(Arrays.toString(strings));
int[] integers = FillArray.fill( int[] integers = FillArray.fill(
new int[9], new Rand.int_()); new int[9], new Rand.Pint());
System.out.println(Arrays.toString(integers)); System.out.println(Arrays.toString(integers));
} }
} }

View File

@ -12,8 +12,8 @@ class Product {
private String description; private String description;
private double price; private double price;
public public
Product(int IDnumber, String descr, double price) { Product(int idNumber, String descr, double price) {
id = IDnumber; id = idNumber;
description = descr; description = descr;
this.price = price; this.price = price;
System.out.println(toString()); System.out.println(toString());

View File

@ -27,7 +27,7 @@ public class TupleTest {
public static void main(String[] args) { public static void main(String[] args) {
Tuple2<String, Integer> ttsi = f(); Tuple2<String, Integer> ttsi = f();
System.out.println(ttsi); System.out.println(ttsi);
// ttsi._1 = "there"; // Compile error: final // ttsi.a1 = "there"; // Compile error: final
System.out.println(g()); System.out.println(g());
System.out.println(h()); System.out.println(h());
System.out.println(k()); System.out.println(k());

3
go.bat
View File

@ -1,3 +0,0 @@
gradlew --parallel --daemon run > output.txt 2> errors.txt
START /min "C:\Program Files\Windows Media Player\wmplayer.exe" %windir%\media\Alarm07.wav
rem find . -size 0 -type f

View File

@ -7,14 +7,14 @@
class Soup1 { class Soup1 {
private Soup1() {} private Soup1() {}
public static Soup1 makeSoup() { // (1) public static Soup1 makeSoup() { // [1]
return new Soup1(); return new Soup1();
} }
} }
class Soup2 { class Soup2 {
private Soup2() {} private Soup2() {}
private static Soup2 ps1 = new Soup2(); // (2) private static Soup2 ps1 = new Soup2(); // [2]
public static Soup2 access() { public static Soup2 access() {
return ps1; return ps1;
} }

View File

@ -28,10 +28,10 @@ class Cups {
public class ExplicitStatic { public class ExplicitStatic {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Inside main()"); System.out.println("Inside main()");
Cups.cup1.f(99); // (1) Cups.cup1.f(99); // [1]
} }
// static Cups cups1 = new Cups(); // (2) // static Cups cups1 = new Cups(); // [2]
// static Cups cups2 = new Cups(); // (2) // static Cups cups2 = new Cups(); // [2]
} }
/* Output: /* Output:
Inside main() Inside main()

View File

@ -16,7 +16,7 @@ class Mug {
public class Mugs { public class Mugs {
Mug mug1; Mug mug1;
Mug mug2; Mug mug2;
{ // (1) { // [1]
mug1 = new Mug(1); mug1 = new Mug(1);
mug2 = new Mug(2); mug2 = new Mug(2);
System.out.println("mug1 & mug2 initialized"); System.out.println("mug1 & mug2 initialized");

View File

@ -2,7 +2,7 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
// An inner class cannot be overriden like a method // An inner class cannot be overridden like a method
class Egg { class Egg {
private Yolk y; private Yolk y;

View File

@ -11,7 +11,7 @@ public class Parcel11 {
@Override @Override
public int value() { return i; } public int value() { return i; }
} }
protected static class ParcelDestination protected static final class ParcelDestination
implements Destination { implements Destination {
private String label; private String label;
private ParcelDestination(String whereTo) { private ParcelDestination(String whereTo) {

View File

@ -6,7 +6,7 @@
public class Parcel5 { public class Parcel5 {
public Destination destination(String s) { public Destination destination(String s) {
class PDestination implements Destination { final class PDestination implements Destination {
private String label; private String label;
private PDestination(String whereTo) { private PDestination(String whereTo) {
label = whereTo; label = whereTo;

View File

@ -7,12 +7,12 @@
public class Parcel8 { public class Parcel8 {
public Wrapping wrapping(int x) { public Wrapping wrapping(int x) {
// Base constructor call: // Base constructor call:
return new Wrapping(x) { // (1) return new Wrapping(x) { // [1]
@Override @Override
public int value() { public int value() {
return super.value() * 47; return super.value() * 47;
} }
}; // (2) }; // [2]
} }
public static void main(String[] args) { public static void main(String[] args) {
Parcel8 p = new Parcel8(); Parcel8 p = new Parcel8();

View File

@ -9,7 +9,8 @@ class Parcel4 {
@Override @Override
public int value() { return i; } public int value() { return i; }
} }
protected class PDestination implements Destination { protected final class
PDestination implements Destination {
private String label; private String label;
private PDestination(String whereTo) { private PDestination(String whereTo) {
label = whereTo; label = whereTo;

View File

@ -9,8 +9,8 @@ import java.time.*; // Java 8 time classes
public abstract class Event { public abstract class Event {
private Instant eventTime; private Instant eventTime;
protected final Duration delayTime; protected final Duration delayTime;
public Event(long millisecond_delay) { public Event(long millisecondDelay) {
delayTime = Duration.ofMillis(millisecond_delay); delayTime = Duration.ofMillis(millisecondDelay);
start(); start();
} }
public void start() { // Allows restarting public void start() { // Allows restarting

View File

@ -11,5 +11,5 @@ abstract class AbstractAccess {
void m3() {} void m3() {}
abstract void m3a(); abstract void m3a();
public void m4() {} public void m4() {}
abstract public void m4a(); public abstract void m4a();
} }

View File

@ -40,7 +40,7 @@ public class Applicator {
System.out.println("Using Processor " + p.name()); System.out.println("Using Processor " + p.name());
System.out.println(p.process(s)); System.out.println(p.process(s));
} }
public static String s = public static final String s =
"Disagreement with beliefs is by definition incorrect"; "Disagreement with beliefs is by definition incorrect";
public static void main(String[] args) { public static void main(String[] args) {
apply(new Upcase(), s); apply(new Upcase(), s);

View File

@ -5,9 +5,9 @@
import java.util.*; import java.util.*;
public interface RandomDoubles { public interface RandomDoubles {
Random rand = new Random(47); Random RAND = new Random(47);
default double next() { return rand.nextDouble(); } default double next() { return RAND.nextDouble(); }
public static void main(String[] args) { static void main(String[] args) {
RandomDoubles rd = new RandomDoubles() {}; RandomDoubles rd = new RandomDoubles() {};
for(int i = 0; i < 7; i ++) for(int i = 0; i < 7; i ++)
System.out.print(rd.next() + " "); System.out.print(rd.next() + " ");

View File

@ -8,11 +8,11 @@ import java.util.*;
public class RandomWords implements Readable { public class RandomWords implements Readable {
private static Random rand = new Random(47); private static Random rand = new Random(47);
private static final char[] capitals = private static final char[] CAPITALS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static final char[] lowers = private static final char[] LOWERS =
"abcdefghijklmnopqrstuvwxyz".toCharArray(); "abcdefghijklmnopqrstuvwxyz".toCharArray();
private static final char[] vowels = private static final char[] VOWELS =
"aeiou".toCharArray(); "aeiou".toCharArray();
private int count; private int count;
public RandomWords(int count) { this.count = count; } public RandomWords(int count) { this.count = count; }
@ -20,10 +20,10 @@ public class RandomWords implements Readable {
public int read(CharBuffer cb) { public int read(CharBuffer cb) {
if(count-- == 0) if(count-- == 0)
return -1; // Indicates end of input return -1; // Indicates end of input
cb.append(capitals[rand.nextInt(capitals.length)]); cb.append(CAPITALS[rand.nextInt(CAPITALS.length)]);
for(int i = 0; i < 4; i++) { for(int i = 0; i < 4; i++) {
cb.append(vowels[rand.nextInt(vowels.length)]); cb.append(VOWELS[rand.nextInt(VOWELS.length)]);
cb.append(lowers[rand.nextInt(lowers.length)]); cb.append(LOWERS[rand.nextInt(LOWERS.length)]);
} }
cb.append(" "); cb.append(" ");
return 10; // Number of characters appended return 10; // Number of characters appended

View File

@ -8,13 +8,13 @@ import java.util.*;
interface StringProcessor extends Processor { interface StringProcessor extends Processor {
@Override @Override
String process(Object input); // (1) String process(Object input); // [1]
String s = // (2) String S = // [2]
"If she weighs the same as a duck, she's made of wood"; "If she weighs the same as a duck, she's made of wood";
public static void main(String[] args) { // (3) static void main(String[] args) { // [3]
Applicator.apply(new Upcase(), s); Applicator.apply(new Upcase(), S);
Applicator.apply(new Downcase(), s); Applicator.apply(new Downcase(), S);
Applicator.apply(new Splitter(), s); Applicator.apply(new Splitter(), S);
} }
} }

View File

@ -5,98 +5,98 @@
package onjava; package onjava;
public interface ConvertTo { public interface ConvertTo {
public static boolean[] primitive(Boolean[] in) { static boolean[] primitive(Boolean[] in) {
boolean[] result = new boolean[in.length]; boolean[] result = new boolean[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; // Autounboxing result[i] = in[i]; // Autounboxing
return result; return result;
} }
public static char[] primitive(Character[] in) { static char[] primitive(Character[] in) {
char[] result = new char[in.length]; char[] result = new char[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static byte[] primitive(Byte[] in) { static byte[] primitive(Byte[] in) {
byte[] result = new byte[in.length]; byte[] result = new byte[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static short[] primitive(Short[] in) { static short[] primitive(Short[] in) {
short[] result = new short[in.length]; short[] result = new short[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static int[] primitive(Integer[] in) { static int[] primitive(Integer[] in) {
int[] result = new int[in.length]; int[] result = new int[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static long[] primitive(Long[] in) { static long[] primitive(Long[] in) {
long[] result = new long[in.length]; long[] result = new long[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static float[] primitive(Float[] in) { static float[] primitive(Float[] in) {
float[] result = new float[in.length]; float[] result = new float[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static double[] primitive(Double[] in) { static double[] primitive(Double[] in) {
double[] result = new double[in.length]; double[] result = new double[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
// Convert from primitive array to wrapped array: // Convert from primitive array to wrapped array:
public static Boolean[] boxed(boolean[] in) { static Boolean[] boxed(boolean[] in) {
Boolean[] result = new Boolean[in.length]; Boolean[] result = new Boolean[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; // Autboxing result[i] = in[i]; // Autboxing
return result; return result;
} }
public static Character[] boxed(char[] in) { static Character[] boxed(char[] in) {
Character[] result = new Character[in.length]; Character[] result = new Character[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static Byte[] boxed(byte[] in) { static Byte[] boxed(byte[] in) {
Byte[] result = new Byte[in.length]; Byte[] result = new Byte[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static Short[] boxed(short[] in) { static Short[] boxed(short[] in) {
Short[] result = new Short[in.length]; Short[] result = new Short[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static Integer[] boxed(int[] in) { static Integer[] boxed(int[] in) {
Integer[] result = new Integer[in.length]; Integer[] result = new Integer[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static Long[] boxed(long[] in) { static Long[] boxed(long[] in) {
Long[] result = new Long[in.length]; Long[] result = new Long[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static Float[] boxed(float[] in) { static Float[] boxed(float[] in) {
Float[] result = new Float[in.length]; Float[] result = new Float[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];
return result; return result;
} }
public static Double[] boxed(double[] in) { static Double[] boxed(double[] in) {
Double[] result = new Double[in.length]; Double[] result = new Double[in.length];
for(int i = 0; i < in.length; i++) for(int i = 0; i < in.length; i++)
result[i] = in[i]; result[i] = in[i];

View File

@ -25,7 +25,7 @@ public interface Count {
return result; return result;
} }
} }
public static class boolean_ { public static class Pboolean {
private boolean b = true; private boolean b = true;
public boolean get() { public boolean get() {
b = !b; b = !b;
@ -48,7 +48,7 @@ public interface Count {
return result; return result;
} }
} }
public static class byte_ { public static class Pbyte {
private byte b; private byte b;
public byte get() { return b++; } public byte get() { return b++; }
public byte get(int n) { return get(); } public byte get(int n) { return get(); }
@ -56,15 +56,15 @@ public interface Count {
return primitive(new Byte().array(sz)); return primitive(new Byte().array(sz));
} }
} }
static final char[] chars = char[] CHARS =
"abcdefghijklmnopqrstuvwxyz".toCharArray(); "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static class Character public static class Character
implements Supplier<java.lang.Character> { implements Supplier<java.lang.Character> {
private int i; private int i;
@Override @Override
public java.lang.Character get() { public java.lang.Character get() {
i = (i + 1) % chars.length; i = (i + 1) % CHARS.length;
return chars[i]; return CHARS[i];
} }
public java.lang.Character get(int n) { public java.lang.Character get(int n) {
return get(); return get();
@ -76,11 +76,11 @@ public interface Count {
return result; return result;
} }
} }
public static class char_ { public static class Pchar {
private int i; private int i;
public char get() { public char get() {
i = (i + 1) % chars.length; i = (i + 1) % CHARS.length;
return chars[i]; return CHARS[i];
} }
public char get(int n) { return get(); } public char get(int n) { return get(); }
public char[] array(int sz) { public char[] array(int sz) {
@ -99,7 +99,7 @@ public interface Count {
return result; return result;
} }
} }
public static class short_ { public static class Pshort {
short s; short s;
public short get() { return s++; } public short get() { return s++; }
public short get(int n) { return get(); } public short get(int n) { return get(); }
@ -120,7 +120,7 @@ public interface Count {
return result; return result;
} }
} }
public static class int_ implements IntSupplier { public static class Pint implements IntSupplier {
int i; int i;
public int get() { return i++; } public int get() { return i++; }
public int get(int n) { return get(); } public int get(int n) { return get(); }
@ -142,7 +142,7 @@ public interface Count {
return result; return result;
} }
} }
public static class long_ implements LongSupplier { public static class Plong implements LongSupplier {
private long l; private long l;
public long get() { return l++; } public long get() { return l++; }
public long get(int n) { return get(); } public long get(int n) { return get(); }
@ -166,7 +166,7 @@ public interface Count {
return result; return result;
} }
} }
public class float_ { public class Pfloat {
private int i; private int i;
public float get() { return i++; } public float get() { return i++; }
public float get(int n) { return get(); } public float get(int n) { return get(); }
@ -189,7 +189,7 @@ public interface Count {
return result; return result;
} }
} }
public class double_ implements DoubleSupplier { public class Pdouble implements DoubleSupplier {
private int i; private int i;
public double get() { return i++; } public double get() { return i++; }
public double get(int n) { return get(); } public double get(int n) { return get(); }

View File

@ -200,33 +200,33 @@ public class HTMLColors {
show(m, m.size()); show(m, m.size());
} }
public static public static
void show(List<String> lst, int count) { void show(Collection<String> lst, int count) {
lst.stream() lst.stream()
.limit(count) .limit(count)
.forEach(System.out::println); .forEach(System.out::println);
} }
public static void show(List<String> lst) { public static void show(Collection<String> lst) {
show(lst, lst.size()); show(lst, lst.size());
} }
public static public static
void showrgb(List<Integer> lst, int count) { void showrgb(Collection<Integer> lst, int count) {
lst.stream() lst.stream()
.limit(count) .limit(count)
.forEach(n -> System.out.format("0x%06X\n", n)); .forEach(n -> System.out.format("0x%06X%n", n));
} }
public static void showrgb(List<Integer> lst) { public static void showrgb(Collection<Integer> lst) {
showrgb(lst, lst.size()); showrgb(lst, lst.size());
} }
public static public static
void show_inv(Map<String,Integer> m, int count) { void showInv(Map<String,Integer> m, int count) {
m.entrySet().stream() m.entrySet().stream()
.limit(count) .limit(count)
.forEach(e -> .forEach(e ->
System.out.format( System.out.format(
"%-20s 0x%06X\n", e.getKey(), e.getValue())); "%-20s 0x%06X\n", e.getKey(), e.getValue()));
} }
public static void show_inv(Map<String,Integer> m) { public static void showInv(Map<String,Integer> m) {
show_inv(m, m.size()); showInv(m, m.size());
} }
public static void border() { public static void border() {
System.out.println("------------------------------"); System.out.println("------------------------------");

View File

@ -9,11 +9,11 @@ import java.awt.event.*;
// Default everything except mouseClicked(): // Default everything except mouseClicked():
public interface MouseClick extends MouseListener { public interface MouseClick extends MouseListener {
@Override @Override
public default void mouseEntered(MouseEvent e) {} default void mouseEntered(MouseEvent e) {}
@Override @Override
public default void mouseExited(MouseEvent e) {} default void mouseExited(MouseEvent e) {}
@Override @Override
public default void mousePressed(MouseEvent e) {} default void mousePressed(MouseEvent e) {}
@Override @Override
public default void mouseReleased(MouseEvent e) {} default void mouseReleased(MouseEvent e) {}
} }

View File

@ -9,7 +9,7 @@ import java.util.function.*;
import static onjava.ConvertTo.*; import static onjava.ConvertTo.*;
public interface Rand { public interface Rand {
static final int MOD = 10_000; int MOD = 10_000;
public static class Boolean public static class Boolean
implements Supplier<java.lang.Boolean> { implements Supplier<java.lang.Boolean> {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@ -27,7 +27,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class boolean_ { public static class Pboolean {
public boolean[] array(int sz) { public boolean[] array(int sz) {
return primitive(new Boolean().array(sz)); return primitive(new Boolean().array(sz));
} }
@ -46,7 +46,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class byte_ { public static class Pbyte {
public byte[] array(int sz) { public byte[] array(int sz) {
return primitive(new Byte().array(sz)); return primitive(new Byte().array(sz));
} }
@ -68,7 +68,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class char_ { public static class Pchar {
public char[] array(int sz) { public char[] array(int sz) {
return primitive(new Character().array(sz)); return primitive(new Character().array(sz));
} }
@ -87,7 +87,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class short_ { public static class Pshort {
public short[] array(int sz) { public short[] array(int sz) {
return primitive(new Short().array(sz)); return primitive(new Short().array(sz));
} }
@ -101,7 +101,7 @@ public interface Rand {
} }
public java.lang.Integer get(int n) { return get(); } public java.lang.Integer get(int n) { return get(); }
public java.lang.Integer[] array(int sz) { public java.lang.Integer[] array(int sz) {
int[] primitive = new int_().array(sz); int[] primitive = new Pint().array(sz);
java.lang.Integer[] result = java.lang.Integer[] result =
new java.lang.Integer[sz]; new java.lang.Integer[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
@ -109,7 +109,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class int_ implements IntSupplier { public static class Pint implements IntSupplier {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@Override @Override
public int getAsInt() { return r.nextInt(MOD); } public int getAsInt() { return r.nextInt(MOD); }
@ -127,14 +127,14 @@ public interface Rand {
} }
public java.lang.Long get(int n) { return get(); } public java.lang.Long get(int n) { return get(); }
public java.lang.Long[] array(int sz) { public java.lang.Long[] array(int sz) {
long[] primitive = new long_().array(sz); long[] primitive = new Plong().array(sz);
java.lang.Long[] result = new java.lang.Long[sz]; java.lang.Long[] result = new java.lang.Long[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
result[i] = primitive[i]; result[i] = primitive[i];
return result; return result;
} }
} }
public static class long_ implements LongSupplier { public static class Plong implements LongSupplier {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@Override @Override
public long getAsLong() { public long getAsLong() {
@ -159,7 +159,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class float_ { public static class Pfloat {
public float[] array(int sz) { public float[] array(int sz) {
return primitive(new Float().array(sz)); return primitive(new Float().array(sz));
} }
@ -176,7 +176,7 @@ public interface Rand {
} }
public java.lang.Double get(int n) { return get(); } public java.lang.Double get(int n) { return get(); }
public java.lang.Double[] array(int sz) { public java.lang.Double[] array(int sz) {
double[] primitive = new Rand.double_().array(sz); double[] primitive = new Rand.Pdouble().array(sz);
java.lang.Double[] result = java.lang.Double[] result =
new java.lang.Double[sz]; new java.lang.Double[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
@ -184,7 +184,7 @@ public interface Rand {
return result; return result;
} }
} }
public static class double_ implements DoubleSupplier { public static class Pdouble implements DoubleSupplier {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@Override @Override
public double getAsDouble() { public double getAsDouble() {
@ -203,8 +203,8 @@ public interface Rand {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
private int strlen = 7; // Default string length private int strlen = 7; // Default string length
public String() {} public String() {}
public String(int str_length) { public String(int strLength) {
strlen = str_length; strlen = strLength;
} }
@Override @Override
public java.lang.String get() { public java.lang.String get() {

View File

@ -7,7 +7,6 @@ package onjava;
import java.util.*; import java.util.*;
import java.util.function.*; import java.util.function.*;
import java.util.stream.*; import java.util.stream.*;
import java.util.function.*;
public class Suppliers { public class Suppliers {
// Create a collection and fill it: // Create a collection and fill it:

View File

@ -5,10 +5,10 @@
package onjava; package onjava;
public class Tuple2<A, B> { public class Tuple2<A, B> {
public final A _1; public final A a1;
public final B _2; public final B a2;
public Tuple2(A a, B b) { _1 = a; _2 = b; } public Tuple2(A a, B b) { a1 = a; a2 = b; }
public String rep() { return _1 + ", " + _2; } public String rep() { return a1 + ", " + a2; }
@Override @Override
public String toString() { public String toString() {
return "(" + rep() + ")"; return "(" + rep() + ")";

View File

@ -5,13 +5,13 @@
package onjava; package onjava;
public class Tuple3<A, B, C> extends Tuple2<A, B> { public class Tuple3<A, B, C> extends Tuple2<A, B> {
public final C _3; public final C a3;
public Tuple3(A a, B b, C c) { public Tuple3(A a, B b, C c) {
super(a, b); super(a, b);
_3 = c; a3 = c;
} }
@Override @Override
public String rep() { public String rep() {
return super.rep() + ", " + _3; return super.rep() + ", " + a3;
} }
} }

View File

@ -6,13 +6,13 @@ package onjava;
public class Tuple4<A, B, C, D> public class Tuple4<A, B, C, D>
extends Tuple3<A, B, C> { extends Tuple3<A, B, C> {
public final D _4; public final D a4;
public Tuple4(A a, B b, C c, D d) { public Tuple4(A a, B b, C c, D d) {
super(a, b, c); super(a, b, c);
_4 = d; a4 = d;
} }
@Override @Override
public String rep() { public String rep() {
return super.rep() + ", " + _4; return super.rep() + ", " + a4;
} }
} }

View File

@ -6,13 +6,13 @@ package onjava;
public class Tuple5<A, B, C, D, E> public class Tuple5<A, B, C, D, E>
extends Tuple4<A, B, C, D> { extends Tuple4<A, B, C, D> {
public final E _5; public final E a5;
public Tuple5(A a, B b, C c, D d, E e) { public Tuple5(A a, B b, C c, D d, E e) {
super(a, b, c, d); super(a, b, c, d);
_5 = e; a5 = e;
} }
@Override @Override
public String rep() { public String rep() {
return super.rep() + ", " + _5; return super.rep() + ", " + a5;
} }
} }

View File

@ -19,9 +19,9 @@ public class ClassNameFinder {
int magic = data.readInt(); // 0xcafebabe int magic = data.readInt(); // 0xcafebabe
int minorVersion = data.readShort(); int minorVersion = data.readShort();
int majorVersion = data.readShort(); int majorVersion = data.readShort();
int constant_pool_count = data.readShort(); int constantPoolCount = data.readShort();
int[] constant_pool = new int[constant_pool_count]; int[] constantPool = new int[constantPoolCount];
for(int i = 1; i < constant_pool_count; i++) { for(int i = 1; i < constantPoolCount; i++) {
int tag = data.read(); int tag = data.read();
// int tableSize; // int tableSize;
switch(tag) { switch(tag) {
@ -65,13 +65,13 @@ public class ClassNameFinder {
throw new RuntimeException("Bad tag " + tag); throw new RuntimeException("Bad tag " + tag);
} }
} }
short access_flags = data.readShort(); short accessFlags = data.readShort();
String access = (access_flags & 0x0001) == 0 ? String access = (accessFlags & 0x0001) == 0 ?
"nonpublic:" : "public:"; "nonpublic:" : "public:";
int this_class = data.readShort(); int thisClass = data.readShort();
int super_class = data.readShort(); int superClass = data.readShort();
return access + classNameTable.get( return access + classNameTable.get(
offsetTable.get(this_class)).replace('/', '.'); offsetTable.get(thisClass)).replace('/', '.');
} catch(IOException | RuntimeException e) { } catch(IOException | RuntimeException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -113,21 +113,21 @@ onjava.BasicSupplier
onjava.CollectionMethodDifferences onjava.CollectionMethodDifferences
onjava.ConvertTo onjava.ConvertTo
onjava.Count$Boolean onjava.Count$Boolean
onjava.Count$boolean_ onjava.Count$Pboolean
onjava.Count$Byte onjava.Count$Byte
onjava.Count$byte_ onjava.Count$Pbyte
onjava.Count$Character onjava.Count$Character
onjava.Count$char_ onjava.Count$Pchar
onjava.Count$Double onjava.Count$Double
onjava.Count$double_ onjava.Count$Pdouble
onjava.Count$Float onjava.Count$Float
onjava.Count$float_ onjava.Count$Pfloat
onjava.Count$Integer onjava.Count$Integer
onjava.Count$int_ onjava.Count$Pint
onjava.Count$Long onjava.Count$Long
onjava.Count$long_ onjava.Count$Plong
onjava.Count$Short onjava.Count$Short
onjava.Count$short_ onjava.Count$Pshort
onjava.Count onjava.Count
onjava.CountingIntegerList onjava.CountingIntegerList
onjava.CountMap onjava.CountMap
@ -144,21 +144,21 @@ onjava.Pair
onjava.ProcessFiles$Strategy onjava.ProcessFiles$Strategy
onjava.ProcessFiles onjava.ProcessFiles
onjava.Rand$Boolean onjava.Rand$Boolean
onjava.Rand$boolean_ onjava.Rand$Pboolean
onjava.Rand$Byte onjava.Rand$Byte
onjava.Rand$byte_ onjava.Rand$Pbyte
onjava.Rand$Character onjava.Rand$Character
onjava.Rand$char_ onjava.Rand$Pchar
onjava.Rand$Double onjava.Rand$Double
onjava.Rand$double_ onjava.Rand$Pdouble
onjava.Rand$Float onjava.Rand$Float
onjava.Rand$float_ onjava.Rand$Pfloat
onjava.Rand$Integer onjava.Rand$Integer
onjava.Rand$int_ onjava.Rand$Pint
onjava.Rand$Long onjava.Rand$Long
onjava.Rand$long_ onjava.Rand$Plong
onjava.Rand$Short onjava.Rand$Short
onjava.Rand$short_ onjava.Rand$Pshort
onjava.Rand$String onjava.Rand$String
onjava.Rand onjava.Rand
onjava.Range onjava.Range

View File

@ -6,8 +6,8 @@
public class Precedence { public class Precedence {
public static void main(String[] args) { public static void main(String[] args) {
int x = 1, y = 2, z = 3; int x = 1, y = 2, z = 3;
int a = x + y - 2/2 + z; // (1) int a = x + y - 2/2 + z; // [1]
int b = x + (y - 2)/(2 + z); // (2) int b = x + (y - 2)/(2 + z); // [2]
System.out.println("a = " + a); System.out.println("a = " + a);
System.out.println("b = " + b); System.out.println("b = " + b);
} }

View File

@ -9,9 +9,9 @@ public class Underscores {
System.out.println(d); System.out.println(d);
int bin = 0b0010_1111_1010_1111_1010_1111_1010_1111; int bin = 0b0010_1111_1010_1111_1010_1111_1010_1111;
System.out.println(Integer.toBinaryString(bin)); System.out.println(Integer.toBinaryString(bin));
System.out.printf("%x\n", bin); System.out.printf("%x%n", bin);
long hex = 0x7f_e9_b7_aa; long hex = 0x7f_e9_b7_aa;
System.out.printf("%x\n", hex); System.out.printf("%x%n", hex);
} }
} }
/* Output: /* Output:

View File

@ -85,10 +85,10 @@ class ItemFactory {
static List<Supplier<Item>> items = static List<Supplier<Item>> items =
Arrays.asList( Arrays.asList(
Scissors::new, Paper::new, Rock::new); Scissors::new, Paper::new, Rock::new);
final static int sz = items.size(); static final int SZ = items.size();
private static SplittableRandom rand = new SplittableRandom(47); private static SplittableRandom rand = new SplittableRandom(47);
public static Item newItem() { public static Item newItem() {
return items.get(rand.nextInt(sz)).get(); return items.get(rand.nextInt(SZ)).get();
} }
public static Tuple2<Item,Item> newPair() { public static Tuple2<Item,Item> newPair() {
return tuple(newItem(), newItem()); return tuple(newItem(), newItem());
@ -97,8 +97,8 @@ class ItemFactory {
class Compete { class Compete {
public static Outcome match(Tuple2<Item,Item> p) { public static Outcome match(Tuple2<Item,Item> p) {
System.out.print(p._1 + " -> " + p._2 + " : "); System.out.print(p.a1 + " -> " + p.a2 + " : ");
return p._1.compete(p._2); return p.a1.compete(p.a2);
} }
} }

View File

@ -7,7 +7,6 @@ import java.util.*;
import java.util.function.*; import java.util.function.*;
import java.util.stream.*; import java.util.stream.*;
class BadShapeCreation extends RuntimeException { class BadShapeCreation extends RuntimeException {
BadShapeCreation(String msg) { BadShapeCreation(String msg) {
super(msg); super(msg);
@ -22,8 +21,7 @@ interface Shape {
abstract class ShapeFactory { abstract class ShapeFactory {
static Map<String, Supplier<Shape>> factories = static Map<String, Supplier<Shape>> factories =
new HashMap<>(); new HashMap<>();
static Shape createShape(String id) static Shape createShape(String id) {
throws BadShapeCreation {
if(!factories.containsKey(id)) { if(!factories.containsKey(id)) {
try { try {
Class.forName(id); // Load dynamically Class.forName(id); // Load dynamically
@ -38,7 +36,7 @@ abstract class ShapeFactory {
} }
} }
class Circle implements Shape { final class Circle implements Shape {
private Circle() {} private Circle() {}
public void draw() { public void draw() {
System.out.println("Circle.draw"); System.out.println("Circle.draw");
@ -51,7 +49,7 @@ class Circle implements Shape {
} }
} }
class Square implements Shape { final class Square implements Shape {
private Square() {} private Square() {}
public void draw() { public void draw() {
System.out.println("Square.draw"); System.out.println("Square.draw");

View File

@ -17,8 +17,7 @@ class BadShapeCreation extends RuntimeException {
abstract class Shape { abstract class Shape {
public abstract void draw(); public abstract void draw();
public abstract void erase(); public abstract void erase();
static Shape factory(String type) static Shape factory(String type) {
throws BadShapeCreation {
switch(type) { switch(type) {
case "Circle": return new Circle(); case "Circle": return new Circle();
case "Square": return new Square(); case "Square": return new Square();

View File

@ -65,11 +65,11 @@ class TrashFactory {
static List<Function<Double, Trash>> ttypes = static List<Function<Double, Trash>> ttypes =
Arrays.asList( Arrays.asList(
Aluminum::new, Paper::new, Glass::new); Aluminum::new, Paper::new, Glass::new);
final static int sz = ttypes.size(); static final int SZ = ttypes.size();
private static SplittableRandom rand = new SplittableRandom(47); private static SplittableRandom rand = new SplittableRandom(47);
public static Trash newTrash() { public static Trash newTrash() {
return ttypes return ttypes
.get(rand.nextInt(sz)) .get(rand.nextInt(SZ))
.apply(rand.nextDouble()); .apply(rand.nextDouble());
} }
} }

View File

@ -12,7 +12,7 @@ interface State {
abstract class StateMachine { abstract class StateMachine {
protected State currentState; protected State currentState;
abstract protected boolean changeState(); protected abstract boolean changeState();
// Template method: // Template method:
protected final void runAll() { protected final void runAll() {
while(changeState()) // Customizable while(changeState()) // Customizable
@ -55,7 +55,7 @@ class Rinse implements State {
class Washer extends StateMachine { class Washer extends StateMachine {
private int i = 0; private int i = 0;
// The state table: // The state table:
private State states[] = { private State[] states = {
new Wash(), new Spin(), new Wash(), new Spin(),
new Rinse(), new Spin(), new Rinse(), new Spin(),
}; };

View File

@ -74,10 +74,10 @@ class FlowerFactory {
static List<Supplier<Flower>> flowers = static List<Supplier<Flower>> flowers =
Arrays.asList(Gladiolus::new, Arrays.asList(Gladiolus::new,
Renuculus::new, Chrysanthemum::new); Renuculus::new, Chrysanthemum::new);
final static int sz = flowers.size(); static final int SZ = flowers.size();
private static SplittableRandom rand = new SplittableRandom(47); private static SplittableRandom rand = new SplittableRandom(47);
public static Flower newFlower() { public static Flower newFlower() {
return flowers.get(rand.nextInt(sz)).get(); return flowers.get(rand.nextInt(SZ)).get();
} }
} }

View File

@ -49,7 +49,7 @@ class OCBox extends JPanel implements Observer {
Observable notifier; Observable notifier;
int x, y; // Locations in grid int x, y; // Locations in grid
Color cColor = newColor(); Color cColor = newColor();
static final Color[] colors = { static final Color[] COLORS = {
Color.black, Color.blue, Color.cyan, Color.black, Color.blue, Color.cyan,
Color.darkGray, Color.gray, Color.green, Color.darkGray, Color.gray, Color.green,
Color.lightGray, Color.magenta, Color.lightGray, Color.magenta,
@ -57,8 +57,8 @@ class OCBox extends JPanel implements Observer {
Color.white, Color.yellow Color.white, Color.yellow
}; };
static Color newColor() { static Color newColor() {
return colors[ return COLORS[
(int)(Math.random() * colors.length) (int)(Math.random() * COLORS.length)
]; ];
} }
OCBox(int x, int y, Observable notifier) { OCBox(int x, int y, Observable notifier) {

View File

@ -13,7 +13,7 @@ public class Alias1 {
System.out.println("x: " + x.i); System.out.println("x: " + x.i);
System.out.println("y: " + y.i); System.out.println("y: " + y.i);
System.out.println("Incrementing x"); System.out.println("Incrementing x");
x.i++; // (2) x.i++; // [2]
System.out.println("x: " + x.i); System.out.println("x: " + x.i);
System.out.println("y: " + y.i); System.out.println("y: " + y.i);
} }

View File

@ -112,7 +112,7 @@ class GreenZebra extends Tomato {
public class CopyConstructor { public class CopyConstructor {
public static void ripen(Tomato t) { public static void ripen(Tomato t) {
// Use the "copy constructor": // Use the "copy constructor":
t = new Tomato(t); // (1) t = new Tomato(t); // [1]
System.out.println("In ripen, t is a " + System.out.println("In ripen, t is a " +
t.getClass().getName()); t.getClass().getName());
} }

View File

@ -9,7 +9,7 @@ public class ImmutableInteger {
public static void main(String[] args) { public static void main(String[] args) {
List<Integer> v = new ArrayList<>(); List<Integer> v = new ArrayList<>();
for(int i = 0; i < 10; i++) for(int i = 0; i < 10; i++)
v.add(new Integer(i)); v.add(Integer.valueOf(i));
// But how do you change the int // But how do you change the int
// inside the Integer? // inside the Integer?
} }

Some files were not shown because too many files have changed in this diff Show More