From fda0e2dee608e958a9bf24795363de5cd576dc4c Mon Sep 17 00:00:00 2001 From: Bruce Eckel Date: Mon, 21 Nov 2016 12:37:57 -0800 Subject: [PATCH] Checkstyle and Findbugs changes Also changed comment callouts from // (1) to // [1] --- Copyright.txt | 8 +- ShowFindbugs.py | 10 ++ annotations/AtUnitComposition.java | 8 +- annotations/AtUnitExternalTest.java | 8 +- annotations/HashSetTest.java | 8 +- annotations/SimulatingNull.java | 4 +- annotations/StackLStringTest.java | 12 +- annotations/UseCase.java | 4 +- annotations/database/DBTable.java | 2 +- annotations/database/Uniqueness.java | 2 +- annotations/ifx/ExtractInterface.java | 2 +- arrays/AlphabeticSearch.java | 20 ++- arrays/ArrayCopying.java | 12 +- arrays/ArraySearching.java | 4 +- arrays/ComparingArrays.java | 4 +- arrays/ModifyExisting.java | 2 +- arrays/ParallelPrefix1.java | 4 +- arrays/ParallelSetAll.java | 8 +- arrays/RaggedArray.java | 2 +- arrays/SimpleSetAll.java | 8 +- arrays/StreamFromArray.java | 4 +- arrays/TestConvertTo.java | 18 +-- arrays/TestCount.java | 22 ++-- arrays/TestRand.java | 22 ++-- arrays/jmh/ParallelSort.java | 2 +- collections/CollectionSequence.java | 2 +- collections/Statistics.java | 2 +- control/BreakAndContinue.java | 6 +- control/ForInFloat.java | 2 +- control/IfElse.java | 2 +- enums/TrafficLight.java | 2 +- exceptions/CleanupIdiom.java | 6 +- exceptions/StormyInning.java | 6 +- exceptions/StreamsAreAutoCloseable.java | 4 +- .../{File_System.java => FileSystemDemo.java} | 4 +- files/Writing.java | 4 +- functional/AnonymousClosure.java | 2 +- functional/BiConsumerPermutations.java | 6 +- functional/Closure1.java | 2 +- functional/Closure2.java | 2 +- functional/Closure3.java | 2 +- functional/Closure4.java | 2 +- functional/Closure5.java | 2 +- functional/Closure6.java | 8 +- functional/Closure7.java | 2 +- functional/Closure8.java | 6 +- functional/Closure9.java | 2 +- functional/CtorReference.java | 6 +- functional/CurryingAndPartials.java | 4 +- functional/LambdaExpressions.java | 10 +- functional/MethodReferences.java | 20 +-- functional/MultiUnbound.java | 14 +-- functional/ProduceFunction.java | 4 +- functional/SharedStorage.java | 6 +- functional/Strategize.java | 12 +- functional/UnboundMethodReference.java | 4 +- generics/DogsAndRobotMethodReferences.java | 16 +-- generics/DynamicProxyMixin.java | 8 +- generics/GenericsAndCovariance.java | 2 +- generics/Holder.java | 13 +- generics/PrimitiveGenericTest.java | 2 +- generics/Store.java | 4 +- generics/TupleTest.java | 2 +- go.bat | 3 - hiding/Lunch.java | 4 +- housekeeping/ExplicitStatic.java | 6 +- housekeeping/Mugs.java | 2 +- innerclasses/BigEgg.java | 2 +- innerclasses/Parcel11.java | 2 +- innerclasses/Parcel5.java | 2 +- innerclasses/Parcel8.java | 4 +- innerclasses/TestParcel.java | 3 +- innerclasses/controller/Event.java | 4 +- interfaces/AbstractAccess.java | 2 +- interfaces/Applicator.java | 2 +- interfaces/RandomDoubles.java | 6 +- interfaces/RandomWords.java | 12 +- .../interfaceprocessor/StringProcessor.java | 12 +- onjava/ConvertTo.java | 32 ++--- onjava/Count.java | 26 ++-- onjava/HTMLColors.java | 16 +-- onjava/MouseClick.java | 8 +- onjava/Rand.java | 28 ++--- onjava/Suppliers.java | 1 - onjava/Tuple2.java | 8 +- onjava/Tuple3.java | 6 +- onjava/Tuple4.java | 6 +- onjava/Tuple5.java | 6 +- onjava/atunit/ClassNameFinder.java | 48 ++++---- operators/Precedence.java | 4 +- operators/Underscores.java | 4 +- patterns/PaperScissorsRock.java | 8 +- patterns/ShapeFactory2.java | 8 +- patterns/factory/ShapeFactory1.java | 3 +- patterns/recyclea/RecycleA.java | 4 +- patterns/state/StateMachineDemo.java | 4 +- patterns/visitor/BeeAndFlowers.java | 4 +- patterns/visualobserver/BoxObserver.java | 6 +- references/Alias1.java | 2 +- references/CopyConstructor.java | 2 +- references/ImmutableInteger.java | 2 +- reuse/SprinklerSystem.java | 2 +- streams/ForEach.java | 8 +- streams/Optionals.java | 16 +-- streams/Reduce.java | 4 +- strings/BetterRead.java | 4 +- strings/Conversion.java | 96 +++++++-------- strings/Groups.java | 2 +- strings/ReceiptBuilder.java | 12 +- strings/SimpleFormat.java | 4 +- strings/SimpleRead.java | 4 +- strings/ThreatAnalyzer.java | 2 +- strings/Turtle.java | 2 +- threads/CachedThreadPool3.java | 4 +- threads/CarBuilder.java | 4 +- threads/Futures.java | 2 +- threads/ParallelStreamPuzzle.java | 2 +- threads/ParallelStreamPuzzle2.java | 2 +- threads/Prime.java | 2 +- threads/Summing.java | 6 +- threads/Summing2.java | 6 +- threads/Summing3.java | 18 +-- threads/Summing4.java | 6 +- threads/restaurant2/RestaurantWithQueues.java | 2 +- typeinfo/ClassInitialization.java | 8 +- typeinfo/HiddenImplementation.java | 2 +- typeinfo/PetCount2.java | 2 +- typeinfo/PetCount3.java | 2 +- typeinfo/Robot.java | 2 +- typeinfo/Shapes.java | 2 +- typeinfo/pets/ForNameCreator.java | 2 +- typeinfo/pets/LiteralPetCreator.java | 12 +- typeinfo/pets/Pets.java | 8 +- .../CollectionMethods.java | 116 ++++++++++++------ understandingcollections/HTMLColorTest.java | 10 +- understandingcollections/SetOrder.java | 4 +- understandingcollections/TypesForSets.java | 23 ++-- understandingcollections/jmh/Deques.java | 1 + understandingcollections/jmh/Lists.java | 1 + understandingcollections/jmh/Maps.java | 1 + understandingcollections/jmh/Queues.java | 1 + understandingcollections/jmh/Sets.java | 1 + validating/Inverter4.java | 4 +- validating/SLF4JLevels.java | 2 +- validating/SLF4JLogging.java | 2 +- validating/StringInverter.java | 2 +- 146 files changed, 590 insertions(+), 533 deletions(-) create mode 100644 ShowFindbugs.py rename files/{File_System.java => FileSystemDemo.java} (95%) delete mode 100644 go.bat diff --git a/Copyright.txt b/Copyright.txt index 8f25e3a2..3470ee0e 100644 --- a/Copyright.txt +++ b/Copyright.txt @@ -1,5 +1,5 @@ // Copyright.txt -This computer source code is Copyright ©2016 MindView LLC +This computer source code is Copyright ©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 diff --git a/ShowFindbugs.py b/ShowFindbugs.py new file mode 100644 index 00000000..ec11f8fb --- /dev/null +++ b/ShowFindbugs.py @@ -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") diff --git a/annotations/AtUnitComposition.java b/annotations/AtUnitComposition.java index 87ecb692..90a462a3 100644 --- a/annotations/AtUnitComposition.java +++ b/annotations/AtUnitComposition.java @@ -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) */ diff --git a/annotations/AtUnitExternalTest.java b/annotations/AtUnitExternalTest.java index c7659c6f..960eca71 100644 --- a/annotations/AtUnitExternalTest.java +++ b/annotations/AtUnitExternalTest.java @@ -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) */ diff --git a/annotations/HashSetTest.java b/annotations/HashSetTest.java index 7ea3ce2c..744e214d 100644 --- a/annotations/HashSetTest.java +++ b/annotations/HashSetTest.java @@ -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) */ diff --git a/annotations/SimulatingNull.java b/annotations/SimulatingNull.java index 7b63b946..45f4637a 100644 --- a/annotations/SimulatingNull.java +++ b/annotations/SimulatingNull.java @@ -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 ""; } diff --git a/annotations/StackLStringTest.java b/annotations/StackLStringTest.java index 62e7783b..ac551aff 100644 --- a/annotations/StackLStringTest.java +++ b/annotations/StackLStringTest.java @@ -10,19 +10,19 @@ import onjava.atunit.*; import onjava.*; public class StackLStringTest extends StackL { - @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 { } /* Output: annotations.StackLStringTest - . _pop - . _top - . _push + . tPop + . tTop + . tPush OK (3 tests) */ diff --git a/annotations/UseCase.java b/annotations/UseCase.java index 7dc851a3..4d354db5 100644 --- a/annotations/UseCase.java +++ b/annotations/UseCase.java @@ -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"; } diff --git a/annotations/database/DBTable.java b/annotations/database/DBTable.java index 8cdad9b6..53b9ac44 100644 --- a/annotations/database/DBTable.java +++ b/annotations/database/DBTable.java @@ -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 ""; } diff --git a/annotations/database/Uniqueness.java b/annotations/database/Uniqueness.java index b1adc319..bbbb3f22 100644 --- a/annotations/database/Uniqueness.java +++ b/annotations/database/Uniqueness.java @@ -7,5 +7,5 @@ package annotations.database; public @interface Uniqueness { Constraints constraints() - default @Constraints(unique = true); + default @Constraints(unique = true); } diff --git a/annotations/ifx/ExtractInterface.java b/annotations/ifx/ExtractInterface.java index bef18673..8138f263 100644 --- a/annotations/ifx/ExtractInterface.java +++ b/annotations/ifx/ExtractInterface.java @@ -9,5 +9,5 @@ import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface ExtractInterface { - public String interfaceName() default "-!!-"; + String interfaceName() default "-!!-"; } diff --git a/arrays/AlphabeticSearch.java b/arrays/AlphabeticSearch.java index 1ede5c2f..28ae7a7d 100644 --- a/arrays/AlphabeticSearch.java +++ b/arrays/AlphabeticSearch.java @@ -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 */ diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java index 88b84232..14a29e57 100644 --- a/arrays/ArrayCopying.java +++ b/arrays/ArrayCopying.java @@ -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); } diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java index baf7878f..1bc07752 100644 --- a/arrays/ArraySearching.java +++ b/arrays/ArraySearching.java @@ -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) { diff --git a/arrays/ComparingArrays.java b/arrays/ComparingArrays.java index b146e3dd..ac964d06 100644 --- a/arrays/ComparingArrays.java +++ b/arrays/ComparingArrays.java @@ -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)); diff --git a/arrays/ModifyExisting.java b/arrays/ModifyExisting.java index 664c4fe6..4bf9036c 100644 --- a/arrays/ModifyExisting.java +++ b/arrays/ModifyExisting.java @@ -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); } } diff --git a/arrays/ParallelPrefix1.java b/arrays/ParallelPrefix1.java index 1e3a45b8..6ad28a87 100644 --- a/arrays/ParallelPrefix1.java +++ b/arrays/ParallelPrefix1.java @@ -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()); } } diff --git a/arrays/ParallelSetAll.java b/arrays/ParallelSetAll.java index cda4a8a0..6ef1486c 100644 --- a/arrays/ParallelSetAll.java +++ b/arrays/ParallelSetAll.java @@ -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(); diff --git a/arrays/RaggedArray.java b/arrays/RaggedArray.java index b667a2b9..70c913de 100644 --- a/arrays/RaggedArray.java +++ b/arrays/RaggedArray.java @@ -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)); diff --git a/arrays/SimpleSetAll.java b/arrays/SimpleSetAll.java index 74cccbe4..82ec6ec6 100644 --- a/arrays/SimpleSetAll.java +++ b/arrays/SimpleSetAll.java @@ -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); } } diff --git a/arrays/StreamFromArray.java b/arrays/StreamFromArray.java index b5c5176f..0f985540 100644 --- a/arrays/StreamFromArray.java +++ b/arrays/StreamFromArray.java @@ -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)); } diff --git a/arrays/TestConvertTo.java b/arrays/TestConvertTo.java index fe312688..0a0132f0 100644 --- a/arrays/TestConvertTo.java +++ b/arrays/TestConvertTo.java @@ -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); diff --git a/arrays/TestCount.java b/arrays/TestCount.java index ba02c046..e05edf22 100644 --- a/arrays/TestCount.java +++ b/arrays/TestCount.java @@ -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); } } diff --git a/arrays/TestRand.java b/arrays/TestRand.java index f9d61ef2..39df151f 100644 --- a/arrays/TestRand.java +++ b/arrays/TestRand.java @@ -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"); diff --git a/arrays/jmh/ParallelSort.java b/arrays/jmh/ParallelSort.java index 20216fa3..2533bc05 100644 --- a/arrays/jmh/ParallelSort.java +++ b/arrays/jmh/ParallelSort.java @@ -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() { diff --git a/collections/CollectionSequence.java b/collections/CollectionSequence.java index 0bfbd265..d805f5f6 100644 --- a/collections/CollectionSequence.java +++ b/collections/CollectionSequence.java @@ -12,7 +12,7 @@ extends AbstractCollection { public int size() { return pets.length; } @Override public Iterator iterator() { - return new Iterator() { // (1) + return new Iterator() { // [1] private int index = 0; @Override public boolean hasNext() { diff --git a/collections/Statistics.java b/collections/Statistics.java index c22ed96c..6b725d71 100644 --- a/collections/Statistics.java +++ b/collections/Statistics.java @@ -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); diff --git a/control/BreakAndContinue.java b/control/BreakAndContinue.java index 80a42c2f..337730cf 100644 --- a/control/BreakAndContinue.java +++ b/control/BreakAndContinue.java @@ -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 diff --git a/control/ForInFloat.java b/control/ForInFloat.java index 8b3b4591..77198d05 100644 --- a/control/ForInFloat.java +++ b/control/ForInFloat.java @@ -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) diff --git a/control/IfElse.java b/control/IfElse.java index 279f8f5b..dc9bc845 100644 --- a/control/IfElse.java +++ b/control/IfElse.java @@ -8,7 +8,7 @@ public class IfElse { static void test(int testval, int target) { if(testval > target) result = +1; - else if(testval < target) // (1) + else if(testval < target) // [1] result = -1; else result = 0; // Match diff --git a/enums/TrafficLight.java b/enums/TrafficLight.java index 4ca4813d..70d0942d 100644 --- a/enums/TrafficLight.java +++ b/enums/TrafficLight.java @@ -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; diff --git a/exceptions/CleanupIdiom.java b/exceptions/CleanupIdiom.java index 75613e48..5044d8de 100644 --- a/exceptions/CleanupIdiom.java +++ b/exceptions/CleanupIdiom.java @@ -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(); diff --git a/exceptions/StormyInning.java b/exceptions/StormyInning.java index c1db5222..dec405d8 100644 --- a/exceptions/StormyInning.java +++ b/exceptions/StormyInning.java @@ -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 diff --git a/exceptions/StreamsAreAutoCloseable.java b/exceptions/StreamsAreAutoCloseable.java index 8c69144e..f997b668 100644 --- a/exceptions/StreamsAreAutoCloseable.java +++ b/exceptions/StreamsAreAutoCloseable.java @@ -13,12 +13,12 @@ public class StreamsAreAutoCloseable { Stream in = Files.lines( Paths.get("StreamsAreAutoCloseable.java")); PrintWriter outfile = new PrintWriter( - "Results.txt"); // (1) + "Results.txt"); // [1] ) { in.skip(5) .limit(1) .map(String::toLowerCase) .forEachOrdered(outfile::println); - } // (2) + } // [2] } } diff --git a/files/File_System.java b/files/FileSystemDemo.java similarity index 95% rename from files/File_System.java rename to files/FileSystemDemo.java index b8cf516a..c1872af6 100644 --- a/files/File_System.java +++ b/files/FileSystemDemo.java @@ -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); } diff --git a/files/Writing.java b/files/Writing.java index 40a6a99a..98edb6a7 100644 --- a/files/Writing.java +++ b/files/Writing.java @@ -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: " + diff --git a/functional/AnonymousClosure.java b/functional/AnonymousClosure.java index 1a1ba346..1d19e364 100644 --- a/functional/AnonymousClosure.java +++ b/functional/AnonymousClosure.java @@ -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" diff --git a/functional/BiConsumerPermutations.java b/functional/BiConsumerPermutations.java index 3cd01a33..720dde44 100644 --- a/functional/BiConsumerPermutations.java +++ b/functional/BiConsumerPermutations.java @@ -6,11 +6,11 @@ import java.util.function.*; public class BiConsumerPermutations { static BiConsumer bicid = (i, d) -> - System.out.format("%d, %f\n", i, d); + System.out.format("%d, %f%n", i, d); static BiConsumer bicdi = (d, i) -> - System.out.format("%d, %f\n", i, d); + System.out.format("%d, %f%n", i, d); static BiConsumer 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); diff --git a/functional/Closure1.java b/functional/Closure1.java index 505009d2..01dfa172 100644 --- a/functional/Closure1.java +++ b/functional/Closure1.java @@ -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++; } } diff --git a/functional/Closure2.java b/functional/Closure2.java index cdcd9cf3..502acb8c 100644 --- a/functional/Closure2.java +++ b/functional/Closure2.java @@ -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; } diff --git a/functional/Closure3.java b/functional/Closure3.java index 25fd443f..0674153f 100644 --- a/functional/Closure3.java +++ b/functional/Closure3.java @@ -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++; diff --git a/functional/Closure4.java b/functional/Closure4.java index 96cdd3b9..dc0a22d0 100644 --- a/functional/Closure4.java +++ b/functional/Closure4.java @@ -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; } diff --git a/functional/Closure5.java b/functional/Closure5.java index 82fba731..8cef1493 100644 --- a/functional/Closure5.java +++ b/functional/Closure5.java @@ -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++; diff --git a/functional/Closure6.java b/functional/Closure6.java index 6f116d95..d9b4654c 100644 --- a/functional/Closure6.java +++ b/functional/Closure6.java @@ -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; } } diff --git a/functional/Closure7.java b/functional/Closure7.java index 4ccb0e92..a842546a 100644 --- a/functional/Closure7.java +++ b/functional/Closure7.java @@ -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; diff --git a/functional/Closure8.java b/functional/Closure8.java index 8ecb583b..0a93758f 100644 --- a/functional/Closure8.java +++ b/functional/Closure8.java @@ -6,7 +6,7 @@ import java.util.*; import java.util.function.*; public class Closure8 { - Supplier> make_fun() { + Supplier> makeFun() { final List 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 - 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); diff --git a/functional/Closure9.java b/functional/Closure9.java index 6ed827f8..a9e173e2 100644 --- a/functional/Closure9.java +++ b/functional/Closure9.java @@ -7,7 +7,7 @@ import java.util.*; import java.util.function.*; public class Closure9 { - Supplier> make_fun() { + Supplier> makeFun() { List ai = new ArrayList<>(); ai = new ArrayList<>(); // Reassignment return () -> ai; diff --git a/functional/CtorReference.java b/functional/CtorReference.java index fcf8ea75..51bff8dd 100644 --- a/functional/CtorReference.java +++ b/functional/CtorReference.java @@ -25,9 +25,9 @@ interface Make2Args { public class CtorReference { public static void main(String[] args) { - MakeNoArgs mna = Dog::new; // (1) - Make1Arg m1a = Dog::new; // (2) - Make2Args m2a = Dog::new; // (3) + MakeNoArgs mna = Dog::new; // [1] + Make1Arg m1a = Dog::new; // [2] + Make2Args m2a = Dog::new; // [3] Dog dn = mna.make(); Dog d1 = m1a.make("Comet"); diff --git a/functional/CurryingAndPartials.java b/functional/CurryingAndPartials.java index aa5f7457..c4784559 100644 --- a/functional/CurryingAndPartials.java +++ b/functional/CurryingAndPartials.java @@ -12,12 +12,12 @@ public class CurryingAndPartials { public static void main(String[] args) { // Curried function: Function> sum = - a -> b -> a + b; // (1) + a -> b -> a + b; // [1] System.out.println(uncurried("Hi ", "Ho")); Function - hi = sum.apply("Hi "); // (2) + hi = sum.apply("Hi "); // [2] System.out.println(hi.apply("Ho")); // Partial application: diff --git a/functional/LambdaExpressions.java b/functional/LambdaExpressions.java index adb3f5da..50dd7222 100644 --- a/functional/LambdaExpressions.java +++ b/functional/LambdaExpressions.java @@ -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()"; }; diff --git a/functional/MethodReferences.java b/functional/MethodReferences.java index 5becd371..5911f317 100644 --- a/functional/MethodReferences.java +++ b/functional/MethodReferences.java @@ -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!"); } } diff --git a/functional/MultiUnbound.java b/functional/MultiUnbound.java index fa2ada8f..aed17795 100644 --- a/functional/MultiUnbound.java +++ b/functional/MultiUnbound.java @@ -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'); } } diff --git a/functional/ProduceFunction.java b/functional/ProduceFunction.java index 5b2ce9ad..bb573532 100644 --- a/functional/ProduceFunction.java +++ b/functional/ProduceFunction.java @@ -5,11 +5,11 @@ import java.util.function.*; interface -FuncSS extends Function {} // (1) +FuncSS extends Function {} // [1] public class ProduceFunction { static FuncSS produce() { - return s -> s.toLowerCase(); // (2) + return s -> s.toLowerCase(); // [2] } public static void main(String[] args) { FuncSS f = produce(); diff --git a/functional/SharedStorage.java b/functional/SharedStorage.java index 789255c6..be005eec 100644 --- a/functional/SharedStorage.java +++ b/functional/SharedStorage.java @@ -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()); diff --git a/functional/Strategize.java b/functional/Strategize.java index 92b83a44..cc87e047 100644 --- a/functional/Strategize.java +++ b/functional/Strategize.java @@ -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] } } } diff --git a/functional/UnboundMethodReference.java b/functional/UnboundMethodReference.java index d0240dec..fc28af61 100644 --- a/functional/UnboundMethodReference.java +++ b/functional/UnboundMethodReference.java @@ -18,10 +18,10 @@ interface TransformX { public class UnboundMethodReference { public static void main(String[] args) { - // MakeString ms = X::f; // (1) + // MakeString ms = X::f; // [1] TransformX sp = X::f; X x = new X(); - System.out.println(sp.transform(x)); // (2) + System.out.println(sp.transform(x)); // [2] System.out.println(x.f()); // Same effect } } diff --git a/generics/DogsAndRobotMethodReferences.java b/generics/DogsAndRobotMethodReferences.java index cae8c018..4a7c346c 100644 --- a/generics/DogsAndRobotMethodReferences.java +++ b/generics/DogsAndRobotMethodReferences.java @@ -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

void perform(P performer, Consumer

action1, Consumer

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); } } diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index 2c886f92..250aec23 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -13,12 +13,12 @@ class MixinProxy implements InvocationHandler { public MixinProxy(Tuple2>... pairs) { delegatesByMethod = new HashMap<>(); for(Tuple2> 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)); } diff --git a/generics/GenericsAndCovariance.java b/generics/GenericsAndCovariance.java index b96a43a6..4dca050a 100644 --- a/generics/GenericsAndCovariance.java +++ b/generics/GenericsAndCovariance.java @@ -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); } } diff --git a/generics/Holder.java b/generics/Holder.java index 5937a813..f85d2ebc 100644 --- a/generics/Holder.java +++ b/generics/Holder.java @@ -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 { private T value; @@ -10,8 +11,14 @@ public class Holder { 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 = new Holder<>(new Apple()); @@ -32,5 +39,5 @@ public class Holder { /* Output: java.lang.ClassCastException: Apple cannot be cast to Orange -true +false */ diff --git a/generics/PrimitiveGenericTest.java b/generics/PrimitiveGenericTest.java index 934c1ba3..cfd211a7 100644 --- a/generics/PrimitiveGenericTest.java +++ b/generics/PrimitiveGenericTest.java @@ -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)); } } diff --git a/generics/Store.java b/generics/Store.java index ec447263..0847c018 100644 --- a/generics/Store.java +++ b/generics/Store.java @@ -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()); diff --git a/generics/TupleTest.java b/generics/TupleTest.java index f85e5125..52901fd4 100644 --- a/generics/TupleTest.java +++ b/generics/TupleTest.java @@ -27,7 +27,7 @@ public class TupleTest { public static void main(String[] args) { Tuple2 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()); diff --git a/go.bat b/go.bat deleted file mode 100644 index 957d931c..00000000 --- a/go.bat +++ /dev/null @@ -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 diff --git a/hiding/Lunch.java b/hiding/Lunch.java index a0b9e789..12faa00d 100644 --- a/hiding/Lunch.java +++ b/hiding/Lunch.java @@ -7,14 +7,14 @@ class Soup1 { private Soup1() {} - public static Soup1 makeSoup() { // (1) + public static Soup1 makeSoup() { // [1] return new Soup1(); } } class Soup2 { private Soup2() {} - private static Soup2 ps1 = new Soup2(); // (2) + private static Soup2 ps1 = new Soup2(); // [2] public static Soup2 access() { return ps1; } diff --git a/housekeeping/ExplicitStatic.java b/housekeeping/ExplicitStatic.java index 8e86b003..f0ec5c0a 100644 --- a/housekeeping/ExplicitStatic.java +++ b/housekeeping/ExplicitStatic.java @@ -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() diff --git a/housekeeping/Mugs.java b/housekeeping/Mugs.java index 373471a2..a99f0d1d 100644 --- a/housekeeping/Mugs.java +++ b/housekeeping/Mugs.java @@ -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"); diff --git a/innerclasses/BigEgg.java b/innerclasses/BigEgg.java index b55ac35f..e4faff59 100644 --- a/innerclasses/BigEgg.java +++ b/innerclasses/BigEgg.java @@ -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; diff --git a/innerclasses/Parcel11.java b/innerclasses/Parcel11.java index d9f6f46a..994864b9 100644 --- a/innerclasses/Parcel11.java +++ b/innerclasses/Parcel11.java @@ -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) { diff --git a/innerclasses/Parcel5.java b/innerclasses/Parcel5.java index 3b469419..4b88c4f8 100644 --- a/innerclasses/Parcel5.java +++ b/innerclasses/Parcel5.java @@ -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; diff --git a/innerclasses/Parcel8.java b/innerclasses/Parcel8.java index c8385b4e..b126b103 100644 --- a/innerclasses/Parcel8.java +++ b/innerclasses/Parcel8.java @@ -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(); diff --git a/innerclasses/TestParcel.java b/innerclasses/TestParcel.java index 970b2c3a..2f6152aa 100644 --- a/innerclasses/TestParcel.java +++ b/innerclasses/TestParcel.java @@ -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; diff --git a/innerclasses/controller/Event.java b/innerclasses/controller/Event.java index afdb4510..662f0e9d 100644 --- a/innerclasses/controller/Event.java +++ b/innerclasses/controller/Event.java @@ -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 diff --git a/interfaces/AbstractAccess.java b/interfaces/AbstractAccess.java index 8c72c2c5..b7a22bd8 100644 --- a/interfaces/AbstractAccess.java +++ b/interfaces/AbstractAccess.java @@ -11,5 +11,5 @@ abstract class AbstractAccess { void m3() {} abstract void m3a(); public void m4() {} - abstract public void m4a(); + public abstract void m4a(); } diff --git a/interfaces/Applicator.java b/interfaces/Applicator.java index 3e992f15..6cca24c9 100644 --- a/interfaces/Applicator.java +++ b/interfaces/Applicator.java @@ -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); diff --git a/interfaces/RandomDoubles.java b/interfaces/RandomDoubles.java index 19619b4c..2c4e8c86 100644 --- a/interfaces/RandomDoubles.java +++ b/interfaces/RandomDoubles.java @@ -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() + " "); diff --git a/interfaces/RandomWords.java b/interfaces/RandomWords.java index f744fd9e..95eefcd4 100644 --- a/interfaces/RandomWords.java +++ b/interfaces/RandomWords.java @@ -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 diff --git a/interfaces/interfaceprocessor/StringProcessor.java b/interfaces/interfaceprocessor/StringProcessor.java index 3078c315..88ad20ee 100644 --- a/interfaces/interfaceprocessor/StringProcessor.java +++ b/interfaces/interfaceprocessor/StringProcessor.java @@ -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); } } diff --git a/onjava/ConvertTo.java b/onjava/ConvertTo.java index 015d636b..985b7f30 100644 --- a/onjava/ConvertTo.java +++ b/onjava/ConvertTo.java @@ -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]; diff --git a/onjava/Count.java b/onjava/Count.java index 0a5f717e..294be06d 100644 --- a/onjava/Count.java +++ b/onjava/Count.java @@ -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 { 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(); } diff --git a/onjava/HTMLColors.java b/onjava/HTMLColors.java index 7ba46d59..3d570a09 100644 --- a/onjava/HTMLColors.java +++ b/onjava/HTMLColors.java @@ -200,33 +200,33 @@ public class HTMLColors { show(m, m.size()); } public static - void show(List lst, int count) { + void show(Collection lst, int count) { lst.stream() .limit(count) .forEach(System.out::println); } - public static void show(List lst) { + public static void show(Collection lst) { show(lst, lst.size()); } public static - void showrgb(List lst, int count) { + void showrgb(Collection 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 lst) { + public static void showrgb(Collection lst) { showrgb(lst, lst.size()); } public static - void show_inv(Map m, int count) { + void showInv(Map 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 m) { - show_inv(m, m.size()); + public static void showInv(Map m) { + showInv(m, m.size()); } public static void border() { System.out.println("------------------------------"); diff --git a/onjava/MouseClick.java b/onjava/MouseClick.java index 39259efc..cf8871b3 100644 --- a/onjava/MouseClick.java +++ b/onjava/MouseClick.java @@ -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) {} } diff --git a/onjava/Rand.java b/onjava/Rand.java index 10dc8b21..7af72706 100644 --- a/onjava/Rand.java +++ b/onjava/Rand.java @@ -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 { 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() { diff --git a/onjava/Suppliers.java b/onjava/Suppliers.java index a7c52eb7..e1a724f3 100644 --- a/onjava/Suppliers.java +++ b/onjava/Suppliers.java @@ -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: diff --git a/onjava/Tuple2.java b/onjava/Tuple2.java index ec7f86d2..b7642aca 100644 --- a/onjava/Tuple2.java +++ b/onjava/Tuple2.java @@ -5,10 +5,10 @@ package onjava; public class Tuple2 { - 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() + ")"; diff --git a/onjava/Tuple3.java b/onjava/Tuple3.java index aeb3c4c3..971d380d 100644 --- a/onjava/Tuple3.java +++ b/onjava/Tuple3.java @@ -5,13 +5,13 @@ package onjava; public class Tuple3 extends Tuple2 { - 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; } } diff --git a/onjava/Tuple4.java b/onjava/Tuple4.java index 1adb02fd..9ad6c922 100644 --- a/onjava/Tuple4.java +++ b/onjava/Tuple4.java @@ -6,13 +6,13 @@ package onjava; public class Tuple4 extends Tuple3 { - 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; } } diff --git a/onjava/Tuple5.java b/onjava/Tuple5.java index b10ebfec..e346864d 100644 --- a/onjava/Tuple5.java +++ b/onjava/Tuple5.java @@ -6,13 +6,13 @@ package onjava; public class Tuple5 extends Tuple4 { - 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; } } diff --git a/onjava/atunit/ClassNameFinder.java b/onjava/atunit/ClassNameFinder.java index 8c0eff78..13592086 100644 --- a/onjava/atunit/ClassNameFinder.java +++ b/onjava/atunit/ClassNameFinder.java @@ -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 diff --git a/operators/Precedence.java b/operators/Precedence.java index b77adfe5..15081797 100644 --- a/operators/Precedence.java +++ b/operators/Precedence.java @@ -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); } diff --git a/operators/Underscores.java b/operators/Underscores.java index de9a0c1e..ccd56425 100644 --- a/operators/Underscores.java +++ b/operators/Underscores.java @@ -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: diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java index 247641b5..8ea0bcf3 100644 --- a/patterns/PaperScissorsRock.java +++ b/patterns/PaperScissorsRock.java @@ -85,10 +85,10 @@ class ItemFactory { static List> 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 newPair() { return tuple(newItem(), newItem()); @@ -97,8 +97,8 @@ class ItemFactory { class Compete { public static Outcome match(Tuple2 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); } } diff --git a/patterns/ShapeFactory2.java b/patterns/ShapeFactory2.java index 4a66eb0b..3a82b47d 100644 --- a/patterns/ShapeFactory2.java +++ b/patterns/ShapeFactory2.java @@ -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> 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"); diff --git a/patterns/factory/ShapeFactory1.java b/patterns/factory/ShapeFactory1.java index a2c75572..147d4c4d 100644 --- a/patterns/factory/ShapeFactory1.java +++ b/patterns/factory/ShapeFactory1.java @@ -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(); diff --git a/patterns/recyclea/RecycleA.java b/patterns/recyclea/RecycleA.java index 0f09b392..02e35008 100644 --- a/patterns/recyclea/RecycleA.java +++ b/patterns/recyclea/RecycleA.java @@ -65,11 +65,11 @@ class TrashFactory { static List> 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()); } } diff --git a/patterns/state/StateMachineDemo.java b/patterns/state/StateMachineDemo.java index d184a132..51a5f66f 100644 --- a/patterns/state/StateMachineDemo.java +++ b/patterns/state/StateMachineDemo.java @@ -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(), }; diff --git a/patterns/visitor/BeeAndFlowers.java b/patterns/visitor/BeeAndFlowers.java index b94eb94b..d5fbb11e 100644 --- a/patterns/visitor/BeeAndFlowers.java +++ b/patterns/visitor/BeeAndFlowers.java @@ -74,10 +74,10 @@ class FlowerFactory { static List> 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(); } } diff --git a/patterns/visualobserver/BoxObserver.java b/patterns/visualobserver/BoxObserver.java index 68068731..d0cb06a6 100644 --- a/patterns/visualobserver/BoxObserver.java +++ b/patterns/visualobserver/BoxObserver.java @@ -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) { diff --git a/references/Alias1.java b/references/Alias1.java index 0e0e3c8b..02051d3f 100644 --- a/references/Alias1.java +++ b/references/Alias1.java @@ -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); } diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java index f8d3ce61..4c100559 100644 --- a/references/CopyConstructor.java +++ b/references/CopyConstructor.java @@ -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()); } diff --git a/references/ImmutableInteger.java b/references/ImmutableInteger.java index 516bab0a..ab475a8b 100644 --- a/references/ImmutableInteger.java +++ b/references/ImmutableInteger.java @@ -9,7 +9,7 @@ public class ImmutableInteger { public static void main(String[] args) { List v = new ArrayList<>(); for(int i = 0; i < 10; i++) - v.add(new Integer(i)); + v.add(Integer.valueOf(i)); // But how do you change the int // inside the Integer? } diff --git a/reuse/SprinklerSystem.java b/reuse/SprinklerSystem.java index 79cd4c0b..4931e593 100644 --- a/reuse/SprinklerSystem.java +++ b/reuse/SprinklerSystem.java @@ -27,7 +27,7 @@ public class SprinklerSystem { "valve3 = " + valve3 + " " + "valve4 = " + valve4 + "\n" + "i = " + i + " " + "f = " + f + " " + - "source = " + source; // (1) + "source = " + source; // [1] } public static void main(String[] args) { SprinklerSystem sprinklers = new SprinklerSystem(); diff --git a/streams/ForEach.java b/streams/ForEach.java index ad2edd95..64364fe0 100644 --- a/streams/ForEach.java +++ b/streams/ForEach.java @@ -7,16 +7,16 @@ import java.util.stream.*; import static streams.RandInts.*; public class ForEach { - final static int sz = 14; + static final int SZ = 14; public static void main(String[] args) { - rands().limit(sz) + rands().limit(SZ) .forEach(n -> System.out.format("%d ", n)); System.out.println(); - rands().limit(sz) + rands().limit(SZ) .parallel() .forEach(n -> System.out.format("%d ", n)); System.out.println(); - rands().limit(sz) + rands().limit(SZ) .parallel() .forEachOrdered(n -> System.out.format("%d ", n)); } diff --git a/streams/Optionals.java b/streams/Optionals.java index 774df4b5..a54e9d3e 100644 --- a/streams/Optionals.java +++ b/streams/Optionals.java @@ -13,17 +13,17 @@ public class Optionals { else System.out.println("Nothing inside!"); } - static void if_present(Optional optString) { + static void ifPresent(Optional optString) { optString.ifPresent(System.out::println); } - static void or_else(Optional optString) { + static void orElse(Optional optString) { System.out.println(optString.orElse("Nada")); } - static void or_else_get(Optional optString) { + static void orElseGet(Optional optString) { System.out.println( optString.orElseGet(() -> "Generated")); } - static void or_else_throw(Optional optString) { + static void orElseThrow(Optional optString) { try { System.out.println(optString.orElseThrow( () -> new Exception("Supplied"))); @@ -39,10 +39,10 @@ public class Optionals { } public static void main(String[] args) { test("basics", Optionals::basics); - test("ifPresent", Optionals::if_present); - test("orElse", Optionals::or_else); - test("orElseGet", Optionals::or_else_get); - test("orElseThrow", Optionals::or_else_throw); + test("ifPresent", Optionals::ifPresent); + test("orElse", Optionals::orElse); + test("orElseGet", Optionals::orElseGet); + test("orElseThrow", Optionals::orElseThrow); } } /* Output: diff --git a/streams/Reduce.java b/streams/Reduce.java index 72237089..c02ba496 100644 --- a/streams/Reduce.java +++ b/streams/Reduce.java @@ -14,9 +14,9 @@ class Frobnitz { } // Generator: static Random rand = new Random(47); - static final int bound = 100; + static final int BOUND = 100; static Frobnitz supply() { - return new Frobnitz(rand.nextInt(bound)); + return new Frobnitz(rand.nextInt(BOUND)); } } diff --git a/strings/BetterRead.java b/strings/BetterRead.java index 0bc2e490..7c7ec9b1 100644 --- a/strings/BetterRead.java +++ b/strings/BetterRead.java @@ -17,8 +17,8 @@ public class BetterRead { double favorite = stdin.nextDouble(); System.out.println(age); System.out.println(favorite); - System.out.format("Hi %s.\n", name); - System.out.format("In 5 years you will be %d.\n", + System.out.format("Hi %s.%n", name); + System.out.format("In 5 years you will be %d.%n", age + 5); System.out.format("My favorite double is %f.", favorite / 2); diff --git a/strings/Conversion.java b/strings/Conversion.java index 425e63c9..c708b5f4 100644 --- a/strings/Conversion.java +++ b/strings/Conversion.java @@ -11,70 +11,70 @@ public class Conversion { char u = 'a'; System.out.println("u = 'a'"); - f.format("s: %s\n", u); - // f.format("d: %d\n", u); - f.format("c: %c\n", u); - f.format("b: %b\n", u); - // f.format("f: %f\n", u); - // f.format("e: %e\n", u); - // f.format("x: %x\n", u); - f.format("h: %h\n", u); + f.format("s: %s%n", u); + // f.format("d: %d%n", u); + f.format("c: %c%n", u); + f.format("b: %b%n", u); + // f.format("f: %f%n", u); + // f.format("e: %e%n", u); + // f.format("x: %x%n", u); + f.format("h: %h%n", u); int v = 121; System.out.println("v = 121"); - f.format("d: %d\n", v); - f.format("c: %c\n", v); - f.format("b: %b\n", v); - f.format("s: %s\n", v); - // f.format("f: %f\n", v); - // f.format("e: %e\n", v); - f.format("x: %x\n", v); - f.format("h: %h\n", v); + f.format("d: %d%n", v); + f.format("c: %c%n", v); + f.format("b: %b%n", v); + f.format("s: %s%n", v); + // f.format("f: %f%n", v); + // f.format("e: %e%n", v); + f.format("x: %x%n", v); + f.format("h: %h%n", v); BigInteger w = new BigInteger("50000000000000"); System.out.println( "w = new BigInteger(\"50000000000000\")"); - f.format("d: %d\n", w); - // f.format("c: %c\n", w); - f.format("b: %b\n", w); - f.format("s: %s\n", w); - // f.format("f: %f\n", w); - // f.format("e: %e\n", w); - f.format("x: %x\n", w); - f.format("h: %h\n", w); + f.format("d: %d%n", w); + // f.format("c: %c%n", w); + f.format("b: %b%n", w); + f.format("s: %s%n", w); + // f.format("f: %f%n", w); + // f.format("e: %e%n", w); + f.format("x: %x%n", w); + f.format("h: %h%n", w); double x = 179.543; System.out.println("x = 179.543"); - // f.format("d: %d\n", x); - // f.format("c: %c\n", x); - f.format("b: %b\n", x); - f.format("s: %s\n", x); - f.format("f: %f\n", x); - f.format("e: %e\n", x); - // f.format("x: %x\n", x); - f.format("h: %h\n", x); + // f.format("d: %d%n", x); + // f.format("c: %c%n", x); + f.format("b: %b%n", x); + f.format("s: %s%n", x); + f.format("f: %f%n", x); + f.format("e: %e%n", x); + // f.format("x: %x%n", x); + f.format("h: %h%n", x); Conversion y = new Conversion(); System.out.println("y = new Conversion()"); - // f.format("d: %d\n", y); - // f.format("c: %c\n", y); - f.format("b: %b\n", y); - f.format("s: %s\n", y); - // f.format("f: %f\n", y); - // f.format("e: %e\n", y); - // f.format("x: %x\n", y); - f.format("h: %h\n", y); + // f.format("d: %d%n", y); + // f.format("c: %c%n", y); + f.format("b: %b%n", y); + f.format("s: %s%n", y); + // f.format("f: %f%n", y); + // f.format("e: %e%n", y); + // f.format("x: %x%n", y); + f.format("h: %h%n", y); boolean z = false; System.out.println("z = false"); - // f.format("d: %d\n", z); - // f.format("c: %c\n", z); - f.format("b: %b\n", z); - f.format("s: %s\n", z); - // f.format("f: %f\n", z); - // f.format("e: %e\n", z); - // f.format("x: %x\n", z); - f.format("h: %h\n", z); + // f.format("d: %d%n", z); + // f.format("c: %c%n", z); + f.format("b: %b%n", z); + f.format("s: %s%n", z); + // f.format("f: %f%n", z); + // f.format("e: %e%n", z); + // f.format("x: %x%n", z); + f.format("h: %h%n", z); } } /* Output: diff --git a/strings/Groups.java b/strings/Groups.java index 0de006c1..6eda4978 100644 --- a/strings/Groups.java +++ b/strings/Groups.java @@ -5,7 +5,7 @@ import java.util.regex.*; public class Groups { - static public final String POEM = + public static final String POEM = "Twas brillig, and the slithy toves\n" + "Did gyre and gimble in the wabe.\n" + "All mimsy were the borogoves,\n" + diff --git a/strings/ReceiptBuilder.java b/strings/ReceiptBuilder.java index 23823463..50c3955d 100644 --- a/strings/ReceiptBuilder.java +++ b/strings/ReceiptBuilder.java @@ -9,17 +9,17 @@ public class ReceiptBuilder { private Formatter f = new Formatter(new StringBuilder()); public ReceiptBuilder() { - f.format("%-15s %5s %10s\n", "Item", "Qty", "Price"); - f.format("%-15s %5s %10s\n", "----", "---", "-----"); + f.format("%-15s %5s %10s%n", "Item", "Qty", "Price"); + f.format("%-15s %5s %10s%n", "----", "---", "-----"); } public void add(String name, int qty, double price) { - f.format("%-15.15s %5d %10.2f\n", name, qty, price); + f.format("%-15.15s %5d %10.2f%n", name, qty, price); total += price * qty; } public String build() { - f.format("%-15s %5s %10.2f\n", "Tax", "", total*0.06); - f.format("%-15s %5s %10s\n", "", "", "-----"); - f.format("%-15s %5s %10.2f\n", "Total", "", + f.format("%-15s %5s %10.2f%n", "Tax", "", total*0.06); + f.format("%-15s %5s %10s%n", "", "", "-----"); + f.format("%-15s %5s %10.2f%n", "Total", "", total * 1.06); return f.toString(); } diff --git a/strings/SimpleFormat.java b/strings/SimpleFormat.java index 28d0ef4e..cad6b84c 100644 --- a/strings/SimpleFormat.java +++ b/strings/SimpleFormat.java @@ -10,9 +10,9 @@ public class SimpleFormat { // The old way: System.out.println("Row 1: [" + x + " " + y + "]"); // The new way: - System.out.format("Row 1: [%d %f]\n", x, y); + System.out.format("Row 1: [%d %f]%n", x, y); // or - System.out.printf("Row 1: [%d %f]\n", x, y); + System.out.printf("Row 1: [%d %f]%n", x, y); } } /* Output: diff --git a/strings/SimpleRead.java b/strings/SimpleRead.java index 8fc5fd63..0dce6612 100644 --- a/strings/SimpleRead.java +++ b/strings/SimpleRead.java @@ -20,8 +20,8 @@ public class SimpleRead { String[] numArray = numbers.split(" "); int age = Integer.parseInt(numArray[0]); double favorite = Double.parseDouble(numArray[1]); - System.out.format("Hi %s.\n", name); - System.out.format("In 5 years you will be %d.\n", + System.out.format("Hi %s.%n", name); + System.out.format("In 5 years you will be %d.%n", age + 5); System.out.format("My favorite double is %f.", favorite / 2); diff --git a/strings/ThreatAnalyzer.java b/strings/ThreatAnalyzer.java index c25f64e8..920f62b0 100644 --- a/strings/ThreatAnalyzer.java +++ b/strings/ThreatAnalyzer.java @@ -23,7 +23,7 @@ public class ThreatAnalyzer { String ip = match.group(1); String date = match.group(2); System.out.format( - "Threat on %s from %s\n", date,ip); + "Threat on %s from %s%n", date,ip); } } } diff --git a/strings/Turtle.java b/strings/Turtle.java index a7a67b27..a499a7aa 100644 --- a/strings/Turtle.java +++ b/strings/Turtle.java @@ -13,7 +13,7 @@ public class Turtle { this.f = f; } public void move(int x, int y) { - f.format("%s The Turtle is at (%d,%d)\n", name, x, y); + f.format("%s The Turtle is at (%d,%d)%n", name, x, y); } public static void main(String[] args) { PrintStream outAlias = System.out; diff --git a/threads/CachedThreadPool3.java b/threads/CachedThreadPool3.java index 98bf0f1c..967fd16c 100644 --- a/threads/CachedThreadPool3.java +++ b/threads/CachedThreadPool3.java @@ -8,7 +8,7 @@ import java.util.stream.*; public class CachedThreadPool3 { public static Integer - extract_result(Future f) { + extractResult(Future f) { try { return f.get(); } catch(Exception e) { @@ -26,7 +26,7 @@ public class CachedThreadPool3 { List> futures = exec.invokeAll(tasks); Integer sum = futures.stream() - .map(CachedThreadPool3::extract_result) + .map(CachedThreadPool3::extractResult) .reduce(0, Integer::sum); System.out.println("sum = " + sum); exec.shutdown(); diff --git a/threads/CarBuilder.java b/threads/CarBuilder.java index 8cb9a263..a5624138 100644 --- a/threads/CarBuilder.java +++ b/threads/CarBuilder.java @@ -107,8 +107,8 @@ class Reporter implements Runnable { abstract class Robot implements Runnable { private RobotPool pool; - public Robot(RobotPool p) { pool = p; } protected Assembler assembler; + public Robot(RobotPool p) { pool = p; } public Robot assignAssembler(Assembler assembler) { this.assembler = assembler; return this; @@ -119,7 +119,7 @@ abstract class Robot implements Runnable { notifyAll(); } // The part of run() that's different for each robot: - abstract protected void performService(); + protected abstract void performService(); public void run() { try { powerDown(); // Wait until needed diff --git a/threads/Futures.java b/threads/Futures.java index 1fcf5b7d..7af93964 100644 --- a/threads/Futures.java +++ b/threads/Futures.java @@ -13,7 +13,7 @@ public class Futures { Executors.newSingleThreadExecutor(); Future f = exec.submit(new CountingTask(99)); - System.out.println(f.get()); //(1) + System.out.println(f.get()); // [1] exec.shutdown(); } } diff --git a/threads/ParallelStreamPuzzle.java b/threads/ParallelStreamPuzzle.java index 8798c649..9855af2b 100644 --- a/threads/ParallelStreamPuzzle.java +++ b/threads/ParallelStreamPuzzle.java @@ -18,7 +18,7 @@ public class ParallelStreamPuzzle { List x = Stream.generate(new IntGenerator()) .limit(10) - .parallel() // (1) + .parallel() // [1] .collect(Collectors.toList()); System.out.println(x); } diff --git a/threads/ParallelStreamPuzzle2.java b/threads/ParallelStreamPuzzle2.java index 7ced862b..0dab06ca 100644 --- a/threads/ParallelStreamPuzzle2.java +++ b/threads/ParallelStreamPuzzle2.java @@ -14,7 +14,7 @@ public class ParallelStreamPuzzle2 { static class IntGenerator implements Supplier { private int current = 0; - public synchronized Integer get() { // (1) + public synchronized Integer get() { // [1] trace.add(current + ": " + Thread.currentThread().getName()); return current++; diff --git a/threads/Prime.java b/threads/Prime.java index deed762e..9f4e8841 100644 --- a/threads/Prime.java +++ b/threads/Prime.java @@ -20,7 +20,7 @@ public class Prime { long start = System.currentTimeMillis(); List primes = iterate(2, i -> i + 1) - .parallel() //(1) + .parallel() // [1] .filter(Prime::isPrime) .limit(COUNT) .mapToObj(Long::toString) diff --git a/threads/Summing.java b/threads/Summing.java index 34b4de18..3086be1f 100644 --- a/threads/Summing.java +++ b/threads/Summing.java @@ -16,13 +16,13 @@ public class Summing { if(result == checkValue) System.out.println(duration + "ms"); else - System.out.format("result: %d\ncheckValue: %d\n", + System.out.format("result: %d%ncheckValue: %d%n", result, checkValue); x = result; // Prevent optimization } - public static int SZ = 100_000_000; + public static final int SZ = 100_000_000; // This even works: - // public static int SZ = 1_000_000_000; + // public static final int SZ = 1_000_000_000; // Gauss's formula: public static final long CHECK = (long)SZ * ((long)SZ + 1)/2; diff --git a/threads/Summing2.java b/threads/Summing2.java index 3e5f28e3..ccc0f1ba 100644 --- a/threads/Summing2.java +++ b/threads/Summing2.java @@ -7,14 +7,14 @@ import java.util.*; public class Summing2 { static long basicSum(long[] ia) { long sum = 0; - final int sz = ia.length; - for(int i = 0; i < sz; i++) + int size = ia.length; + for(int i = 0; i < size; i++) sum += ia[i]; return sum; } // Approximate largest value of SZ before // running out of memory on my machine: - public static int SZ = 20_000_000; + public static final int SZ = 20_000_000; public static final long CHECK = (long)SZ * ((long)SZ + 1)/2; public static void main(String[] args) { diff --git a/threads/Summing3.java b/threads/Summing3.java index eba4c5be..9d0e446e 100644 --- a/threads/Summing3.java +++ b/threads/Summing3.java @@ -7,29 +7,29 @@ import java.util.*; public class Summing3 { static long basicSum(Long[] ia) { long sum = 0; - final int sz = ia.length; - for(int i = 0; i < sz; i++) + int size = ia.length; + for(int i = 0; i < size; i++) sum += ia[i]; return sum; } // Approximate largest value of SZ before // running out of memory on my machine: - public static int SZ = 10_000_000; + public static final int SZ = 10_000_000; public static final long CHECK = (long)SZ * ((long)SZ + 1)/2; public static void main(String[] args) { System.out.println(CHECK); - Long[] La = new Long[SZ+1]; - Arrays.parallelSetAll(La, i -> (long)i); + Long[] aL = new Long[SZ+1]; + Arrays.parallelSetAll(aL, i -> (long)i); Summing.timeTest("Long Array Stream Reduce", CHECK, () -> - Arrays.stream(La).reduce(0L, Long::sum)); + Arrays.stream(aL).reduce(0L, Long::sum)); Summing.timeTest("Long Basic Sum", CHECK, () -> - basicSum(La)); + basicSum(aL)); // Destructive summation: Summing.timeTest("Long parallelPrefix",CHECK, ()-> { - Arrays.parallelPrefix(La, Long::sum); - return La[La.length - 1]; + Arrays.parallelPrefix(aL, Long::sum); + return aL[aL.length - 1]; }); } } diff --git a/threads/Summing4.java b/threads/Summing4.java index 7cc6a63b..c068e55d 100644 --- a/threads/Summing4.java +++ b/threads/Summing4.java @@ -7,11 +7,11 @@ import java.util.*; public class Summing4 { public static void main(String[] args) { System.out.println(Summing3.CHECK); - Long[] La = new Long[Summing3.SZ+1]; - Arrays.parallelSetAll(La, i -> (long)i); + Long[] aL = new Long[Summing3.SZ+1]; + Arrays.parallelSetAll(aL, i -> (long)i); Summing.timeTest("Long Parallel", Summing3.CHECK, () -> - Arrays.stream(La).parallel().reduce(0L,Long::sum)); + Arrays.stream(aL).parallel().reduce(0L,Long::sum)); } } /* Output: diff --git a/threads/restaurant2/RestaurantWithQueues.java b/threads/restaurant2/RestaurantWithQueues.java index b3b5ed46..30101d7f 100644 --- a/threads/restaurant2/RestaurantWithQueues.java +++ b/threads/restaurant2/RestaurantWithQueues.java @@ -31,7 +31,7 @@ class Order { // (A data-transfer object) } } -// This is what comes back from the chef: +// This comes back from the chef: class Plate { private final Order order; private final Food food; diff --git a/typeinfo/ClassInitialization.java b/typeinfo/ClassInitialization.java index d0cd074b..f87a2222 100644 --- a/typeinfo/ClassInitialization.java +++ b/typeinfo/ClassInitialization.java @@ -5,8 +5,8 @@ import java.util.*; class Initable { - static final int staticFinal = 47; - static final int staticFinal2 = + static final int STATIC_FINAL = 47; + static final int STATIC_FINAL2 = ClassInitialization.rand.nextInt(1000); static { System.out.println("Initializing Initable"); @@ -34,9 +34,9 @@ public class ClassInitialization { Class initable = Initable.class; System.out.println("After creating Initable ref"); // Does not trigger initialization: - System.out.println(Initable.staticFinal); + System.out.println(Initable.STATIC_FINAL); // Does trigger initialization: - System.out.println(Initable.staticFinal2); + System.out.println(Initable.STATIC_FINAL2); // Does trigger initialization: System.out.println(Initable2.staticNonFinal); Class initable3 = Class.forName("Initable3"); diff --git a/typeinfo/HiddenImplementation.java b/typeinfo/HiddenImplementation.java index a1de7c48..9891843b 100644 --- a/typeinfo/HiddenImplementation.java +++ b/typeinfo/HiddenImplementation.java @@ -20,7 +20,7 @@ public class HiddenImplementation { } */ // Oops! Reflection still allows us to call g(): callHiddenMethod(a, "g"); - // And even methods that are less accessible! + // And even less accessible methods! callHiddenMethod(a, "u"); callHiddenMethod(a, "v"); callHiddenMethod(a, "w"); diff --git a/typeinfo/PetCount2.java b/typeinfo/PetCount2.java index 0adfde0d..073d1dab 100644 --- a/typeinfo/PetCount2.java +++ b/typeinfo/PetCount2.java @@ -6,7 +6,7 @@ import typeinfo.pets.*; public class PetCount2 { public static void main(String[] args) { - PetCount.countPets(Pets.creator); + PetCount.countPets(Pets.CREATOR); } } /* Output: diff --git a/typeinfo/PetCount3.java b/typeinfo/PetCount3.java index b7218108..a7259c17 100644 --- a/typeinfo/PetCount3.java +++ b/typeinfo/PetCount3.java @@ -12,7 +12,7 @@ public class PetCount3 { static class Counter extends LinkedHashMap, Integer> { public Counter() { - super(LiteralPetCreator.allTypes.stream() + super(LiteralPetCreator.ALL_TYPES.stream() .map(lpc -> Pair.make(lpc, 0)) .collect( Collectors.toMap(Pair::key, Pair::value))); diff --git a/typeinfo/Robot.java b/typeinfo/Robot.java index 180e2296..ca13cc22 100644 --- a/typeinfo/Robot.java +++ b/typeinfo/Robot.java @@ -9,7 +9,7 @@ public interface Robot { String name(); String model(); List operations(); - public static void test(Robot r) { + static void test(Robot r) { if(r instanceof Null) System.out.println("[Null Robot]"); System.out.println("Robot name: " + r.name()); diff --git a/typeinfo/Shapes.java b/typeinfo/Shapes.java index 94c20971..d6c169e6 100644 --- a/typeinfo/Shapes.java +++ b/typeinfo/Shapes.java @@ -7,7 +7,7 @@ import java.util.stream.*; abstract class Shape { void draw() { System.out.println(this + ".draw()"); } @Override - abstract public String toString(); + public abstract String toString(); } class Circle extends Shape { diff --git a/typeinfo/pets/ForNameCreator.java b/typeinfo/pets/ForNameCreator.java index 1a7696ee..cbfdbaf5 100644 --- a/typeinfo/pets/ForNameCreator.java +++ b/typeinfo/pets/ForNameCreator.java @@ -8,7 +8,7 @@ import java.util.*; public class ForNameCreator extends PetCreator { private static List> types = new ArrayList<>(); - // Types that you want randomly created: + // Types you want randomly created: private static String[] typeNames = { "typeinfo.pets.Mutt", "typeinfo.pets.Pug", diff --git a/typeinfo/pets/LiteralPetCreator.java b/typeinfo/pets/LiteralPetCreator.java index d06e6df0..f94f358d 100644 --- a/typeinfo/pets/LiteralPetCreator.java +++ b/typeinfo/pets/LiteralPetCreator.java @@ -11,22 +11,22 @@ public class LiteralPetCreator extends PetCreator { // No try block needed. @SuppressWarnings("unchecked") public static - final List> allTypes = + final List> ALL_TYPES = Collections.unmodifiableList(Arrays.asList( Pet.class, Dog.class, Cat.class, Rodent.class, Mutt.class, Pug.class, EgyptianMau.class, Manx.class, Cymric.class, Rat.class, Mouse.class, Hamster.class)); // Types for random creation: - private static final List> types = - allTypes.subList(allTypes.indexOf(Mutt.class), - allTypes.size()); + private static final List> TYPES = + ALL_TYPES.subList(ALL_TYPES.indexOf(Mutt.class), + ALL_TYPES.size()); @Override public List> types() { - return types; + return TYPES; } public static void main(String[] args) { - System.out.println(types); + System.out.println(TYPES); } } /* Output: diff --git a/typeinfo/pets/Pets.java b/typeinfo/pets/Pets.java index 1da72b06..c7cce4d0 100644 --- a/typeinfo/pets/Pets.java +++ b/typeinfo/pets/Pets.java @@ -8,15 +8,15 @@ import java.util.*; import java.util.stream.*; public class Pets { - public static final PetCreator creator = + public static final PetCreator CREATOR = new LiteralPetCreator(); public static Pet get() { - return creator.get(); + return CREATOR.get(); } public static Pet[] array(int size) { Pet[] result = new Pet[size]; for(int i = 0; i < size; i++) - result[i] = creator.get(); + result[i] = CREATOR.get(); return result; } public static List list(int size) { @@ -25,6 +25,6 @@ public class Pets { return result; } public static Stream stream() { - return Stream.generate(creator); + return Stream.generate(CREATOR); } } diff --git a/understandingcollections/CollectionMethods.java b/understandingcollections/CollectionMethods.java index f1eee036..eaea1383 100644 --- a/understandingcollections/CollectionMethods.java +++ b/understandingcollections/CollectionMethods.java @@ -4,15 +4,16 @@ // Visit http://OnJava8.com for more book information. // Things you can do with all Collections import java.util.*; -import onjava.*; +import static onjava.HTMLColors.*; public class CollectionMethods { public static void main(String[] args) { - Collection c = new ArrayList<>(); - c.addAll(Countries.names(6)); + Collection c = + new ArrayList<>(LIST.subList(0, 4)); c.add("ten"); c.add("eleven"); - System.out.println(c); + show(c); + border(); // Make an array from the List: Object[] array = c.toArray(); // Make a String array from the List: @@ -24,23 +25,26 @@ public class CollectionMethods { "Collections.max(c) = " + Collections.max(c)); System.out.println( "Collections.min(c) = " + Collections.min(c)); + border(); // Add a Collection to another Collection - Collection c2 = new ArrayList<>(); - c2.addAll(Countries.names(6)); + Collection c2 = + new ArrayList<>(LIST.subList(10, 14)); c.addAll(c2); - System.out.println(c); - c.remove(Countries.DATA[0][0]); - System.out.println(c); - c.remove(Countries.DATA[1][0]); - System.out.println(c); + show(c); + border(); + c.remove(LIST.get(0)); + show(c); + border(); // Remove all components that are // in the argument collection: c.removeAll(c2); - System.out.println(c); + show(c); + border(); c.addAll(c2); - System.out.println(c); + show(c); + border(); // Is an element in this Collection? - String val = Countries.DATA[3][0]; + String val = LIST.get(3); System.out.println( "c.contains(" + val + ") = " + c.contains(val)); // Is a Collection in this Collection? @@ -51,38 +55,80 @@ public class CollectionMethods { // Keep all the elements that are in both // c2 and c3 (an intersection of sets): c2.retainAll(c3); - System.out.println(c2); + show(c2); // Throw away all the elements // in c2 that also appear in c3: c2.removeAll(c3); System.out.println("c2.isEmpty() = " + c2.isEmpty()); - c = new ArrayList<>(); - c.addAll(Countries.names(6)); - System.out.println(c); + border(); + // Functional operation: + c = new ArrayList<>(LIST); + c.removeIf(s -> !s.startsWith("P")); + c.removeIf(s -> s.startsWith("Pale")); + // Stream operation: + c.stream().forEach(System.out::println); c.clear(); // Remove all elements System.out.println("after c.clear():" + c); } } /* Output: -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, -ten, eleven] +AliceBlue +AntiqueWhite +Aquamarine +Azure +ten +eleven +------------------------------ Collections.max(c) = ten -Collections.min(c) = ALGERIA -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, -ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA -FASO, BURUNDI] -[ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, -eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, -BURUNDI] -[BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, -ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] -[ten, eleven] -[ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA -FASO, BURUNDI] -c.contains(BOTSWANA) = true +Collections.min(c) = AliceBlue +------------------------------ +AliceBlue +AntiqueWhite +Aquamarine +Azure +ten +eleven +Brown +BurlyWood +CadetBlue +Chartreuse +------------------------------ +AntiqueWhite +Aquamarine +Azure +ten +eleven +Brown +BurlyWood +CadetBlue +Chartreuse +------------------------------ +AntiqueWhite +Aquamarine +Azure +ten +eleven +------------------------------ +AntiqueWhite +Aquamarine +Azure +ten +eleven +Brown +BurlyWood +CadetBlue +Chartreuse +------------------------------ +c.contains(Azure) = true c.containsAll(c2) = true -[ANGOLA, BENIN] c2.isEmpty() = true -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +------------------------------ +PapayaWhip +PeachPuff +Peru +Pink +Plum +PowderBlue +Purple after c.clear():[] */ diff --git a/understandingcollections/HTMLColorTest.java b/understandingcollections/HTMLColorTest.java index 67011c8f..7256bfcb 100644 --- a/understandingcollections/HTMLColorTest.java +++ b/understandingcollections/HTMLColorTest.java @@ -5,15 +5,15 @@ import static onjava.HTMLColors.*; public class HTMLColorTest { - static final int DISPLAYSIZE = 20; + static final int DISPLAY_SIZE = 20; public static void main(String[] args) { - show(MAP, DISPLAYSIZE); + show(MAP, DISPLAY_SIZE); border(); - show_inv(INVMAP, DISPLAYSIZE); + showInv(INVMAP, DISPLAY_SIZE); border(); - show(LIST, DISPLAYSIZE); + show(LIST, DISPLAY_SIZE); border(); - showrgb(RGBLIST, DISPLAYSIZE); + showrgb(RGBLIST, DISPLAY_SIZE); } } /* Output: diff --git a/understandingcollections/SetOrder.java b/understandingcollections/SetOrder.java index aade8900..2ca1a832 100644 --- a/understandingcollections/SetOrder.java +++ b/understandingcollections/SetOrder.java @@ -13,7 +13,7 @@ public class SetOrder { "java.util.LinkedHashSet", "java.util.concurrent.CopyOnWriteArraySet", }; - static List RLIST = + static final List RLIST = new ArrayList<>(HTMLColors.LIST); static { Collections.reverse(RLIST); @@ -21,7 +21,7 @@ public class SetOrder { public static void main(String[] args) throws Exception { for(String type: sets) { - System.out.format("[-> %s <-]\n", + System.out.format("[-> %s <-]%n", type.substring(type.lastIndexOf('.') + 1)); @SuppressWarnings("unchecked") Set set = (Set) diff --git a/understandingcollections/TypesForSets.java b/understandingcollections/TypesForSets.java index fd14711c..33ebe129 100644 --- a/understandingcollections/TypesForSets.java +++ b/understandingcollections/TypesForSets.java @@ -5,22 +5,25 @@ // Methods necessary to put your own type in a Set import java.util.*; import java.util.function.*; +import java.util.Objects; class SetType { int i; public SetType(int n) { i = n; } @Override public boolean equals(Object o) { - return o instanceof SetType && (i == ((SetType)o).i); + if (o == this) return true; + return o instanceof SetType && + Objects.equals(i, ((SetType)o).i); } @Override + public int hashCode() { return Objects.hash(i); } + @Override public String toString() { return Integer.toString(i); } } class HashType extends SetType { public HashType(int n) { super(n); } - @Override - public int hashCode() { return i; } } class TreeType extends SetType @@ -68,17 +71,13 @@ public class TypesForSets { } } /* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +[1, 2, 3, 4, 5, 6, 7, 8, 9, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] -[8, 6, 3, 5, 4, 2, 2, 1, 0, 3, 6, 7, 9, 1, 3, 1, 5, 0, 9, -8, 0, 9, 8, 7, 4, 6, 2, 4, 7, 5] -[2, 2, 1, 4, 6, 6, 8, 4, 9, 3, 0, 4, 8, 5, 8, 1, 7, 5, 5, -3, 1, 9, 6, 0, 7, 0, 9, 7, 2, 3] -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +[1, 2, 3, 4, 5, 6, 7, 8, 9, 0] +[1, 2, 3, 4, 5, 6, 7, 8, 9, 0] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Expected: SetType cannot be cast to java.lang.Comparable Expected: HashType cannot be cast to java.lang.Comparable */ diff --git a/understandingcollections/jmh/Deques.java b/understandingcollections/jmh/Deques.java index ab50aa76..c124bcf3 100644 --- a/understandingcollections/jmh/Deques.java +++ b/understandingcollections/jmh/Deques.java @@ -36,6 +36,7 @@ public class Deques { private int size; @Setup + @SuppressWarnings("unchecked") public void setup() throws Exception { deque = (Deque) Class.forName(type).newInstance(); diff --git a/understandingcollections/jmh/Lists.java b/understandingcollections/jmh/Lists.java index 997b992a..7cb1e566 100644 --- a/understandingcollections/jmh/Lists.java +++ b/understandingcollections/jmh/Lists.java @@ -39,6 +39,7 @@ public class Lists { private ListIterator it; @Setup + @SuppressWarnings("unchecked") public void setup() throws Exception { list = (List) Class.forName(type).newInstance(); diff --git a/understandingcollections/jmh/Maps.java b/understandingcollections/jmh/Maps.java index 30401618..9edcba33 100644 --- a/understandingcollections/jmh/Maps.java +++ b/understandingcollections/jmh/Maps.java @@ -42,6 +42,7 @@ public class Maps { private String key; @Setup + @SuppressWarnings("unchecked") public void setup() throws Exception { map = (Map) Class.forName(type).newInstance(); diff --git a/understandingcollections/jmh/Queues.java b/understandingcollections/jmh/Queues.java index 8a9ebad7..2cd61f8d 100644 --- a/understandingcollections/jmh/Queues.java +++ b/understandingcollections/jmh/Queues.java @@ -44,6 +44,7 @@ public class Queues { private int size; @Setup + @SuppressWarnings("unchecked") public void setup() throws Exception { queue = (Queue) Class.forName(type).newInstance(); diff --git a/understandingcollections/jmh/Sets.java b/understandingcollections/jmh/Sets.java index 98af1b47..3f3bf5a3 100644 --- a/understandingcollections/jmh/Sets.java +++ b/understandingcollections/jmh/Sets.java @@ -39,6 +39,7 @@ public class Sets { private String key; @Setup + @SuppressWarnings("unchecked") public void setup() throws Exception { set = (Set) Class.forName(type).newInstance(); diff --git a/validating/Inverter4.java b/validating/Inverter4.java index b00a4ad2..b1840ff4 100644 --- a/validating/Inverter4.java +++ b/validating/Inverter4.java @@ -6,7 +6,7 @@ package validating; import static java.lang.Character.*; public class Inverter4 implements StringInverter { - static final String allowed = + static final String ALLOWED = "abcdefghijklmnopqrstuvwxyz ,." + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public String invert(String str) { @@ -15,7 +15,7 @@ public class Inverter4 implements StringInverter { String result = ""; for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); - if(allowed.indexOf(c) == -1) + if(ALLOWED.indexOf(c) == -1) throw new RuntimeException(c + " Not allowed"); result += isUpperCase(c) ? toLowerCase(c) : diff --git a/validating/SLF4JLevels.java b/validating/SLF4JLevels.java index c2b66868..e8b2b4cb 100644 --- a/validating/SLF4JLevels.java +++ b/validating/SLF4JLevels.java @@ -5,7 +5,7 @@ import org.slf4j.*; public class SLF4JLevels { - private static final Logger log = + private static Logger log = LoggerFactory.getLogger(SLF4JLevels.class); public static void main(String[] args) { log.trace("Hello"); diff --git a/validating/SLF4JLogging.java b/validating/SLF4JLogging.java index 9a18dedf..0f23bb4d 100644 --- a/validating/SLF4JLogging.java +++ b/validating/SLF4JLogging.java @@ -5,7 +5,7 @@ import org.slf4j.*; public class SLF4JLogging { - private static final Logger log = + private static Logger log = LoggerFactory.getLogger(SLF4JLogging.class); public static void main(String[] args) { log.info("hello logging"); diff --git a/validating/StringInverter.java b/validating/StringInverter.java index 680bab3c..f01e46dc 100644 --- a/validating/StringInverter.java +++ b/validating/StringInverter.java @@ -5,5 +5,5 @@ package validating; interface StringInverter { - public String invert(String str); + String invert(String str); }