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
This computer source code is Copyright ©2016 MindView LLC
This computer source code is Copyright ©2016 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

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 {
AtUnitExample1 testObject = new AtUnitExample1();
@Test boolean _methodOne() {
@Test boolean tMethodOne() {
return
testObject.methodOne().equals("This is methodOne");
}
@Test boolean _methodTwo() {
@Test boolean tMethodTwo() {
return testObject.methodTwo() == 2;
}
}
/* Output:
annotations.AtUnitComposition
. _methodOne
. _methodTwo This is methodTwo
. tMethodOne
. tMethodTwo This is methodTwo
OK (2 tests)
*/

View File

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

View File

@ -14,11 +14,11 @@ public class HashSetTest {
@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();
@ -26,8 +26,8 @@ public class HashSetTest {
}
/* Output:
annotations.HashSetTest
. _remove
. _contains
. tRemove
. tContains
. initialization
OK (3 tests)
*/

View File

@ -7,6 +7,6 @@ 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 "";
}

View File

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

View File

@ -7,6 +7,6 @@ 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";
}

View File

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

View File

@ -7,5 +7,5 @@ package annotations.database;
public @interface Uniqueness {
Constraints constraints()
default @Constraints(unique = true);
default @Constraints(unique = true);
}

View File

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

View File

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

View File

@ -26,21 +26,21 @@ public class ArrayCopying {
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,12 +49,12 @@ public class ArrayCopying {
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:
@ -62,7 +62,7 @@ public class ArrayCopying {
Arrays.setAll(b2, Sup::new);
try {
Sub[] d3 =
Arrays.copyOf(b2, b2.length, Sub[].class); // (6)
Arrays.copyOf(b2, b2.length, Sub[].class); // [6]
} catch(Exception e) {
System.out.println(e);
}

View File

@ -9,8 +9,8 @@ import static onjava.ArrayShow.*;
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) {

View File

@ -8,7 +8,7 @@ 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 class ComparingArrays {
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));

View File

@ -11,7 +11,7 @@ public class ModifyExisting {
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);
}
}

View File

@ -8,14 +8,14 @@ import static onjava.ArrayShow.*;
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());
}
}

View File

@ -9,13 +9,13 @@ public class ParallelSetAll {
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();

View File

@ -14,7 +14,7 @@ public class RaggedArray {
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));

View File

@ -22,13 +22,13 @@ public class SimpleSetAll {
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 +36,11 @@ public class SimpleSetAll {
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);
}
}

View File

@ -14,7 +14,7 @@ public class StreamFromArray {
.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 class StreamFromArray {
//- 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));
}

View File

@ -8,58 +8,58 @@ 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);

View File

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

View File

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

View File

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

View File

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

View File

@ -12,7 +12,7 @@ public class Statistics {
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);

View File

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

View File

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

View File

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

View File

@ -11,7 +11,7 @@ public class TrafficLight {
Signal color = Signal.RED;
public void change() {
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:
case RED: color = Signal.GREEN;
break;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,11 +6,11 @@ import java.util.function.*;
public class BiConsumerPermutations {
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) ->
System.out.format("%d, %f\n", i, d);
System.out.format("%d, %f%n", i, d);
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) {
bicid.accept(47, 11.34);
bicdi.accept(22.45, 92);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -13,7 +13,7 @@ public class GenericsAndCovariance {
// flist.add(new Fruit());
// flist.add(new Object());
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);
}
}

View File

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

View File

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

View File

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

View File

@ -27,7 +27,7 @@ public class TupleTest {
public static void main(String[] args) {
Tuple2<String, Integer> ttsi = f();
System.out.println(ttsi);
// ttsi._1 = "there"; // Compile error: final
// ttsi.a1 = "there"; // Compile error: final
System.out.println(g());
System.out.println(h());
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 {
private Soup1() {}
public static Soup1 makeSoup() { // (1)
public static Soup1 makeSoup() { // [1]
return new Soup1();
}
}
class Soup2 {
private Soup2() {}
private static Soup2 ps1 = new Soup2(); // (2)
private static Soup2 ps1 = new Soup2(); // [2]
public static Soup2 access() {
return ps1;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,5 +11,5 @@ abstract class AbstractAccess {
void m3() {}
abstract void m3a();
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(p.process(s));
}
public static String s =
public static final String s =
"Disagreement with beliefs is by definition incorrect";
public static void main(String[] args) {
apply(new Upcase(), s);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,11 +9,11 @@ import java.awt.event.*;
// Default everything except mouseClicked():
public interface MouseClick extends MouseListener {
@Override
public default void mouseEntered(MouseEvent e) {}
default void mouseEntered(MouseEvent e) {}
@Override
public default void mouseExited(MouseEvent e) {}
default void mouseExited(MouseEvent e) {}
@Override
public default void mousePressed(MouseEvent e) {}
default void mousePressed(MouseEvent e) {}
@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.*;
public interface Rand {
static final int MOD = 10_000;
int MOD = 10_000;
public static class Boolean
implements Supplier<java.lang.Boolean> {
SplittableRandom r = new SplittableRandom(47);
@ -27,7 +27,7 @@ public interface Rand {
return result;
}
}
public static class boolean_ {
public static class Pboolean {
public boolean[] array(int sz) {
return primitive(new Boolean().array(sz));
}
@ -46,7 +46,7 @@ public interface Rand {
return result;
}
}
public static class byte_ {
public static class Pbyte {
public byte[] array(int sz) {
return primitive(new Byte().array(sz));
}
@ -68,7 +68,7 @@ public interface Rand {
return result;
}
}
public static class char_ {
public static class Pchar {
public char[] array(int sz) {
return primitive(new Character().array(sz));
}
@ -87,7 +87,7 @@ public interface Rand {
return result;
}
}
public static class short_ {
public static class Pshort {
public short[] array(int 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[] array(int sz) {
int[] primitive = new int_().array(sz);
int[] primitive = new Pint().array(sz);
java.lang.Integer[] result =
new java.lang.Integer[sz];
for(int i = 0; i < sz; i++)
@ -109,7 +109,7 @@ public interface Rand {
return result;
}
}
public static class int_ implements IntSupplier {
public static class Pint implements IntSupplier {
SplittableRandom r = new SplittableRandom(47);
@Override
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[] array(int sz) {
long[] primitive = new long_().array(sz);
long[] primitive = new Plong().array(sz);
java.lang.Long[] result = new java.lang.Long[sz];
for(int i = 0; i < sz; i++)
result[i] = primitive[i];
return result;
}
}
public static class long_ implements LongSupplier {
public static class Plong implements LongSupplier {
SplittableRandom r = new SplittableRandom(47);
@Override
public long getAsLong() {
@ -159,7 +159,7 @@ public interface Rand {
return result;
}
}
public static class float_ {
public static class Pfloat {
public float[] array(int 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[] array(int sz) {
double[] primitive = new Rand.double_().array(sz);
double[] primitive = new Rand.Pdouble().array(sz);
java.lang.Double[] result =
new java.lang.Double[sz];
for(int i = 0; i < sz; i++)
@ -184,7 +184,7 @@ public interface Rand {
return result;
}
}
public static class double_ implements DoubleSupplier {
public static class Pdouble implements DoubleSupplier {
SplittableRandom r = new SplittableRandom(47);
@Override
public double getAsDouble() {
@ -203,8 +203,8 @@ public interface Rand {
SplittableRandom r = new SplittableRandom(47);
private int strlen = 7; // Default string length
public String() {}
public String(int str_length) {
strlen = str_length;
public String(int strLength) {
strlen = strLength;
}
@Override
public java.lang.String get() {

View File

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

View File

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

View File

@ -5,13 +5,13 @@
package onjava;
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) {
super(a, b);
_3 = c;
a3 = c;
}
@Override
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>
extends Tuple3<A, B, C> {
public final D _4;
public final D a4;
public Tuple4(A a, B b, C c, D d) {
super(a, b, c);
_4 = d;
a4 = d;
}
@Override
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>
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) {
super(a, b, c, d);
_5 = e;
a5 = e;
}
@Override
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 minorVersion = data.readShort();
int majorVersion = data.readShort();
int constant_pool_count = data.readShort();
int[] constant_pool = new int[constant_pool_count];
for(int i = 1; i < constant_pool_count; i++) {
int constantPoolCount = data.readShort();
int[] constantPool = new int[constantPoolCount];
for(int i = 1; i < constantPoolCount; i++) {
int tag = data.read();
// int tableSize;
switch(tag) {
@ -65,13 +65,13 @@ public class ClassNameFinder {
throw new RuntimeException("Bad tag " + tag);
}
}
short access_flags = data.readShort();
String access = (access_flags & 0x0001) == 0 ?
short accessFlags = data.readShort();
String access = (accessFlags & 0x0001) == 0 ?
"nonpublic:" : "public:";
int this_class = data.readShort();
int super_class = data.readShort();
int thisClass = data.readShort();
int superClass = data.readShort();
return access + classNameTable.get(
offsetTable.get(this_class)).replace('/', '.');
offsetTable.get(thisClass)).replace('/', '.');
} catch(IOException | RuntimeException e) {
throw new RuntimeException(e);
}
@ -113,21 +113,21 @@ onjava.BasicSupplier
onjava.CollectionMethodDifferences
onjava.ConvertTo
onjava.Count$Boolean
onjava.Count$boolean_
onjava.Count$Pboolean
onjava.Count$Byte
onjava.Count$byte_
onjava.Count$Pbyte
onjava.Count$Character
onjava.Count$char_
onjava.Count$Pchar
onjava.Count$Double
onjava.Count$double_
onjava.Count$Pdouble
onjava.Count$Float
onjava.Count$float_
onjava.Count$Pfloat
onjava.Count$Integer
onjava.Count$int_
onjava.Count$Pint
onjava.Count$Long
onjava.Count$long_
onjava.Count$Plong
onjava.Count$Short
onjava.Count$short_
onjava.Count$Pshort
onjava.Count
onjava.CountingIntegerList
onjava.CountMap
@ -144,21 +144,21 @@ onjava.Pair
onjava.ProcessFiles$Strategy
onjava.ProcessFiles
onjava.Rand$Boolean
onjava.Rand$boolean_
onjava.Rand$Pboolean
onjava.Rand$Byte
onjava.Rand$byte_
onjava.Rand$Pbyte
onjava.Rand$Character
onjava.Rand$char_
onjava.Rand$Pchar
onjava.Rand$Double
onjava.Rand$double_
onjava.Rand$Pdouble
onjava.Rand$Float
onjava.Rand$float_
onjava.Rand$Pfloat
onjava.Rand$Integer
onjava.Rand$int_
onjava.Rand$Pint
onjava.Rand$Long
onjava.Rand$long_
onjava.Rand$Plong
onjava.Rand$Short
onjava.Rand$short_
onjava.Rand$Pshort
onjava.Rand$String
onjava.Rand
onjava.Range

View File

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

View File

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

View File

@ -85,10 +85,10 @@ class ItemFactory {
static List<Supplier<Item>> items =
Arrays.asList(
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);
public static Item newItem() {
return items.get(rand.nextInt(sz)).get();
return items.get(rand.nextInt(SZ)).get();
}
public static Tuple2<Item,Item> newPair() {
return tuple(newItem(), newItem());
@ -97,8 +97,8 @@ class ItemFactory {
class Compete {
public static Outcome match(Tuple2<Item,Item> p) {
System.out.print(p._1 + " -> " + p._2 + " : ");
return p._1.compete(p._2);
System.out.print(p.a1 + " -> " + p.a2 + " : ");
return p.a1.compete(p.a2);
}
}

View File

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

View File

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

View File

@ -65,11 +65,11 @@ class TrashFactory {
static List<Function<Double, Trash>> ttypes =
Arrays.asList(
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);
public static Trash newTrash() {
return ttypes
.get(rand.nextInt(sz))
.get(rand.nextInt(SZ))
.apply(rand.nextDouble());
}
}

View File

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

View File

@ -74,10 +74,10 @@ class FlowerFactory {
static List<Supplier<Flower>> flowers =
Arrays.asList(Gladiolus::new,
Renuculus::new, Chrysanthemum::new);
final static int sz = flowers.size();
static final int SZ = flowers.size();
private static SplittableRandom rand = new SplittableRandom(47);
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;
int x, y; // Locations in grid
Color cColor = newColor();
static final Color[] colors = {
static final Color[] COLORS = {
Color.black, Color.blue, Color.cyan,
Color.darkGray, Color.gray, Color.green,
Color.lightGray, Color.magenta,
@ -57,8 +57,8 @@ class OCBox extends JPanel implements Observer {
Color.white, Color.yellow
};
static Color newColor() {
return colors[
(int)(Math.random() * colors.length)
return COLORS[
(int)(Math.random() * COLORS.length)
];
}
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("y: " + y.i);
System.out.println("Incrementing x");
x.i++; // (2)
x.i++; // [2]
System.out.println("x: " + x.i);
System.out.println("y: " + y.i);
}

View File

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

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