From 4f6362334dc967ee71bdd5220066dfc026fc8544 Mon Sep 17 00:00:00 2001 From: Bruce Eckel Date: Mon, 25 Jan 2016 18:05:55 -0800 Subject: [PATCH] After "Arrays" chapter completed --- annotations/AtUnitComposition.java | 5 +- annotations/AtUnitExample1.java | 3 +- annotations/AtUnitExample2.java | 5 +- annotations/AtUnitExample3.java | 3 +- annotations/AtUnitExample4.java | 25 +- annotations/AtUnitExample5.java | 3 +- annotations/AtUnitExternalTest.java | 5 +- annotations/HashSetTest.java | 3 +- annotations/PasswordUtils.java | 12 +- annotations/StackL.java | 2 +- annotations/StackLStringTest.java | 5 +- annotations/UseCaseTracker.java | 3 +- annotations/database/TableCreator.java | 11 +- annotations/database/Uniqueness.java | 2 +- annotations/ifx/ExtractInterface.java | 2 +- annotations/ifx/IfaceExtractorProcessor.java | 6 +- annotations/ifx/Multiplier.java | 2 +- annotations/simplest/Simple.java | 2 +- annotations/simplest/SimpleProcessor.java | 2 +- arrays/AlphabeticSearch.java | 11 +- arrays/ArrayCopying.java | 81 ++++++ arrays/ArrayOfGenericType.java | 8 +- arrays/ArrayOfGenerics.java | 16 +- arrays/ArrayOptions.java | 17 +- arrays/ArraySearching.java | 25 +- arrays/AssemblingMultidimensionalArrays.java | 2 +- arrays/BadMicroBenchmark.java | 21 ++ arrays/BadMicroBenchmark2.java | 22 ++ arrays/BadMicroBenchmark3.java | 34 +++ arrays/CollectionComparison.java | 11 +- arrays/CompType.java | 21 +- arrays/ComparatorTest.java | 13 +- arrays/ComparingArrays.java | 60 +++- arrays/CopyingArrays.java | 45 --- arrays/CountUpward.java | 23 ++ arrays/FillingArrays.java | 21 +- arrays/IceCream.java | 8 +- arrays/ModifyExisting.java | 21 ++ arrays/MultiDimWrapperArray.java | 2 +- arrays/MultidimensionalPrimitiveArray.java | 1 - arrays/ParallelPrefix.java | 22 ++ arrays/ParallelSetAll.java | 24 ++ arrays/ParallelSort.java | 26 ++ arrays/Prefix1.java | 27 ++ arrays/Prefix2.java | 20 ++ arrays/PrimitiveConversionDemonstration.java | 23 -- arrays/PythonLists.py | 10 + arrays/RaggedArray.java | 13 +- arrays/RandomSuppliersTest.java | 25 -- arrays/Reverse.java | 11 +- arrays/SimpleSetAll.java | 56 ++++ arrays/StreamFromArray.java | 51 ++++ arrays/StringSorting.java | 18 +- arrays/SuppliersTest.java | 40 --- arrays/TestArrayGeneration.java | 48 ---- arrays/TestConvertTo.java | 87 ++++++ arrays/TestCount.java | 140 ++++++++++ arrays/TestGenerated.java | 23 -- arrays/TestRand.java | 161 +++++++++++ arrays/build.xml | 44 ++- assertions/Assert2.java | 2 +- assertions/Queue.java | 7 +- build.xml | 4 +- collections/AdapterMethodIdiom.java | 10 +- collections/AddingGroups.java | 8 +- collections/ApplesAndOrangesWithGenerics.java | 6 - .../ApplesAndOrangesWithoutGenerics.java | 2 +- collections/AsListInference.java | 22 +- collections/CrossCollectionIteration2.java | 33 +++ collections/ForInCollections.java | 2 +- collections/GenericsAndUpcasting.java | 4 +- collections/IterableClass.java | 2 +- collections/ListFeatures.java | 3 +- collections/MapOfList.java | 4 +- collections/MultiIterableClass.java | 10 +- collections/NonCollectionSequence.java | 3 +- collections/PrintingCollections.java | 2 +- collections/QueueDemo.java | 2 +- collections/SetOfString.java | 25 ++ collections/SortedSetOfInteger.java | 19 -- collections/SortedSetOfString.java | 25 ++ collections/Statistics.java | 4 +- collections/UniqueWords.java | 3 +- collections/UniqueWordsAlphabetic.java | 5 +- collections/build.xml | 8 +- collectionsindepth/AssociativeArray.java | 2 +- collectionsindepth/Bits.java | 4 +- collectionsindepth/CanonicalMapping.java | 2 +- collectionsindepth/CollectionMethods.java | 2 +- collectionsindepth/CountedString.java | 2 +- collectionsindepth/Enumerations.java | 2 +- collectionsindepth/FailFast.java | 2 +- ...n.java => FilledCollectionGeneration.java} | 14 +- ...ataTest.java => FilledCollectionTest.java} | 9 +- collectionsindepth/FillingLists.java | 2 +- collectionsindepth/Groundhog.java | 2 +- collectionsindepth/Groundhog2.java | 2 +- collectionsindepth/LinkedHashMapDemo.java | 6 +- collectionsindepth/ListPerformance.java | 17 +- collectionsindepth/ListSortSearch.java | 5 +- collectionsindepth/Lists.java | 2 +- collectionsindepth/MapDataTest.java | 58 ---- collectionsindepth/MapEntry.java | 11 +- collectionsindepth/MapPerformance.java | 2 +- collectionsindepth/Maps.java | 8 +- collectionsindepth/Prediction.java | 4 +- collectionsindepth/ReadOnly.java | 2 +- collectionsindepth/SetPerformance.java | 2 +- collectionsindepth/SimpleHashMap.java | 11 +- collectionsindepth/SlowMap.java | 2 +- collectionsindepth/SortedMapDemo.java | 4 +- collectionsindepth/SortedSetDemo.java | 2 +- collectionsindepth/SpringDetector.java | 3 +- collectionsindepth/SpringDetector2.java | 5 +- collectionsindepth/Stacks.java | 5 +- collectionsindepth/Synchronization.java | 2 +- collectionsindepth/Test.java | 2 +- collectionsindepth/Tester.java | 28 +- collectionsindepth/ToDoList.java | 2 +- collectionsindepth/TypesForSets.java | 6 +- collectionsindepth/Unsupported.java | 5 +- collectionsindepth/Utilities.java | 2 +- collectionsindepth/build.xml | 10 +- com/mindviewinc/simple/List.java | 2 +- com/mindviewinc/simple/Vector.java | 2 +- compression/GZIPcompress.java | 13 +- compression/ZipCompress.java | 14 +- control/BreakAndContinue.java | 2 +- control/LabeledWhile.java | 2 +- control/ListCharacters.java | 3 +- control/VowelsAndConsonants.java | 2 +- control/WhileTest.java | 2 +- enums/Burrito.java | 8 +- enums/Competitor.java | 2 +- enums/EnumMaps.java | 4 +- enums/Input.java | 2 +- enums/OzWitch.java | 2 +- enums/PostOffice.java | 8 +- enums/RandomTest.java | 3 +- enums/Reflection.java | 2 +- enums/RoShamBo.java | 2 +- enums/RoShamBo1.java | 16 +- enums/RoShamBo2.java | 2 +- enums/RoShamBo3.java | 2 +- enums/RoShamBo5.java | 2 +- enums/RoShamBo6.java | 2 +- enums/SecurityCategory.java | 2 +- enums/SpaceShip.java | 3 +- enums/TrafficLight.java | 2 +- enums/build.xml | 4 +- enums/cartoons/EnumImplementation.java | 2 +- enums/menu/Food.java | 2 +- exceptions/AlwaysFinally.java | 2 +- exceptions/BodyException.java | 2 +- exceptions/Cleanup.java | 2 +- exceptions/CleanupIdiom.java | 6 +- exceptions/ConstructorException.java | 2 +- exceptions/DynamicFields.java | 4 +- exceptions/ExceptionMethods.java | 5 +- exceptions/ExtraFeatures.java | 5 +- exceptions/FinallyWorks.java | 2 +- exceptions/Human.java | 2 +- exceptions/InheritingExceptions.java | 2 +- exceptions/InputFile.java | 2 +- exceptions/InputFile2.java | 15 +- exceptions/LoggingExceptions.java | 2 +- exceptions/LoggingExceptions2.java | 2 +- exceptions/LostMessage.java | 2 +- exceptions/MainException.java | 3 +- exceptions/NeverCaught.java | 2 +- exceptions/RethrowNew.java | 2 +- exceptions/StormyInning.java | 2 +- exceptions/StreamsAreAutoCloseable.java | 4 +- exceptions/TurnOffChecking.java | 5 +- exceptions/WhoCalled.java | 10 +- exceptions/WithFinally.java | 2 +- files/AddAndSubtractPaths.java | 3 +- files/Directories.java | 3 +- files/Find.java | 3 +- files/ListOfLines.java | 3 +- files/PathAnalysis.java | 4 +- files/PathWatcher.java | 3 +- files/ReadLineStream.java | 3 +- files/TreeWatcher.java | 3 +- files/Writing.java | 3 +- files/build.xml | 3 +- functional/UnboundMethodReference.java | 2 +- generics/Apply.java | 79 +----- generics/ApplyFunctional.java | 49 ++++ generics/ApplyTest.java | 84 ++++++ generics/ArrayOfGeneric.java | 8 +- generics/BankTeller.java | 40 +-- generics/BasicBounds.java | 18 +- generics/BasicHolder.java | 3 +- generics/BasicSupplierDemo.java | 10 +- generics/CaptureConversion.java | 35 ++- generics/CheckedList.java | 2 +- generics/CountedObject.java | 4 +- generics/CreatorGeneric.java | 9 +- generics/DogsAndRobotMethodReferences.java | 44 +++ generics/DogsAndRobots.cpp | 18 +- generics/DogsAndRobots.java | 8 +- generics/DogsAndRobots.py | 15 +- generics/DynamicProxyMixin.java | 9 +- generics/EpicBattle.java | 19 +- generics/Erased.java | 19 +- generics/ErasureAndInheritance.java | 2 +- generics/FactoryConstraint.java | 64 +++-- generics/Fibonacci.java | 10 +- generics/Fill.java | 57 ---- generics/Fill2.java | 94 ------- generics/Functional.java | 191 ------------- generics/GenericArray.java | 10 +- generics/GenericArray2.java | 2 +- generics/GenericArrayWithTypeToken.java | 3 +- generics/GenericCast.java | 11 +- generics/GenericHolder.java | 4 +- generics/GenericReading.java | 12 +- generics/GenericVarargs.java | 2 +- generics/GenericWriting.java | 26 -- generics/HijackedInterface.java | 11 +- generics/Holder.java | 10 +- generics/InheritBounds.java | 14 +- generics/InstantiateGenericType.java | 30 +- generics/IterableFibonacci.java | 2 +- generics/LatentReflection.java | 2 +- generics/LinkedStack.java | 6 +- generics/ListMaker.java | 2 +- generics/ListOfInt.java | 16 +- generics/LostInformation.java | 6 +- generics/Mixins.cpp | 4 + generics/Mixins.java | 6 +- generics/MultipleInterfaceVariants.java | 3 +- generics/PlainGenericInheritance.java | 6 +- generics/PrimitiveGenericTest.java | 53 ++-- generics/RandomList.java | 6 +- .../SelfBoundingAndCovariantArguments.java | 16 +- generics/SimpleDogsAndRobots.java | 2 +- generics/Store.java | 6 +- generics/Suppliers.java | 34 --- generics/Templates.cpp | 3 + generics/ThrowGenericException.java | 16 +- generics/TupleList.java | 14 +- generics/TupleTest.java | 2 +- generics/TupleTest2.java | 5 +- generics/UnboundedWildcards1.java | 25 +- generics/UnboundedWildcards2.java | 17 +- generics/Unconstrained.java | 3 +- generics/UseList.java | 2 +- generics/UseList2.java | 2 +- generics/WatercolorSets.java | 30 +- generics/Wildcards.java | 257 ++++++++++++++---- generics/build.xml | 14 +- generics/coffee/CoffeeSupplier.java | 8 +- generics/dogsandrobots.go | 32 +++ hiding/Cake.java | 2 +- hiding/ChocolateChip.java | 4 +- hiding/Dinner.java | 2 +- hiding/IceCream.java | 2 +- hiding/LibTest.java | 2 +- hiding/Pie.java | 2 +- hiding/build.xml | 2 +- hiding/dessert/Cookie.java | 2 +- hiding/foreign/Foreign.java | 13 - hiding/local/PackagedClass.java | 11 - housekeeping/ArrayClassObj.java | 2 +- housekeeping/ArrayInit.java | 2 +- housekeeping/ArrayNew.java | 2 +- housekeeping/Burrito.java | 7 +- housekeeping/Demotion.java | 2 +- housekeeping/DynamicArray.java | 2 +- housekeeping/ExplicitStatic.java | 2 +- housekeeping/InitialValues.java | 2 +- housekeeping/InitialValues2.java | 2 +- housekeeping/Leaf.java | 2 +- housekeeping/Mugs.java | 2 +- housekeeping/NewVarArgs.java | 2 +- housekeeping/OrderOfInitialization.java | 2 +- housekeeping/Overloading.java | 3 +- housekeeping/OverloadingOrder.java | 2 +- housekeeping/PrimitiveOverloading.java | 2 +- housekeeping/SimpleConstructor.java | 2 +- housekeeping/SimpleConstructor2.java | 2 +- housekeeping/StaticInitialization.java | 2 +- housekeeping/TerminationCondition.java | 4 +- housekeeping/VarArgs.java | 2 +- innerclasses/AnonymousConstructor.java | 5 +- innerclasses/BigEgg.java | 10 +- innerclasses/BigEgg2.java | 2 +- innerclasses/Callbacks.java | 9 +- innerclasses/DotNew.java | 2 +- innerclasses/DotThis.java | 2 +- innerclasses/GreenhouseController.java | 6 +- innerclasses/GreenhouseControls.java | 49 +++- innerclasses/InheritInner.java | 2 +- innerclasses/LocalInnerClass.java | 4 +- innerclasses/MultiImplementation.java | 5 +- innerclasses/MultiNestingAccess.java | 2 +- innerclasses/Parcel1.java | 2 +- innerclasses/Parcel10.java | 2 +- innerclasses/Parcel11.java | 5 +- innerclasses/Parcel2.java | 2 +- innerclasses/Parcel3.java | 2 +- innerclasses/Parcel5.java | 2 +- innerclasses/Parcel6.java | 2 +- innerclasses/Parcel7.java | 6 +- innerclasses/Parcel7b.java | 4 +- innerclasses/Parcel8.java | 6 +- innerclasses/Parcel9.java | 6 +- innerclasses/Sequence.java | 6 +- innerclasses/TestBed.java | 2 +- innerclasses/controller/Controller.java | 2 +- innerclasses/controller/Event.java | 15 +- innerclasses/mui/MultiInterfaces.java | 2 +- interfaces/AdaptedRandomDoubles.java | 2 +- interfaces/Adventure.java | 2 +- interfaces/Applicator.java | 2 +- interfaces/Factories.java | 3 +- interfaces/Games.java | 2 +- interfaces/HorrorShow.java | 2 +- interfaces/Months.java | 2 +- interfaces/PureInterface.java | 2 +- interfaces/RandVals.java | 2 +- interfaces/RandomDoubles.java | 2 +- interfaces/RandomWords.java | 2 +- interfaces/build.xml | 4 + .../interfaceprocessor/StringProcessor.java | 6 +- interfaces/music4/Music4.java | 2 +- iostreams/BasicFileOutput.java | 4 +- iostreams/BufferedInputFile.java | 8 +- iostreams/FileOutputShortcut.java | 8 +- iostreams/FormattedMemoryInput.java | 14 +- iostreams/MemoryInput.java | 4 +- iostreams/StoringAndRecoveringData.java | 4 +- iostreams/TestEOF.java | 17 +- iostreams/UsingRandomAccessFile.java | 6 +- network/ChatterClient.java | 2 +- network/Dgram.java | 6 +- network/LocalHost.java | 4 +- network/MultiSimpleClient.java | 8 +- network/MultiSimpleServer.java | 7 +- network/SimpleClient.java | 9 +- network/SimpleServer.java | 7 +- network/WhoAmI.java | 6 +- newio/BufferToText.java | 45 +-- newio/ChannelCopy.java | 24 +- newio/Endians.java | 2 +- newio/FileLocking.java | 5 +- newio/GetChannel.java | 35 --- newio/LargeMappedFiles.java | 23 +- newio/LockingMappedFiles.java | 11 +- newio/MappedIO.java | 24 +- newio/TransferTo.java | 20 +- newio/UsingBuffers.java | 3 +- newio/build.xml | 2 - onjava/ArrayShow.java | 73 +++++ onjava/BasicSupplier.java | 9 +- onjava/CollectionMethodDifferences.java | 16 +- onjava/ConvertTo.java | 51 +++- onjava/Count.java | 202 ++++++++++++++ ...ingMapData.java => CountingFilledMap.java} | 10 +- onjava/CountingIntegerList.java | 2 +- onjava/CountingSupplier.java | 88 ------ onjava/Countries.java | 5 +- onjava/DaemonThreadFactory.java | 3 +- onjava/Deque.java | 2 +- onjava/Enums.java | 5 +- ...lectionData.java => FilledCollection.java} | 12 +- onjava/{MapData.java => FilledMap.java} | 37 +-- onjava/Generated.java | 21 -- onjava/Hex.java | 3 +- onjava/OSExecute.java | 39 ++- onjava/Rand.java | 224 +++++++++++++++ onjava/RandomSupplier.java | 85 ------ onjava/Range.java | 3 +- onjava/RmDir.java | 2 +- onjava/Sets.java | 3 +- onjava/Sleep.java | 2 +- onjava/Stack.java | 10 +- onjava/Suppliers.java | 37 +++ onjava/SwingConsole.java | 2 +- onjava/TaskItem.java | 2 +- onjava/TaskManager.java | 2 +- onjava/TimeIt.java | 17 ++ onjava/TimedAbort.java | 2 +- onjava/Tuple.java | 2 +- onjava/Tuple3.java | 2 +- onjava/TypeCounter.java | 2 +- onjava/atunit/AtUnit.java | 8 +- onjava/atunit/ClassNameFinder.java | 3 +- onjava/atunit/Test.java | 2 +- onjava/atunit/TestObjectCleanup.java | 2 +- onjava/atunit/TestObjectCreate.java | 2 +- onjava/atunit/TestProperty.java | 2 +- onjava/build.xml | 4 +- operators/AllOps.java | 4 +- operators/Assignment.java | 2 +- operators/AutoInc.java | 2 +- operators/BitManipulation.java | 2 +- operators/Bool.java | 2 +- operators/EqualsMethod2.java | 2 +- operators/MathOps.java | 2 +- operators/Overflow.java | 2 +- operators/PassObject.java | 2 +- operators/RoundingNumbers.java | 2 +- operators/ShortCircuit.java | 2 +- operators/URShift.java | 2 +- output_duet.py | 142 +++++----- patterns/CommandPattern.java | 2 +- patterns/Facade.java | 2 +- patterns/PaperScissorsRock.java | 6 +- patterns/ProxyDemo.java | 4 +- patterns/ShapeFactory2.java | 4 +- patterns/StateDemo.java | 4 +- patterns/TemplateMethod.java | 4 +- patterns/absfactory/GameEnvironment.java | 4 +- patterns/adapt/Adapter.java | 4 +- patterns/chain/ChainOfResponsibility.java | 4 +- patterns/doubledispatch/Aluminum.java | 2 +- patterns/doubledispatch/Cardboard.java | 2 +- patterns/doubledispatch/DoubleDispatch.java | 2 +- patterns/doubledispatch/Glass.java | 2 +- patterns/doubledispatch/Paper.java | 2 +- patterns/doubledispatch/TypedBin.java | 2 +- patterns/doubledispatch/TypedBinMember.java | 2 +- patterns/factory/ShapeFactory1.java | 4 +- patterns/observer/ObservedFlower.java | 4 +- patterns/recyclea/RecycleA.java | 4 +- patterns/recyclec/RecycleC.java | 2 +- patterns/state/StateMachineDemo.java | 5 +- patterns/strategy/StrategyPattern.java | 2 +- patterns/strategy/StrategyPattern2.java | 2 +- patterns/trash/Fillable.java | 2 +- patterns/trash/FillableList.java | 2 +- patterns/trash/ParseTrash.java | 2 +- patterns/trash/Trash.java | 2 +- patterns/trashvisitor/Aluminum.java | 2 +- patterns/trashvisitor/Cardboard.java | 2 +- patterns/trashvisitor/Glass.java | 2 +- patterns/trashvisitor/Paper.java | 2 +- patterns/trashvisitor/Visitable.java | 5 +- patterns/trashvisitor/Visitor.java | 2 +- patterns/visitor/BeeAndFlowers.java | 6 +- patterns/visualobserver/BoxObserver.java | 2 +- polymorphism/FieldAccess.java | 2 +- polymorphism/Frog.java | 2 +- polymorphism/PolyConstructors.java | 2 +- polymorphism/PrivateOverride.java | 2 +- polymorphism/PrivateOverride2.java | 20 ++ polymorphism/RTTI.java | 2 +- polymorphism/ReferenceCounting.java | 20 +- polymorphism/Sandwich.java | 10 +- polymorphism/Shapes.java | 13 +- polymorphism/StaticPolymorphism.java | 2 +- polymorphism/Transmogrify.java | 10 +- polymorphism/build.xml | 2 +- polymorphism/music/Music.java | 2 +- polymorphism/music/Music2.java | 2 +- polymorphism/music/Note.java | 4 +- polymorphism/music3/Music3.java | 2 +- ...mShapeGenerator.java => RandomShapes.java} | 13 +- preferences/PreferencesDemo.java | 6 +- references/AddingClone.java | 14 +- references/Alias1.java | 6 +- references/Alias2.java | 8 +- references/CheckCloneable.java | 11 +- .../{Cloning.java => CloneArrayList.java} | 10 +- references/Compete.java | 67 ++--- references/CopyConstructor.java | 12 +- references/DeepCopy.java | 44 ++- references/HorrorFlick.java | 14 +- references/Immutable1.java | 2 +- references/ImmutableInteger.java | 2 +- references/ImmutableStrings.java | 8 +- references/LocalCopy.java | 57 ---- references/MutableInteger.java | 2 +- references/PassReferences.java | 1 - references/SimplerMutableInteger.java | 30 ++ references/Snake.java | 17 +- references/build.xml | 8 +- remote/PerfectTimeImpl.java | 3 +- remote/PerfectTimeServer.java | 6 +- reuse/Bath.java | 2 +- reuse/Beetle.java | 2 +- reuse/BlankFinal.java | 2 +- reuse/CADSystem.java | 10 +- reuse/Car.java | 2 +- reuse/Cartoon.java | 2 +- reuse/Chess.java | 2 +- reuse/Detergent.java | 2 +- reuse/FinalArguments.java | 2 +- reuse/FinalData.java | 5 +- reuse/FinalOverridingIllusion.java | 2 +- reuse/Hide.java | 2 +- reuse/Jurassic.java | 2 +- reuse/Orc.java | 2 +- reuse/PlaceSetting.java | 2 +- reuse/SprinklerSystem.java | 4 +- reuse/Wind.java | 2 +- serialization/APerson.java | 18 +- serialization/AStoreCADState.java | 19 +- serialization/Alien.java | 2 +- serialization/Blip3.java | 7 +- serialization/Blips.java | 7 +- serialization/FreezeAlien.java | 5 +- serialization/Logon.java | 7 +- serialization/MyWorld.java | 58 ++-- serialization/People.java | 6 +- serialization/RecoverCADState.java | 23 +- serialization/SerialCtl.java | 10 +- serialization/Worm.java | 16 +- serialization/xfiles/ThawAlien.java | 3 +- standardio/ChangeSystemOut.java | 2 +- standardio/Echo.java | 9 +- standardio/OSExecuteDemo.java | 2 +- standardio/Redirecting.java | 8 +- standardio/build.xml | 4 +- staticchecking/DogsAndRobots.cpp | 4 + staticchecking/DogsAndRobots.py | 9 +- staticchecking/NoBasePetSpeak.py | 18 +- staticchecking/PetSpeak.py | 13 +- staticchecking/dogsandrobots.go | 4 + .../drc/DogAndRobotCollections.java | 6 +- staticchecking/petspeak.go | 24 +- streams/FileToWordsBuilder.java | 3 +- streams/FileToWordsRegexp.java | 3 +- streams/FileToWordsTest.java | 3 +- streams/FlatMap.java | 3 +- streams/Informational.java | 3 +- streams/OptionalFlatMap.java | 3 +- streams/Peeking.java | 3 +- streams/RandomWords.java | 6 +- streams/SortedComparator.java | 3 +- streams/SpecialCollector.java | 3 +- streams/TreeSetOfWords.java | 3 +- strings/InfiniteRecursion.java | 2 +- strings/JGrep.java | 5 +- strings/ReceiptBuilder.java | 3 +- strings/Resetting.java | 3 +- strings/StartEnd.java | 2 +- strings/TestRegularExpression.java | 2 +- strings/TheReplacements.java | 3 +- strings/ThreatAnalyzer.java | 3 +- swt/ColorBoxes.java | 4 +- swt/DisplayEnvironment.java | 5 +- swt/DisplayProperties.java | 2 +- swt/HelloSWT.java | 2 +- swt/Menus.java | 5 +- swt/ShellsAreMainWindows.java | 2 +- swt/SineWave.java | 2 +- swt/TabbedPane.java | 9 +- {concurrency => tasks}/ActiveObjectDemo.java | 6 +- .../AtomicEvenSupplier.java | 4 +- {concurrency => tasks}/AtomicIntegerTest.java | 2 +- {concurrency => tasks}/Atomicity.java | 2 +- {concurrency => tasks}/AtomicityTest.java | 6 +- {concurrency => tasks}/AttemptLocking.java | 8 +- .../BankTellerSimulation.java | 29 +- {concurrency => tasks}/BasicThreads.java | 4 +- {concurrency => tasks}/CachedThreadPool.java | 8 +- {concurrency => tasks}/CallableDemo.java | 8 +- .../CaptureUncaughtException.java | 2 +- {concurrency => tasks}/CarBuilder.java | 36 ++- {concurrency => tasks}/Chopstick.java | 4 +- {concurrency => tasks}/CloseResource.java | 18 +- .../CountDownLatchDemo.java | 15 +- {concurrency => tasks}/CriticalSection.java | 16 +- {concurrency => tasks}/DaemonFromFactory.java | 7 +- {concurrency => tasks}/Daemons.java | 7 +- .../DaemonsDoRunFinally.java | 5 +- .../DeadlockingDiningPhilosophers.java | 13 +- {concurrency => tasks}/DelayQueueDemo.java | 12 +- {concurrency => tasks}/EvenChecker.java | 8 +- {concurrency => tasks}/EvenSupplier.java | 4 +- {concurrency => tasks}/ExceptionThread.java | 6 +- {concurrency => tasks}/ExchangerDemo.java | 16 +- .../ExplicitCriticalSection.java | 7 +- {concurrency => tasks}/FastSimulation.java | 16 +- {concurrency => tasks}/Fat.java | 4 +- .../FixedDiningPhilosophers.java | 15 +- {concurrency => tasks}/FixedThreadPool.java | 8 +- .../GreenhouseScheduler.java | 26 +- {concurrency => tasks}/HorseRace.java | 8 +- {concurrency => tasks}/IntSupplier.java | 2 +- {concurrency => tasks}/Interrupting.java | 16 +- {concurrency => tasks}/Interrupting2.java | 7 +- {concurrency => tasks}/InterruptingIdiom.java | 7 +- {concurrency => tasks}/Joining.java | 7 +- {concurrency => tasks}/LiftOff.java | 4 +- {concurrency => tasks}/ListComparisons.java | 12 +- {concurrency => tasks}/MainThread.java | 2 +- {concurrency => tasks}/MapComparisons.java | 25 +- {concurrency => tasks}/MoreBasicThreads.java | 4 +- {concurrency => tasks}/MultiLock.java | 7 +- {concurrency => tasks}/MutexEvenSupplier.java | 4 +- {concurrency => tasks}/NIOInterruption.java | 18 +- .../NaiveExceptionHandling.java | 2 +- {concurrency => tasks}/NotifyVsNotifyAll.java | 13 +- {concurrency => tasks}/OrnamentalGarden.java | 18 +- {concurrency => tasks}/Philosopher.java | 4 +- {concurrency => tasks}/PipedIO.java | 18 +- {concurrency => tasks}/Pool.java | 4 +- .../PriorityBlockingQueueDemo.java | 24 +- {concurrency => tasks}/ReaderWriterList.java | 10 +- {concurrency => tasks}/ResponsiveUI.java | 7 +- {concurrency => tasks}/Restaurant.java | 6 +- {concurrency => tasks}/SelfManaged.java | 4 +- {concurrency => tasks}/SemaphoreDemo.java | 13 +- .../SerialNumberChecker.java | 7 +- .../SerialNumberSupplier.java | 2 +- .../SettingDefaultHandler.java | 6 +- {concurrency => tasks}/SimpleDaemons.java | 7 +- .../SimpleMicroBenchmark.java | 7 +- {concurrency => tasks}/SimplePriorities.java | 12 +- {concurrency => tasks}/SimpleThread.java | 4 +- .../SingleThreadExecutor.java | 2 +- {concurrency => tasks}/SleepingTask.java | 10 +- {concurrency => tasks}/SyncObject.java | 4 +- .../SynchronizationComparisons.java | 6 +- .../TestBlockingQueues.java | 2 +- {concurrency => tasks}/Tester.java | 7 +- .../ThreadLocalVariableHolder.java | 15 +- {concurrency => tasks}/ThreadVariations.java | 4 +- {concurrency => tasks}/ToastOMatic.java | 24 +- {concurrency => tasks}/build.xml | 22 +- .../restaurant2/RestaurantWithQueues.java | 26 +- .../waxomatic/WaxOMatic.java | 17 +- .../waxomatic2/WaxOMatic2.java | 23 +- typeinfo/AnonymousImplementation.java | 5 +- typeinfo/ClassInitialization.java | 3 +- typeinfo/HiddenImplementation.java | 8 +- typeinfo/InnerImplementation.java | 5 +- typeinfo/InterfaceViolation.java | 2 +- typeinfo/ModifyingPrivateFields.java | 6 +- typeinfo/NullRobot.java | 2 +- typeinfo/Operation.java | 3 +- typeinfo/Person.java | 5 +- typeinfo/PetCount.java | 2 +- typeinfo/PetCount3.java | 2 +- typeinfo/RegisteredFactories.java | 2 +- typeinfo/SelectingMethods.java | 11 +- typeinfo/ShowMethods.java | 6 +- typeinfo/SimpleProxyDemo.java | 3 +- typeinfo/SweetShop.java | 2 +- typeinfo/pets/Individual.java | 3 +- typeinfo/pets/LiteralPetCreator.java | 10 +- typeinfo/pets/PetCreator.java | 5 +- typeinfo/pets/Pets.java | 2 +- typeinfo/toys/GenericToyTest.java | 5 +- typeinfo/toys/ToyTest.java | 2 +- ui/BorderLayout1.java | 2 +- ui/Borders.java | 2 +- ui/Button1.java | 2 +- ui/Button2.java | 2 +- ui/Button2b.java | 2 +- ui/ButtonGroups.java | 2 +- ui/Buttons.java | 2 +- ui/CheckBoxes.java | 2 +- ui/ColorBoxes.java | 4 +- ui/ComboBoxes.java | 2 +- ui/Dialogs.java | 2 +- ui/Faces.java | 2 +- ui/FileChooserTest.java | 38 +-- ui/FlowLayout1.java | 2 +- ui/GridLayout1.java | 2 +- ui/HTMLButton.java | 2 +- ui/HelloLabel.java | 3 +- ui/InterruptableLongRunningCallable.java | 2 +- ui/InterruptableLongRunningTask.java | 2 +- ui/LongRunningTask.java | 2 +- ui/LookAndFeel.java | 2 +- ui/Menus.java | 2 +- ui/MessageBoxes.java | 6 +- ui/MonitoredLongRunningCallable.java | 2 +- ui/Popup.java | 2 +- ui/Progress.java | 2 +- ui/RadioButtons.java | 2 +- ui/ShowAddListeners.java | 5 +- ui/SineWave.java | 2 +- ui/SubmitLabelManipulationTask.java | 3 +- ui/SubmitSwingProgram.java | 3 +- ui/TabbedPane1.java | 2 +- ui/TextArea.java | 2 +- ui/TextFields.java | 8 +- ui/TextPane.java | 6 +- ui/TicTacToe.java | 18 +- ui/TrackEvent.java | 2 +- unittesting/JUnitDemo.java | 2 +- verify_output.py | 2 +- 689 files changed, 4450 insertions(+), 3060 deletions(-) create mode 100644 arrays/ArrayCopying.java create mode 100644 arrays/BadMicroBenchmark.java create mode 100644 arrays/BadMicroBenchmark2.java create mode 100644 arrays/BadMicroBenchmark3.java delete mode 100644 arrays/CopyingArrays.java create mode 100644 arrays/CountUpward.java create mode 100644 arrays/ModifyExisting.java create mode 100644 arrays/ParallelPrefix.java create mode 100644 arrays/ParallelSetAll.java create mode 100644 arrays/ParallelSort.java create mode 100644 arrays/Prefix1.java create mode 100644 arrays/Prefix2.java delete mode 100644 arrays/PrimitiveConversionDemonstration.java delete mode 100644 arrays/RandomSuppliersTest.java create mode 100644 arrays/SimpleSetAll.java create mode 100644 arrays/StreamFromArray.java delete mode 100644 arrays/SuppliersTest.java delete mode 100644 arrays/TestArrayGeneration.java create mode 100644 arrays/TestConvertTo.java create mode 100644 arrays/TestCount.java delete mode 100644 arrays/TestGenerated.java create mode 100644 arrays/TestRand.java create mode 100644 collections/CrossCollectionIteration2.java create mode 100644 collections/SetOfString.java delete mode 100644 collections/SortedSetOfInteger.java create mode 100644 collections/SortedSetOfString.java rename collectionsindepth/{CollectionDataGeneration.java => FilledCollectionGeneration.java} (62%) rename collectionsindepth/{CollectionDataTest.java => FilledCollectionTest.java} (79%) delete mode 100644 collectionsindepth/MapDataTest.java create mode 100644 generics/ApplyFunctional.java create mode 100644 generics/ApplyTest.java create mode 100644 generics/DogsAndRobotMethodReferences.java delete mode 100644 generics/Fill.java delete mode 100644 generics/Fill2.java delete mode 100644 generics/Functional.java delete mode 100644 generics/GenericWriting.java delete mode 100644 generics/Suppliers.java create mode 100644 generics/dogsandrobots.go delete mode 100644 hiding/foreign/Foreign.java delete mode 100644 hiding/local/PackagedClass.java delete mode 100644 newio/GetChannel.java create mode 100644 onjava/ArrayShow.java create mode 100644 onjava/Count.java rename onjava/{CountingMapData.java => CountingFilledMap.java} (90%) delete mode 100644 onjava/CountingSupplier.java rename onjava/{CollectionData.java => FilledCollection.java} (56%) rename onjava/{MapData.java => FilledMap.java} (57%) delete mode 100644 onjava/Generated.java create mode 100644 onjava/Rand.java delete mode 100644 onjava/RandomSupplier.java create mode 100644 onjava/Suppliers.java create mode 100644 onjava/TimeIt.java create mode 100644 polymorphism/PrivateOverride2.java rename polymorphism/shape/{RandomShapeGenerator.java => RandomShapes.java} (59%) rename references/{Cloning.java => CloneArrayList.java} (84%) delete mode 100644 references/LocalCopy.java create mode 100644 references/SimplerMutableInteger.java rename {concurrency => tasks}/ActiveObjectDemo.java (95%) rename {concurrency => tasks}/AtomicEvenSupplier.java (85%) rename {concurrency => tasks}/AtomicIntegerTest.java (96%) rename {concurrency => tasks}/Atomicity.java (96%) rename {concurrency => tasks}/AtomicityTest.java (86%) rename {concurrency => tasks}/AttemptLocking.java (90%) rename {concurrency => tasks}/BankTellerSimulation.java (90%) rename {concurrency => tasks}/BasicThreads.java (86%) rename {concurrency => tasks}/CachedThreadPool.java (82%) rename {concurrency => tasks}/CallableDemo.java (87%) rename {concurrency => tasks}/CaptureUncaughtException.java (97%) rename {concurrency => tasks}/CarBuilder.java (92%) rename {concurrency => tasks}/Chopstick.java (86%) rename {concurrency => tasks}/CloseResource.java (74%) rename {concurrency => tasks}/CountDownLatchDemo.java (87%) rename {concurrency => tasks}/CriticalSection.java (93%) rename {concurrency => tasks}/DaemonFromFactory.java (90%) rename {concurrency => tasks}/Daemons.java (92%) rename {concurrency => tasks}/DaemonsDoRunFinally.java (89%) rename {concurrency => tasks}/DeadlockingDiningPhilosophers.java (83%) rename {concurrency => tasks}/DelayQueueDemo.java (90%) rename {concurrency => tasks}/EvenChecker.java (85%) rename {concurrency => tasks}/EvenSupplier.java (91%) rename {concurrency => tasks}/ExceptionThread.java (75%) rename {concurrency => tasks}/ExchangerDemo.java (87%) rename {concurrency => tasks}/ExplicitCriticalSection.java (94%) rename {concurrency => tasks}/FastSimulation.java (87%) rename {concurrency => tasks}/Fat.java (90%) rename {concurrency => tasks}/FixedDiningPhilosophers.java (83%) rename {concurrency => tasks}/FixedThreadPool.java (83%) rename {concurrency => tasks}/GreenhouseScheduler.java (90%) rename {concurrency => tasks}/HorseRace.java (95%) rename {concurrency => tasks}/IntSupplier.java (92%) rename {concurrency => tasks}/Interrupting.java (87%) rename {concurrency => tasks}/Interrupting2.java (90%) rename {concurrency => tasks}/InterruptingIdiom.java (93%) rename {concurrency => tasks}/Joining.java (92%) rename {concurrency => tasks}/LiftOff.java (90%) rename {concurrency => tasks}/ListComparisons.java (89%) rename {concurrency => tasks}/MainThread.java (92%) rename {concurrency => tasks}/MapComparisons.java (82%) rename {concurrency => tasks}/MoreBasicThreads.java (92%) rename {concurrency => tasks}/MultiLock.java (88%) rename {concurrency => tasks}/MutexEvenSupplier.java (89%) rename {concurrency => tasks}/NIOInterruption.java (80%) rename {concurrency => tasks}/NaiveExceptionHandling.java (93%) rename {concurrency => tasks}/NotifyVsNotifyAll.java (91%) rename {concurrency => tasks}/OrnamentalGarden.java (87%) rename {concurrency => tasks}/Philosopher.java (94%) rename {concurrency => tasks}/PipedIO.java (82%) rename {concurrency => tasks}/Pool.java (95%) rename {concurrency => tasks}/PriorityBlockingQueueDemo.java (86%) rename {concurrency => tasks}/ReaderWriterList.java (91%) rename {concurrency => tasks}/ResponsiveUI.java (86%) rename {concurrency => tasks}/Restaurant.java (94%) rename {concurrency => tasks}/SelfManaged.java (92%) rename {concurrency => tasks}/SemaphoreDemo.java (91%) rename {concurrency => tasks}/SerialNumberChecker.java (93%) rename {concurrency => tasks}/SerialNumberSupplier.java (89%) rename {concurrency => tasks}/SettingDefaultHandler.java (76%) rename {concurrency => tasks}/SimpleDaemons.java (89%) rename {concurrency => tasks}/SimpleMicroBenchmark.java (90%) rename {concurrency => tasks}/SimplePriorities.java (89%) rename {concurrency => tasks}/SimpleThread.java (92%) rename {concurrency => tasks}/SingleThreadExecutor.java (95%) rename {concurrency => tasks}/SleepingTask.java (84%) rename {concurrency => tasks}/SyncObject.java (92%) rename {concurrency => tasks}/SynchronizationComparisons.java (97%) rename {concurrency => tasks}/TestBlockingQueues.java (98%) rename {concurrency => tasks}/Tester.java (92%) rename {concurrency => tasks}/ThreadLocalVariableHolder.java (78%) rename {concurrency => tasks}/ThreadVariations.java (98%) rename {concurrency => tasks}/ToastOMatic.java (90%) rename {concurrency => tasks}/build.xml (84%) rename {concurrency => tasks}/restaurant2/RestaurantWithQueues.java (91%) rename {concurrency => tasks}/waxomatic/WaxOMatic.java (85%) rename {concurrency => tasks}/waxomatic2/WaxOMatic2.java (83%) diff --git a/annotations/AtUnitComposition.java b/annotations/AtUnitComposition.java index bdc90df7..714d9b78 100644 --- a/annotations/AtUnitComposition.java +++ b/annotations/AtUnitComposition.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating non-embedded tests. +// Creating non-embedded tests package annotations; import onjava.atunit.*; import onjava.*; @@ -16,7 +16,8 @@ public class AtUnitComposition { @Test boolean _methodTwo() { return testObject.methodTwo() == 2; } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitComposition.class"); } diff --git a/annotations/AtUnitExample1.java b/annotations/AtUnitExample1.java index 7b009148..3987752b 100644 --- a/annotations/AtUnitExample1.java +++ b/annotations/AtUnitExample1.java @@ -22,7 +22,8 @@ public class AtUnitExample1 { // Shows output for failure: @Test boolean failureTest() { return false; } @Test boolean anotherDisappointment() { return false; } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitExample1.class"); } diff --git a/annotations/AtUnitExample2.java b/annotations/AtUnitExample2.java index 8e3c806b..467e61c1 100644 --- a/annotations/AtUnitExample2.java +++ b/annotations/AtUnitExample2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Assertions and exceptions can be used in @Tests. +// Assertions and exceptions can be used in @Tests package annotations; import java.io.*; import onjava.atunit.*; @@ -30,7 +30,8 @@ public class AtUnitExample2 { assert methodTwo() == 2: "methodTwo must equal 2"; return methodOne().equals("This is methodOne"); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitExample2.class"); } diff --git a/annotations/AtUnitExample3.java b/annotations/AtUnitExample3.java index 515deaa3..f81eeb53 100644 --- a/annotations/AtUnitExample3.java +++ b/annotations/AtUnitExample3.java @@ -25,7 +25,8 @@ public class AtUnitExample3 { return methodOne().equals("This is methodOne"); } @Test boolean m2() { return methodTwo() == 2; } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitExample3.class"); } diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java index 4208a8e8..2c446ce0 100644 --- a/annotations/AtUnitExample4.java +++ b/annotations/AtUnitExample4.java @@ -16,10 +16,8 @@ public class AtUnitExample4 { public AtUnitExample4(String word) { this.word = word; } public String getWord() { return word; } public String scrambleWord() { - // <* Improve this: *> - List chars = new ArrayList<>(); - for(Character c : word.toCharArray()) - chars.add(c); + List chars = + Arrays.asList(ConvertTo.boxed(word.toCharArray())); Collections.shuffle(chars, rand); StringBuilder result = new StringBuilder(); for(char ch : chars) @@ -41,7 +39,7 @@ public class AtUnitExample4 { return getWord().equals("are"); } @Test boolean scramble1() { - // Change to a specific seed to get verifiable results: + // Change to specific seed to get verifiable results: rand = new Random(47); System.out.println("'" + getWord() + "'"); String scrambled = scrambleWord(); @@ -55,7 +53,8 @@ public class AtUnitExample4 { System.out.println(scrambled); return scrambled.equals("tsaeborornussu"); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { System.out.println("starting"); OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitExample4.class"); @@ -64,17 +63,13 @@ public class AtUnitExample4 { /* Output: starting annotations.AtUnitExample4 - . words 'All' -(failed) + . scramble1 'All' +lAl + . scramble2 'brontosauruses' tsaeborornussu - . scramble1 'are' -rae -(failed) -(3 tests) + . words 'are' ->>> 2 FAILURES <<< - annotations.AtUnitExample4: words - annotations.AtUnitExample4: scramble1 +OK (3 tests) */ diff --git a/annotations/AtUnitExample5.java b/annotations/AtUnitExample5.java index 51e6d759..88370d68 100644 --- a/annotations/AtUnitExample5.java +++ b/annotations/AtUnitExample5.java @@ -40,7 +40,8 @@ public class AtUnitExample5 { output.print("test3"); return true; } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitExample5.class"); } diff --git a/annotations/AtUnitExternalTest.java b/annotations/AtUnitExternalTest.java index a1d8d4c3..2016e0db 100644 --- a/annotations/AtUnitExternalTest.java +++ b/annotations/AtUnitExternalTest.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating non-embedded tests. +// Creating non-embedded tests package annotations; import onjava.atunit.*; import onjava.*; @@ -12,7 +12,8 @@ public class AtUnitExternalTest extends AtUnitExample1 { return methodOne().equals("This is methodOne"); } @Test boolean _methodTwo() { return methodTwo() == 2; } - public static void main(String[] args) throws Exception{ + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit AtUnitExternalTest.class"); } diff --git a/annotations/HashSetTest.java b/annotations/HashSetTest.java index 4eddf105..3d72063f 100644 --- a/annotations/HashSetTest.java +++ b/annotations/HashSetTest.java @@ -21,7 +21,8 @@ public class HashSetTest { testObject.remove("one"); assert testObject.isEmpty(); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit HashSetTest.class"); } diff --git a/annotations/PasswordUtils.java b/annotations/PasswordUtils.java index 6272945b..46c17e0a 100644 --- a/annotations/PasswordUtils.java +++ b/annotations/PasswordUtils.java @@ -7,17 +7,17 @@ import java.util.*; public class PasswordUtils { @UseCase(id = 47, description = "Passwords must contain at least one numeric") - public boolean validatePassword(String password) { - return (password.matches("\\w*\\d\\w*")); + public boolean validatePassword(String passwd) { + return (passwd.matches("\\w*\\d\\w*")); } @UseCase(id = 48) - public String encryptPassword(String password) { - return new StringBuilder(password).reverse().toString(); + public String encryptPassword(String passwd) { + return new StringBuilder(passwd).reverse().toString(); } @UseCase(id = 49, description = "New passwords can't equal previously used ones") public boolean checkForNewPassword( - List prevPasswords, String password) { - return !prevPasswords.contains(password); + List prevPasswords, String passwd) { + return !prevPasswords.contains(passwd); } } diff --git a/annotations/StackL.java b/annotations/StackL.java index 33da5ab0..4ae80f9e 100644 --- a/annotations/StackL.java +++ b/annotations/StackL.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://mindviewinc.com/Books/OnJava/ for more book information. -// A stack built on a linkedList. +// A stack built on a linkedList package annotations; import java.util.*; diff --git a/annotations/StackLStringTest.java b/annotations/StackLStringTest.java index 64816ad4..364038e6 100644 --- a/annotations/StackLStringTest.java +++ b/annotations/StackLStringTest.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://mindviewinc.com/Books/OnJava/ for more book information. -// Applying @Unit to generics. +// Applying @Unit to generics package annotations; import onjava.atunit.*; import onjava.*; @@ -26,7 +26,8 @@ public class StackLStringTest extends StackL { assert top().equals("B"); assert top().equals("B"); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { OSExecute.command("java -cp .. " + "onjava.atunit.AtUnit StackLStringTest.class"); } diff --git a/annotations/UseCaseTracker.java b/annotations/UseCaseTracker.java index 12bcdbac..91da32e5 100644 --- a/annotations/UseCaseTracker.java +++ b/annotations/UseCaseTracker.java @@ -17,7 +17,8 @@ public class UseCaseTracker { } } for(int i : useCases) { - System.out.println("Warning: Missing use case-" + i); + System.out.println( + "Warning: Missing use case-" + i); } } public static void main(String[] args) { diff --git a/annotations/database/TableCreator.java b/annotations/database/TableCreator.java index a3116e6e..ebd70bdd 100644 --- a/annotations/database/TableCreator.java +++ b/annotations/database/TableCreator.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://mindviewinc.com/Books/OnJava/ for more book information. -// Reflection-based annotation processor. +// Reflection-based annotation processor // {Args: annotations.database.Member} package annotations.database; import java.lang.annotation.*; @@ -10,7 +10,8 @@ import java.lang.reflect.*; import java.util.*; public class TableCreator { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length < 1) { System.out.println("arguments: annotated classes"); System.exit(0); @@ -30,7 +31,8 @@ public class TableCreator { List columnDefs = new ArrayList<>(); for(Field field : cl.getDeclaredFields()) { String columnName = null; - Annotation[] anns = field.getDeclaredAnnotations(); + Annotation[] anns = + field.getDeclaredAnnotations(); if(anns.length < 1) continue; // Not a db table column if(anns[0] instanceof SQLInteger) { @@ -57,7 +59,8 @@ public class TableCreator { StringBuilder createCommand = new StringBuilder( "CREATE TABLE " + tableName + "("); for(String columnDef : columnDefs) - createCommand.append("\n " + columnDef + ","); + createCommand.append( + "\n " + columnDef + ","); // Remove trailing comma String tableCreate = createCommand.substring( 0, createCommand.length() - 1) + ");"; diff --git a/annotations/database/Uniqueness.java b/annotations/database/Uniqueness.java index 11843ea9..2ede0e41 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 3585af18..68c32038 100644 --- a/annotations/ifx/ExtractInterface.java +++ b/annotations/ifx/ExtractInterface.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://mindviewinc.com/Books/OnJava/ for more book information. -// javac-based annotation processing. +// javac-based annotation processing package annotations.ifx; import java.lang.annotation.*; diff --git a/annotations/ifx/IfaceExtractorProcessor.java b/annotations/ifx/IfaceExtractorProcessor.java index 1f579b38..a0e92df9 100644 --- a/annotations/ifx/IfaceExtractorProcessor.java +++ b/annotations/ifx/IfaceExtractorProcessor.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://mindviewinc.com/Books/OnJava/ for more book information. -// javac-based annotation processing. +// javac-based annotation processing package annotations.ifx; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; @@ -51,8 +51,8 @@ extends AbstractProcessor { private void writeInterfaceFile(String interfaceName) { try(Writer writer = processingEnv.getFiler() - .createSourceFile(interfaceName) - .openWriter()) { + .createSourceFile(interfaceName) + .openWriter()) { String packageName = elementUtils .getPackageOf(interfaceMethods .get(0)).toString(); diff --git a/annotations/ifx/Multiplier.java b/annotations/ifx/Multiplier.java index 59cc1a9a..d66270f2 100644 --- a/annotations/ifx/Multiplier.java +++ b/annotations/ifx/Multiplier.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://mindviewinc.com/Books/OnJava/ for more book information. -// javac-based annotation processing. +// javac-based annotation processing package annotations.ifx; @ExtractInterface(interfaceName="IMultiplier") diff --git a/annotations/simplest/Simple.java b/annotations/simplest/Simple.java index 5f9d13ec..7e1b8ce9 100644 --- a/annotations/simplest/Simple.java +++ b/annotations/simplest/Simple.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://mindviewinc.com/Books/OnJava/ for more book information. -// A bare-bones annotation. +// A bare-bones annotation package annotations.simplest; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/annotations/simplest/SimpleProcessor.java b/annotations/simplest/SimpleProcessor.java index 80c16129..b42f2d6e 100644 --- a/annotations/simplest/SimpleProcessor.java +++ b/annotations/simplest/SimpleProcessor.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://mindviewinc.com/Books/OnJava/ for more book information. -// A bare-bones annotation processor. +// A bare-bones annotation processor package annotations.simplest; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; diff --git a/arrays/AlphabeticSearch.java b/arrays/AlphabeticSearch.java index 104305a7..01c768c5 100644 --- a/arrays/AlphabeticSearch.java +++ b/arrays/AlphabeticSearch.java @@ -2,19 +2,20 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Searching with a Comparator. +// Searching with a Comparator import java.util.*; import onjava.*; +import static onjava.ArrayShow.*; public class AlphabeticSearch { public static void main(String[] args) { - String[] sa = Generated.array(new String[30], - new RandomSupplier.String(5)); + String[] sa = new Rand.String().array(30); Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER); - System.out.println(Arrays.toString(sa)); + show(sa); int index = Arrays.binarySearch(sa, sa[10], String.CASE_INSENSITIVE_ORDER); - System.out.println("Index: "+ index + "\n"+ sa[index]); + System.out.println( + "Index: "+ index + "\n"+ sa[index]); } } /* Output: diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java new file mode 100644 index 00000000..52fa0ff4 --- /dev/null +++ b/arrays/ArrayCopying.java @@ -0,0 +1,81 @@ +// arrays/ArrayCopying.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Demonstrate Arrays.copy() and Arrays.copyOf() +import java.util.*; +import onjava.*; +import static onjava.ArrayShow.*; + +class Sup { // Superclass + private int id; + public Sup(int n) { id = n; } + @Override + public String toString() { + return getClass().getSimpleName() + id; + } +} + +class Sub extends Sup { // Subclass + public Sub(int n) { super(n); } +} + +public class ArrayCopying { + public static final int SZ = 15; + public static void main(String[] args) { + int[] a1 = new int[SZ]; + Arrays.setAll(a1, new Count.Integer()::get); + show("a1", a1); + int[] a2 = Arrays.copyOf(a1, a1.length); // (1) + // 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) + 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) + Arrays.setAll(a3, new Count.Integer()::get); + Integer[] a4 = Arrays.copyOfRange(a3, 4, 12); + show("a4", a4); + + Sub[] d = new Sub[SZ/2]; + Arrays.setAll(d, Sub::new); + // Produce Sup[] from Sub[]: + Sup[] b = + Arrays.copyOf(d, d.length, Sup[].class); // (4) + show(b); + + // This "downcast" works fine: + Sub[] d2 = + Arrays.copyOf(b, b.length, Sub[].class); // (5) + show(d2); + + // Bad "downcast" compiles but throws exception: + Sup[] b2 = new Sup[SZ/2]; + Arrays.setAll(b2, Sup::new); + try { + Sub[] d3 = + Arrays.copyOf(b2, b2.length, Sub[].class); // (6) + } catch(Exception e) { + System.out.println(e); + } + } +} +/* Output: +a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] +a1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] +a2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] +a2 = [0, 1, 2, 3, 4, 5, 6] +a2 = [0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0] +a4 = [4, 5, 6, 7, 8, 9, 10, 11] +[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6] +[Sub0, Sub1, Sub2, Sub3, Sub4, Sub5, Sub6] +java.lang.ArrayStoreException +*/ diff --git a/arrays/ArrayOfGenericType.java b/arrays/ArrayOfGenericType.java index 394ed961..bd89ffdd 100644 --- a/arrays/ArrayOfGenericType.java +++ b/arrays/ArrayOfGenericType.java @@ -2,15 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Arrays of generic types won't compile. public class ArrayOfGenericType { T[] array; // OK @SuppressWarnings("unchecked") public ArrayOfGenericType(int size) { - //- array = new T[size]; // Illegal - array = (T[])new Object[size]; // "unchecked" Warning + // error: generic array creation: + // - array = new T[size]; + array = (T[])new Object[size]; // unchecked cast } - // Illegal: + // error: generic array creation: //- public U[] makeArray() { return new U[10]; } } diff --git a/arrays/ArrayOfGenerics.java b/arrays/ArrayOfGenerics.java index ea82ad44..b205e82b 100644 --- a/arrays/ArrayOfGenerics.java +++ b/arrays/ArrayOfGenerics.java @@ -2,7 +2,6 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// It is possible to create arrays of generics. import java.util.*; public class ArrayOfGenerics { @@ -10,10 +9,14 @@ public class ArrayOfGenerics { public static void main(String[] args) { List[] ls; List[] la = new List[10]; - ls = (List[])la; // "Unchecked" warning + ls = (List[])la; // Unchecked cast ls[0] = new ArrayList<>(); - // Compile-time checking produces an error: - //- ls[1] = new ArrayList(); + + // -ls[1] = new ArrayList(); + // error: incompatible types: ArrayList + // cannot be converted to List + // ls[1] = new ArrayList(); + // ^ // The problem: List is a subtype of Object Object[] objects = ls; // So assignment is OK @@ -22,10 +25,9 @@ public class ArrayOfGenerics { // However, if your needs are straightforward it is // possible to create an array of generics, albeit - // with an "unchecked" warning: + // with an "unchecked cast" warning: List[] spheres = (List[])new List[10]; - for(int i = 0; i < spheres.length; i++) - spheres[i] = new ArrayList<>(); + Arrays.setAll(spheres, n -> new ArrayList<>()); } } diff --git a/arrays/ArrayOptions.java b/arrays/ArrayOptions.java index 6906310e..2107cae9 100644 --- a/arrays/ArrayOptions.java +++ b/arrays/ArrayOptions.java @@ -2,8 +2,9 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Initialization & re-assignment of arrays. +// Initialization & re-assignment of arrays import java.util.*; +import static onjava.ArrayShow.*; public class ArrayOptions { public static void main(String[] args) { @@ -13,23 +14,25 @@ public class ArrayOptions { // The references inside the array are // automatically initialized to null: - System.out.println("b: " + Arrays.toString(b)); + show("b", b); BerylliumSphere[] c = new BerylliumSphere[4]; for(int i = 0; i < c.length; i++) if(c[i] == null) // Can test for null reference c[i] = new BerylliumSphere(); // Aggregate initialization: - BerylliumSphere[] d = { new BerylliumSphere(), - new BerylliumSphere(), new BerylliumSphere() + BerylliumSphere[] d = { + new BerylliumSphere(), + new BerylliumSphere(), + new BerylliumSphere() }; // Dynamic aggregate initialization: a = new BerylliumSphere[]{ new BerylliumSphere(), new BerylliumSphere(), }; + // (Trailing comma is optional) - // (Trailing comma is optional in both cases) System.out.println("a.length = " + a.length); System.out.println("b.length = " + b.length); System.out.println("c.length = " + c.length); @@ -43,14 +46,14 @@ public class ArrayOptions { // The primitives inside the array are // automatically initialized to zero: - System.out.println("f: " + Arrays.toString(f)); + show("f", f); int[] g = new int[4]; for(int i = 0; i < g.length; i++) g[i] = i*i; int[] h = { 11, 47, 93 }; // Compile error: variable e not initialized: - //- print("e.length = " + e.length); + //- System.out.println("e.length = " + e.length); System.out.println("f.length = " + f.length); System.out.println("g.length = " + g.length); System.out.println("h.length = " + h.length); diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java index c756bdcf..2868744b 100644 --- a/arrays/ArraySearching.java +++ b/arrays/ArraySearching.java @@ -2,35 +2,32 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using Arrays.binarySearch(). +// Using Arrays.binarySearch() import java.util.*; -import java.util.function.*; import onjava.*; +import static onjava.ArrayShow.*; public class ArraySearching { public static void main(String[] args) { - Supplier gen = - new RandomSupplier.Integer(1000); - int[] a = ConvertTo.primitive( - Generated.array(new Integer[25], gen)); + Rand.int_ rand = new Rand.int_(); + int[] a = new Rand.int_().array(25); Arrays.sort(a); - System.out.println( - "Sorted array: " + Arrays.toString(a)); + show("Sorted array", a); while(true) { - int r = gen.get(); + int r = rand.getAsInt(); int location = Arrays.binarySearch(a, r); if(location >= 0) { System.out.println( "Location of " + r + " is " + location + - ", a[" + location + "] = " + a[location]); + ", a[" + location + "] is " + a[location]); break; // Out of while loop } } } } /* Output: -Sorted array: [128, 140, 200, 207, 258, 258, 278, 288, 322, -429, 511, 520, 522, 551, 555, 589, 693, 704, 809, 861, 861, -868, 916, 961, 998] -Location of 322 is 8, a[8] = 322 +Sorted array: [125, 267, 635, 650, 1131, 1506, 1634, +2400, 2766, 3063, 3768, 3941, 4720, 4762, 4948, 5070, +5682, 5807, 6177, 6193, 6656, 7021, 8479, 8737, 9954] +Location of 635 is 2, a[2] is 635 */ diff --git a/arrays/AssemblingMultidimensionalArrays.java b/arrays/AssemblingMultidimensionalArrays.java index 96a5feeb..5667961f 100644 --- a/arrays/AssemblingMultidimensionalArrays.java +++ b/arrays/AssemblingMultidimensionalArrays.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating multidimensional arrays. +// Creating multidimensional arrays import java.util.*; public class AssemblingMultidimensionalArrays { diff --git a/arrays/BadMicroBenchmark.java b/arrays/BadMicroBenchmark.java new file mode 100644 index 00000000..765df060 --- /dev/null +++ b/arrays/BadMicroBenchmark.java @@ -0,0 +1,21 @@ +// arrays/BadMicroBenchmark.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import static onjava.TimeIt.*; + +public class BadMicroBenchmark { + static final int SIZE = 20_000_000; + public static void main(String[] args) { + long[] la = new long[SIZE]; + System.out.print("setAll: "); + timeIt(() -> Arrays.setAll(la, n -> n)); + System.out.print("parallelSetAll: "); + timeIt(() -> Arrays.parallelSetAll(la, n -> n)); + } +} +/* Output: +setAll: 27 +parallelSetAll: 53 +*/ diff --git a/arrays/BadMicroBenchmark2.java b/arrays/BadMicroBenchmark2.java new file mode 100644 index 00000000..b4db0700 --- /dev/null +++ b/arrays/BadMicroBenchmark2.java @@ -0,0 +1,22 @@ +// arrays/BadMicroBenchmark2.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Reversing the test order +import java.util.*; +import static onjava.TimeIt.*; + +public class BadMicroBenchmark2 { + static final int SIZE = 20_000_000; + public static void main(String[] args) { + long[] la = new long[SIZE]; + System.out.print("parallelSetAll: "); + timeIt(() -> Arrays.parallelSetAll(la, n -> n)); + System.out.print("setAll: "); + timeIt(() -> Arrays.setAll(la, n -> n)); + } +} +/* Output: +parallelSetAll: 38 +setAll: 63 +*/ diff --git a/arrays/BadMicroBenchmark3.java b/arrays/BadMicroBenchmark3.java new file mode 100644 index 00000000..aea7532c --- /dev/null +++ b/arrays/BadMicroBenchmark3.java @@ -0,0 +1,34 @@ +// arrays/BadMicroBenchmark3.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Relying on a common resource +import java.util.*; +import static onjava.TimeIt.*; + +public class BadMicroBenchmark3 { + static final int SIZE = 20_000_000; + public static void main(String[] args) { + long[] la = new long[SIZE]; + Random r = new Random(); + System.out.print("parallelSetAll: "); + timeIt(() -> + Arrays.parallelSetAll(la, n -> r.nextLong())); + System.out.print("setAll: "); + timeIt(() -> + Arrays.setAll(la, n -> r.nextLong())); + SplittableRandom sr = new SplittableRandom(); + System.out.print("parallelSetAll: "); + timeIt(() -> + Arrays.parallelSetAll(la, n -> sr.nextLong())); + System.out.print("setAll: "); + timeIt(() -> + Arrays.setAll(la, n -> sr.nextLong())); + } +} +/* Output: +parallelSetAll: 5150 +setAll: 649 +parallelSetAll: 277 +setAll: 246 +*/ diff --git a/arrays/CollectionComparison.java b/arrays/CollectionComparison.java index 6aa3abf1..51ae19ad 100644 --- a/arrays/CollectionComparison.java +++ b/arrays/CollectionComparison.java @@ -3,6 +3,8 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. import java.util.*; +import onjava.*; +import static onjava.ArrayShow.*; class BerylliumSphere { private static long counter; @@ -16,17 +18,16 @@ public class CollectionComparison { BerylliumSphere[] spheres = new BerylliumSphere[10]; for(int i = 0; i < 5; i++) spheres[i] = new BerylliumSphere(); - System.out.println(Arrays.toString(spheres)); + show(spheres); System.out.println(spheres[4]); - List sphereList= new ArrayList<>(); - for(int i = 0; i < 5; i++) - sphereList.add(new BerylliumSphere()); + List sphereList = Suppliers.create( + ArrayList::new, BerylliumSphere::new, 5); System.out.println(sphereList); System.out.println(sphereList.get(4)); int[] integers = { 0, 1, 2, 3, 4, 5 }; - System.out.println(Arrays.toString(integers)); + show(integers); System.out.println(integers[4]); List intList = new ArrayList<>( diff --git a/arrays/CompType.java b/arrays/CompType.java index 91546a2c..70a1587e 100644 --- a/arrays/CompType.java +++ b/arrays/CompType.java @@ -2,10 +2,11 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Implementing Comparable in a class. +// Implementing Comparable in a class import java.util.*; import java.util.function.*; import onjava.*; +import static onjava.ArrayShow.*; public class CompType implements Comparable { int i; @@ -26,19 +27,17 @@ public class CompType implements Comparable { public int compareTo(CompType rv) { return (i < rv.i ? -1 : (i == rv.i ? 0 : 1)); } - private static Random r = new Random(47); - public static Supplier generator() { - return () -> - new CompType(r.nextInt(100), r.nextInt(100)); + private static SplittableRandom r = + new SplittableRandom(47); + public static CompType get() { + return new CompType(r.nextInt(100), r.nextInt(100)); } public static void main(String[] args) { - CompType[] a = - Generated.array(new CompType[12], generator()); - System.out.println("before sorting:"); - System.out.println(Arrays.toString(a)); + CompType[] a = new CompType[12]; + Arrays.setAll(a, n -> get()); + show("Before sorting", a); Arrays.sort(a); - System.out.println("after sorting:"); - System.out.println(Arrays.toString(a)); + show("After sorting", a); } } /* Output: diff --git a/arrays/ComparatorTest.java b/arrays/ComparatorTest.java index 55de1102..85abb45a 100644 --- a/arrays/ComparatorTest.java +++ b/arrays/ComparatorTest.java @@ -2,9 +2,10 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Implementing a Comparator for a class. +// Implementing a Comparator for a class import java.util.*; import onjava.*; +import static onjava.ArrayShow.*; class CompTypeComparator implements Comparator { public int compare(CompType o1, CompType o2) { @@ -14,13 +15,11 @@ class CompTypeComparator implements Comparator { public class ComparatorTest { public static void main(String[] args) { - CompType[] a = Generated.array( - new CompType[12], CompType.generator()); - System.out.println("before sorting:"); - System.out.println(Arrays.toString(a)); + CompType[] a = new CompType[12]; + Arrays.setAll(a, n -> CompType.get()); + show("Before sorting", a); Arrays.sort(a, new CompTypeComparator()); - System.out.println("after sorting:"); - System.out.println(Arrays.toString(a)); + show("After sorting", a); } } /* Output: diff --git a/arrays/ComparingArrays.java b/arrays/ComparingArrays.java index e05b91ac..bbdcdfe3 100644 --- a/arrays/ComparingArrays.java +++ b/arrays/ComparingArrays.java @@ -4,25 +4,57 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using Arrays.equals() import java.util.*; +import onjava.*; public class ComparingArrays { + public static final int SZ = 15; + static String[][] TwoDArray() { + String[][] md = new String[5][]; + Arrays.setAll(md, n -> new String[n]); + for(int i = 0; i < md.length; i++) + Arrays.setAll(md[i], new Rand.String()::get); + return md; + } public static void main(String[] args) { - int[] a1 = new int[10]; - int[] a2 = new int[10]; - Arrays.fill(a1, 47); - Arrays.fill(a2, 47); - System.out.println(Arrays.equals(a1, a2)); + int[] a1 = new int[SZ], a2 = new int[SZ]; + Arrays.setAll(a1, new Count.Integer()::get); + Arrays.setAll(a2, new Count.Integer()::get); + System.out.println( + "a1 == a2: " + Arrays.equals(a1, a2)); a2[3] = 11; - System.out.println(Arrays.equals(a1, a2)); - String[] s1 = new String[4]; - Arrays.fill(s1, "Hi"); - String[] s2 = { new String("Hi"), new String("Hi"), - new String("Hi"), new String("Hi") }; - System.out.println(Arrays.equals(s1, s2)); + System.out.println( + "a1 == a2: " + Arrays.equals(a1, a2)); + + Integer[] a1w = new Integer[SZ], + a2w = new Integer[SZ]; + Arrays.setAll(a1w, new Count.Integer()::get); + Arrays.setAll(a2w, new Count.Integer()::get); + System.out.println( + "a1w == a2w: " + Arrays.equals(a1w, a2w)); + a2w[3] = 11; + System.out.println( + "a1w == a2w: " + Arrays.equals(a1w, a2w)); + + String[][] md1 = TwoDArray(), md2 = TwoDArray(); + System.out.println(Arrays.deepToString(md1)); + System.out.println("deepEquals(md1, md2): " + + Arrays.deepEquals(md1, md2)); + System.out.println( + "md1 == md2: " + Arrays.equals(md1, md2)); + md1[4][1] = "#$#$#$#"; + System.out.println(Arrays.deepToString(md1)); + System.out.println("deepEquals(md1, md2): " + + Arrays.deepEquals(md1, md2)); } } /* Output: -true -false -true +a1 == a2: true +a1 == a2: false +a1w == a2w: true +a1w == a2w: false +[[], [YNzbrny], [YNzbrny, GcFOWZn], [YNzbrny, GcFOWZn, TcQrGse], [YNzbrny, GcFOWZn, TcQrGse, GZMmJMR]] +deepEquals(md1, md2): true +md1 == md2: false +[[], [YNzbrny], [YNzbrny, GcFOWZn], [YNzbrny, GcFOWZn, TcQrGse], [YNzbrny, #$#$#$#, TcQrGse, GZMmJMR]] +deepEquals(md1, md2): false */ diff --git a/arrays/CopyingArrays.java b/arrays/CopyingArrays.java deleted file mode 100644 index 0df6cfa0..00000000 --- a/arrays/CopyingArrays.java +++ /dev/null @@ -1,45 +0,0 @@ -// arrays/CopyingArrays.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using System.arraycopy() -import java.util.*; - -public class CopyingArrays { - public static void main(String[] args) { - int[] i = new int[7]; - int[] j = new int[10]; - Arrays.fill(i, 47); - Arrays.fill(j, 99); - System.out.println("i = " + Arrays.toString(i)); - System.out.println("j = " + Arrays.toString(j)); - System.arraycopy(i, 0, j, 0, i.length); - System.out.println("j = " + Arrays.toString(j)); - int[] k = new int[5]; - Arrays.fill(k, 103); - System.arraycopy(i, 0, k, 0, k.length); - System.out.println("k = " + Arrays.toString(k)); - Arrays.fill(k, 103); - System.arraycopy(k, 0, i, 0, k.length); - System.out.println("i = " + Arrays.toString(i)); - // Objects: - Integer[] u = new Integer[10]; - Integer[] v = new Integer[5]; - Arrays.fill(u, 47); - Arrays.fill(v, 99); - System.out.println("u = " + Arrays.toString(u)); - System.out.println("v = " + Arrays.toString(v)); - System.arraycopy(v, 0, u, u.length/2, v.length); - System.out.println("u = " + Arrays.toString(u)); - } -} -/* Output: -i = [47, 47, 47, 47, 47, 47, 47] -j = [99, 99, 99, 99, 99, 99, 99, 99, 99, 99] -j = [47, 47, 47, 47, 47, 47, 47, 99, 99, 99] -k = [47, 47, 47, 47, 47] -i = [103, 103, 103, 103, 103, 47, 47] -u = [47, 47, 47, 47, 47, 47, 47, 47, 47, 47] -v = [99, 99, 99, 99, 99] -u = [47, 47, 47, 47, 47, 99, 99, 99, 99, 99] -*/ diff --git a/arrays/CountUpward.java b/arrays/CountUpward.java new file mode 100644 index 00000000..49099583 --- /dev/null +++ b/arrays/CountUpward.java @@ -0,0 +1,23 @@ +// arrays/CountUpward.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import java.util.stream.*; +import static onjava.ArrayShow.*; + +public class CountUpward { + static long[] fillCounted(int size) { + return LongStream.iterate(0, i -> i + 1) + .limit(size).toArray(); + } + public static void main(String[] args) { + long[] l1 = fillCounted(20); // No problem + show(l1); + // On my machine, this runs out of heap space: + //- long[] l2 = fillCounted(10_000_000); + } +} +/* Output: +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] +*/ diff --git a/arrays/FillingArrays.java b/arrays/FillingArrays.java index fb207675..9c27d832 100644 --- a/arrays/FillingArrays.java +++ b/arrays/FillingArrays.java @@ -4,6 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using Arrays.fill() import java.util.*; +import static onjava.ArrayShow.*; public class FillingArrays { public static void main(String[] args) { @@ -18,26 +19,26 @@ public class FillingArrays { double[] a8 = new double[size]; String[] a9 = new String[size]; Arrays.fill(a1, true); - System.out.println("a1 = " + Arrays.toString(a1)); + show("a1", a1); Arrays.fill(a2, (byte)11); - System.out.println("a2 = " + Arrays.toString(a2)); + show("a2", a2); Arrays.fill(a3, 'x'); - System.out.println("a3 = " + Arrays.toString(a3)); + show("a3", a3); Arrays.fill(a4, (short)17); - System.out.println("a4 = " + Arrays.toString(a4)); + show("a4", a4); Arrays.fill(a5, 19); - System.out.println("a5 = " + Arrays.toString(a5)); + show("a5", a5); Arrays.fill(a6, 23); - System.out.println("a6 = " + Arrays.toString(a6)); + show("a6", a6); Arrays.fill(a7, 29); - System.out.println("a7 = " + Arrays.toString(a7)); + show("a7", a7); Arrays.fill(a8, 47); - System.out.println("a8 = " + Arrays.toString(a8)); + show("a8", a8); Arrays.fill(a9, "Hello"); - System.out.println("a9 = " + Arrays.toString(a9)); + show("a9", a9); // Manipulating ranges: Arrays.fill(a9, 3, 5, "World"); - System.out.println("a9 = " + Arrays.toString(a9)); + show("a9", a9); } } /* Output: diff --git a/arrays/IceCream.java b/arrays/IceCream.java index 1ed9290b..7ee32d7b 100644 --- a/arrays/IceCream.java +++ b/arrays/IceCream.java @@ -2,11 +2,13 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Returning arrays from methods. +// Returning arrays from methods import java.util.*; +import static onjava.ArrayShow.*; public class IceCream { - private static Random rand = new Random(47); + private static SplittableRandom rand = + new SplittableRandom(47); static final String[] FLAVORS = { "Chocolate", "Strawberry", "Vanilla Fudge Swirl", "Mint Chip", "Mocha Almond Fudge", "Rum Raisin", @@ -29,7 +31,7 @@ public class IceCream { } public static void main(String[] args) { for(int i = 0; i < 7; i++) - System.out.println(Arrays.toString(flavorSet(3))); + show(flavorSet(3)); } } /* Output: diff --git a/arrays/ModifyExisting.java b/arrays/ModifyExisting.java new file mode 100644 index 00000000..3db997b1 --- /dev/null +++ b/arrays/ModifyExisting.java @@ -0,0 +1,21 @@ +// arrays/ModifyExisting.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import onjava.*; +import static onjava.ArrayShow.*; + +public class ModifyExisting { + public static void main(String[] args) { + double[] da = new double[7]; + Arrays.setAll(da, new Rand.Double()::get); + show(da); + Arrays.setAll(da, n -> da[n] / 100); // (1) + show(da); + } +} +/* Output: +[0.73, 0.53, 0.16, 0.19, 0.52, 0.27, 0.26] +[0.0073, 0.0053, 0.0016, 0.0019, 0.0052, 0.0027, 0.0026] +*/ diff --git a/arrays/MultiDimWrapperArray.java b/arrays/MultiDimWrapperArray.java index a0a5f78f..9c6c927a 100644 --- a/arrays/MultiDimWrapperArray.java +++ b/arrays/MultiDimWrapperArray.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://mindviewinc.com/Books/OnJava/ for more book information. -// Multidimensional arrays of "wrapper" objects. +// Multidimensional arrays of "wrapper" objects import java.util.*; public class MultiDimWrapperArray { diff --git a/arrays/MultidimensionalPrimitiveArray.java b/arrays/MultidimensionalPrimitiveArray.java index 4920a704..1162f60f 100644 --- a/arrays/MultidimensionalPrimitiveArray.java +++ b/arrays/MultidimensionalPrimitiveArray.java @@ -2,7 +2,6 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Creating multidimensional arrays. import java.util.*; public class MultidimensionalPrimitiveArray { diff --git a/arrays/ParallelPrefix.java b/arrays/ParallelPrefix.java new file mode 100644 index 00000000..104ebfdc --- /dev/null +++ b/arrays/ParallelPrefix.java @@ -0,0 +1,22 @@ +// arrays/ParallelPrefix.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; + +public class ParallelPrefix { + static final int SIZE = 20_000_000; + public static void main(String[] args) { + long[] nums = new long[SIZE]; + Arrays.setAll(nums, n -> n); + Arrays.parallelPrefix(nums, Long::sum); + System.out.println("First 20: " + nums[19]); + System.out.println("First 200: " + nums[199]); + System.out.println("All: " + nums[nums.length-1]); + } +} +/* Output: +First 20: 190 +First 200: 19900 +All: 199999990000000 +*/ diff --git a/arrays/ParallelSetAll.java b/arrays/ParallelSetAll.java new file mode 100644 index 00000000..c17a0225 --- /dev/null +++ b/arrays/ParallelSetAll.java @@ -0,0 +1,24 @@ +// arrays/ParallelSetAll.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import onjava.*; + +public class ParallelSetAll { + static final int SIZE = 20_000_000; + static void intArray() { + int[] ia = new int[SIZE]; + Arrays.setAll(ia, new Rand.int_()::get); + Arrays.parallelSetAll(ia, new Rand.int_()::get); + } + static void longArray() { + long[] la = new long[SIZE]; + Arrays.setAll(la, new Rand.long_()::get); + Arrays.parallelSetAll(la, new Rand.long_()::get); + } + public static void main(String[] args) { + intArray(); + longArray(); + } +} diff --git a/arrays/ParallelSort.java b/arrays/ParallelSort.java new file mode 100644 index 00000000..4b724c80 --- /dev/null +++ b/arrays/ParallelSort.java @@ -0,0 +1,26 @@ +// arrays/ParallelSort.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import java.time.*; +import onjava.*; +import static onjava.TimeIt.*; + +public class ParallelSort { + static final int SZ = 10_000_000; + public static void main(String[] args) { + int[] ia1 = new Rand.int_().array(SZ); + int[] ia2 = Arrays.copyOf(ia1, ia1.length); + System.out.print("sort(): "); + long millis1 = timeIt(() -> Arrays.sort(ia1)); + System.out.print("parallelSort(): "); + long millis2 = timeIt(() -> Arrays.parallelSort(ia2)); + System.out.println(millis1/millis2); + } +} +/* Output: +sort(): 484 +parallelSort(): 149 +3 +*/ diff --git a/arrays/Prefix1.java b/arrays/Prefix1.java new file mode 100644 index 00000000..fa3629a3 --- /dev/null +++ b/arrays/Prefix1.java @@ -0,0 +1,27 @@ +// arrays/Prefix1.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import onjava.*; +import static onjava.ArrayShow.*; + +public class Prefix1 { + public static void main(String[] args) { + int[] nums = new Count.int_().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)) + .reduce(Integer::sum).getAsInt()); + } +} +/* Output: +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +45 +[0, 1, 3, 6, 10, 15, 21, 28, 36, 45] +15 +*/ diff --git a/arrays/Prefix2.java b/arrays/Prefix2.java new file mode 100644 index 00000000..64548269 --- /dev/null +++ b/arrays/Prefix2.java @@ -0,0 +1,20 @@ +// arrays/Prefix2.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import onjava.*; +import static onjava.ArrayShow.*; + +public class Prefix2 { + public static void main(String[] args) { + String[] strings = new Rand.String(1).array(8); + show(strings); + Arrays.parallelPrefix(strings, (a, b) -> a + b); + show(strings); + } +} +/* Output: +[b, t, p, e, n, p, c, c] +[b, bt, btp, btpe, btpen, btpenp, btpenpc, btpenpcc] +*/ diff --git a/arrays/PrimitiveConversionDemonstration.java b/arrays/PrimitiveConversionDemonstration.java deleted file mode 100644 index 483c4445..00000000 --- a/arrays/PrimitiveConversionDemonstration.java +++ /dev/null @@ -1,23 +0,0 @@ -// arrays/PrimitiveConversionDemonstration.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.util.*; -import onjava.*; - -public class PrimitiveConversionDemonstration { - public static void main(String[] args) { - Integer[] a = Generated.array(Integer.class, - new CountingSupplier.Integer(), 15); - int[] b = ConvertTo.primitive(a); - System.out.println(Arrays.toString(b)); - boolean[] c = ConvertTo.primitive( - Generated.array(Boolean.class, - new CountingSupplier.Boolean(), 7)); - System.out.println(Arrays.toString(c)); - } -} -/* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -[true, false, true, false, true, false, true] -*/ diff --git a/arrays/PythonLists.py b/arrays/PythonLists.py index bec1e652..2d8ed47e 100644 --- a/arrays/PythonLists.py +++ b/arrays/PythonLists.py @@ -24,3 +24,13 @@ class MyList(list): # Inherit from list list2 = MyList(aList) print(type(list2)) # print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1] + +output = """ + +[1, 2, 3, 4, 5] +5 +[1, 2, 3, 4, 5, 6, 7, 8] +[3, 4] + +[8, 7, 6, 5, 4, 3, 2, 1] +""" diff --git a/arrays/RaggedArray.java b/arrays/RaggedArray.java index 31f0197c..78125295 100644 --- a/arrays/RaggedArray.java +++ b/arrays/RaggedArray.java @@ -5,20 +5,23 @@ import java.util.*; public class RaggedArray { + static int val = 1; public static void main(String[] args) { - Random rand = new Random(47); + SplittableRandom rand = new SplittableRandom(47); // 3-D array with varied-length vectors: int[][][] a = new int[rand.nextInt(7)][][]; for(int i = 0; i < a.length; i++) { a[i] = new int[rand.nextInt(5)][]; - for(int j = 0; j < a[i].length; j++) + for(int j = 0; j < a[i].length; j++) { a[i][j] = new int[rand.nextInt(5)]; + Arrays.setAll(a[i][j], n -> val++); // (1) + } } System.out.println(Arrays.deepToString(a)); } } /* Output: -[[], [[0], [0], [0, 0, 0, 0]], [[], [0, 0], [0, 0]], [[0, -0, 0], [0], [0, 0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0], []], -[[0], [], [0]]] +[[], [[1], [2], [3, 4, 5, 6]], [[], [7, 8], [9, 10]], +[[11, 12, 13], [14], [15, 16, 17, 18]], [[19, 20, 21], +[22, 23, 24], [25], []], [[26], [], [27]]] */ diff --git a/arrays/RandomSuppliersTest.java b/arrays/RandomSuppliersTest.java deleted file mode 100644 index 27d31ebb..00000000 --- a/arrays/RandomSuppliersTest.java +++ /dev/null @@ -1,25 +0,0 @@ -// arrays/RandomSuppliersTest.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import onjava.*; - -public class RandomSuppliersTest { - public static void main(String[] args) { - SuppliersTest.test(RandomSupplier.class); - } -} -/* Output: -Double: 0.73 0.53 0.16 0.19 0.52 0.27 0.26 0.05 0.8 0.76 -Float: 0.53 0.16 0.53 0.4 0.49 0.25 0.8 0.11 0.02 0.8 -Long: 7674 8804 8950 7826 4322 896 8033 2984 2344 5810 -Integer: 8303 3141 7138 6012 9966 8689 7185 6992 5746 3976 -Short: 3358 20592 284 26791 12834 -8092 13656 29324 -1423 -5327 -String: bkInaMe sbtWHkj UrUkZPg wsqPzDy CyRFJQA HxxHvHq -XumcXZJ oogoYWM NvqeuTp nXsgqia -Character: x x E A J J m z M s -Byte: -60 -17 55 -14 -5 115 39 -37 79 115 -Boolean: false true false false true true true true true -true -*/ diff --git a/arrays/Reverse.java b/arrays/Reverse.java index 8dfff4d7..729cf395 100644 --- a/arrays/Reverse.java +++ b/arrays/Reverse.java @@ -5,16 +5,15 @@ // The Collections.reverseOrder() Comparator import java.util.*; import onjava.*; +import static onjava.ArrayShow.*; public class Reverse { public static void main(String[] args) { - CompType[] a = Generated.array( - new CompType[12], CompType.generator()); - System.out.println("before sorting:"); - System.out.println(Arrays.toString(a)); + CompType[] a = new CompType[12]; + Arrays.setAll(a, n -> CompType.get()); + show("Before sorting", a); Arrays.sort(a, Collections.reverseOrder()); - System.out.println("after sorting:"); - System.out.println(Arrays.toString(a)); + show("After sorting", a); } } /* Output: diff --git a/arrays/SimpleSetAll.java b/arrays/SimpleSetAll.java new file mode 100644 index 00000000..698fc0c3 --- /dev/null +++ b/arrays/SimpleSetAll.java @@ -0,0 +1,56 @@ +// arrays/SimpleSetAll.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import static onjava.ArrayShow.*; + +class Bob { + final int id; + public Bob(int n) { id = n; } + @Override + public String toString() { return "Bob" + id; } +} + +public class SimpleSetAll { + public static final int SZ = 8; + public static int val = 1; + static char[] chars = "abcdefghijklmnopqrstuvwxyz" + .toCharArray(); + static char getChar(int n) { return chars[n]; } + public static void main(String[] args) { + int[] ia = new int[SZ]; + long[] la = new long[SZ]; + double[] da = new double[SZ]; + Arrays.setAll(ia, n -> n); // (1) + Arrays.setAll(la, n -> n); + Arrays.setAll(da, n -> n); + show(ia); + show(la); + show(da); + Arrays.setAll(ia, n -> val++); // (2) + Arrays.setAll(la, n -> val++); + Arrays.setAll(da, n -> val++); + show(ia); + show(la); + show(da); + + Bob[] ba = new Bob[SZ]; + Arrays.setAll(ba, Bob::new); // (3) + show(ba); + + Character[] ca = new Character[SZ]; + Arrays.setAll(ca, SimpleSetAll::getChar); // (4) + show(ca); + } +} +/* Output: +[0, 1, 2, 3, 4, 5, 6, 7] +[0, 1, 2, 3, 4, 5, 6, 7] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] +[1, 2, 3, 4, 5, 6, 7, 8] +[9, 10, 11, 12, 13, 14, 15, 16] +[17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0] +[Bob0, Bob1, Bob2, Bob3, Bob4, Bob5, Bob6, Bob7] +[a, b, c, d, e, f, g, h] +*/ diff --git a/arrays/StreamFromArray.java b/arrays/StreamFromArray.java new file mode 100644 index 00000000..9808bdaa --- /dev/null +++ b/arrays/StreamFromArray.java @@ -0,0 +1,51 @@ +// arrays/StreamFromArray.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import onjava.*; + +public class StreamFromArray { + public static void main(String[] args) { + String[] s = new Rand.String().array(10); + Arrays.stream(s) + .skip(3) + .limit(5) + .map(ss -> ss + "!") + .forEach(System.out::println); + + int[] ia = new Rand.int_().array(10); + Arrays.stream(ia) + .skip(3) + .limit(5) + .map(i -> i * 10) + .forEach(System.out::println); + + Arrays.stream(new long[10]); + Arrays.stream(new double[10]); + + // Only int, long and double work: + //- Arrays.stream(new boolean[10]); + //- Arrays.stream(new byte[10]); + //- Arrays.stream(new char[10]); + //- Arrays.stream(new short[10]); + //- Arrays.stream(new float[10]); + + // For the other types you must use wrapped arrays: + float[] fa = new Rand.float_().array(10); + Arrays.stream(ConvertTo.boxed(fa)); + Arrays.stream(new Rand.Float().array(10)); + } +} +/* Output: +eloztdv! +ewcippc! +ygpoalk! +ljlbynx! +taprwxz! +47200 +61770 +84790 +66560 +37680 +*/ diff --git a/arrays/StringSorting.java b/arrays/StringSorting.java index 965cb16e..bbdac6df 100644 --- a/arrays/StringSorting.java +++ b/arrays/StringSorting.java @@ -2,25 +2,21 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Sorting an array of Strings. +// Sorting an array of Strings import java.util.*; import onjava.*; +import static onjava.ArrayShow.*; public class StringSorting { public static void main(String[] args) { - String[] sa = Generated.array(new String[20], - new RandomSupplier.String(5)); - System.out.println( - "Before sort: " + Arrays.toString(sa)); + String[] sa = new Rand.String().array(20); + show("Before sort", sa); Arrays.sort(sa); - System.out.println( - "After sort: " + Arrays.toString(sa)); + show("After sort", sa); Arrays.sort(sa, Collections.reverseOrder()); - System.out.println( - "Reverse sort: " + Arrays.toString(sa)); + show("Reverse sort", sa); Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER); - System.out.println( - "Case-insensitive sort: " + Arrays.toString(sa)); + show("Case-insensitive sort", sa); } } /* Output: diff --git a/arrays/SuppliersTest.java b/arrays/SuppliersTest.java deleted file mode 100644 index 461c869d..00000000 --- a/arrays/SuppliersTest.java +++ /dev/null @@ -1,40 +0,0 @@ -// arrays/SuppliersTest.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.util.function.*; -import onjava.*; - -public class SuppliersTest { - public static int size = 10; - public static void test(Class surroundingClass) { - for(Class type : surroundingClass.getClasses()) { - System.out.print(type.getSimpleName() + ": "); - try { - Supplier g = (Supplier)type.newInstance(); - for(int i = 0; i < size; i++) - System.out.printf(g.get() + " "); - System.out.println(); - } catch(InstantiationException | - IllegalAccessException e) { - throw new RuntimeException(e); - } - } - } - public static void main(String[] args) { - test(CountingSupplier.class); - } -} -/* Output: -Double: 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 -Float: 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 -Long: 0 1 2 3 4 5 6 7 8 9 -Integer: 0 1 2 3 4 5 6 7 8 9 -Short: 0 1 2 3 4 5 6 7 8 9 -String: abcdefg hijklmn opqrstu vwxyzAB CDEFGHI JKLMNOP -QRSTUVW XYZabcd efghijk lmnopqr -Character: a b c d e f g h i j -Byte: 0 1 2 3 4 5 6 7 8 9 -Boolean: true false true false true false true false true -false -*/ diff --git a/arrays/TestArrayGeneration.java b/arrays/TestArrayGeneration.java deleted file mode 100644 index f9de72c5..00000000 --- a/arrays/TestArrayGeneration.java +++ /dev/null @@ -1,48 +0,0 @@ -// arrays/TestArrayGeneration.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Test the tools that use generators to fill arrays. -import java.util.*; -import onjava.*; - -public class TestArrayGeneration { - public static void main(String[] args) { - int size = 6; - boolean[] a1 = ConvertTo.primitive(Generated.array( - Boolean.class, new RandomSupplier.Boolean(), size)); - System.out.println("a1 = " + Arrays.toString(a1)); - byte[] a2 = ConvertTo.primitive(Generated.array( - Byte.class, new RandomSupplier.Byte(), size)); - System.out.println("a2 = " + Arrays.toString(a2)); - char[] a3 = ConvertTo.primitive(Generated.array( - Character.class, - new RandomSupplier.Character(), size)); - System.out.println("a3 = " + Arrays.toString(a3)); - short[] a4 = ConvertTo.primitive(Generated.array( - Short.class, new RandomSupplier.Short(), size)); - System.out.println("a4 = " + Arrays.toString(a4)); - int[] a5 = ConvertTo.primitive(Generated.array( - Integer.class, new RandomSupplier.Integer(), size)); - System.out.println("a5 = " + Arrays.toString(a5)); - long[] a6 = ConvertTo.primitive(Generated.array( - Long.class, new RandomSupplier.Long(), size)); - System.out.println("a6 = " + Arrays.toString(a6)); - float[] a7 = ConvertTo.primitive(Generated.array( - Float.class, new RandomSupplier.Float(), size)); - System.out.println("a7 = " + Arrays.toString(a7)); - double[] a8 = ConvertTo.primitive(Generated.array( - Double.class, new RandomSupplier.Double(), size)); - System.out.println("a8 = " + Arrays.toString(a8)); - } -} -/* Output: -a1 = [true, false, true, false, false, true] -a2 = [104, -79, -76, 126, 33, -64] -a3 = [Z, n, T, c, Q, r] -a4 = [-13408, 22612, 15401, 15161, -28466, -12603] -a5 = [7704, 7383, 7706, 575, 8410, 6342] -a6 = [7674, 8804, 8950, 7826, 4322, 896] -a7 = [0.01, 0.2, 0.4, 0.79, 0.27, 0.45] -a8 = [0.16, 0.87, 0.7, 0.66, 0.87, 0.59] -*/ diff --git a/arrays/TestConvertTo.java b/arrays/TestConvertTo.java new file mode 100644 index 00000000..1970be8b --- /dev/null +++ b/arrays/TestConvertTo.java @@ -0,0 +1,87 @@ +// arrays/TestConvertTo.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import onjava.*; +import static onjava.ArrayShow.*; +import static onjava.ConvertTo.*; + +public class TestConvertTo { + static final int size = 6; + public static void main(String[] args) { + 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]; + 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]; + 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]; + 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]; + 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]; + 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]; + 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]; + Arrays.setAll(a8, new Rand.Double()::get); + double[] a8p = primitive(a8); + show("a8p", a8p); + Double[] a8b = boxed(a8p); + show("a8b", a8b); + } +} +/* Output: +a1p: [true, false, true, true, true, false] +a1b: [true, false, true, true, true, false] +a2p: [123, 33, 101, 112, 33, 31] +a2b: [123, 33, 101, 112, 33, 31] +a3p: [b, t, p, e, n, p] +a3b: [b, t, p, e, n, p] +a4p: [635, 8737, 3941, 4720, 6177, 8479] +a4b: [635, 8737, 3941, 4720, 6177, 8479] +a5p: [635, 8737, 3941, 4720, 6177, 8479] +a5b: [635, 8737, 3941, 4720, 6177, 8479] +a6p: [6882, 3765, 692, 9575, 4439, 2638] +a6b: [6882, 3765, 692, 9575, 4439, 2638] +a7p: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18] +a7b: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18] +a8p: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18] +a8b: [4.83, 2.89, 2.9, 1.97, 3.01, 0.18] +*/ diff --git a/arrays/TestCount.java b/arrays/TestCount.java new file mode 100644 index 00000000..909f6fb1 --- /dev/null +++ b/arrays/TestCount.java @@ -0,0 +1,140 @@ +// arrays/TestCount.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Test counting generators +import java.util.*; +import java.util.stream.*; +import onjava.*; +import static onjava.ArrayShow.*; + +public class TestCount { + static final int SZ = 5; + public static void main(String[] args) { + System.out.println("Boolean"); + Boolean[] a1 = new Boolean[SZ]; + Arrays.setAll(a1, new Count.Boolean()::get); + show(a1); + show(Stream.generate(new Count.Boolean()) + .limit(SZ + 1).toArray()); + show(new Count.Boolean().array(SZ + 2)); + show(new Count.boolean_().array(SZ + 3)); + + System.out.println("Byte"); + Byte[] a2 = new Byte[SZ]; + Arrays.setAll(a2, new Count.Byte()::get); + show(a2); + show(Stream.generate(new Count.Byte()) + .limit(SZ + 1).toArray()); + show(new Count.Byte().array(SZ + 2)); + show(new Count.byte_().array(SZ + 3)); + + System.out.println("Character"); + Character[] a3 = new Character[SZ]; + Arrays.setAll(a3, new Count.Character()::get); + show(a3); + show(Stream.generate(new Count.Character()) + .limit(SZ + 1).toArray()); + show(new Count.Character().array(SZ + 2)); + show(new Count.char_().array(SZ + 3)); + + System.out.println("Short"); + Short[] a4 = new Short[SZ]; + Arrays.setAll(a4, new Count.Short()::get); + show(a4); + show(Stream.generate(new Count.Short()) + .limit(SZ + 1).toArray()); + show(new Count.Short().array(SZ + 2)); + show(new Count.short_().array(SZ + 3)); + + System.out.println("Integer"); + int[] a5 = new int[SZ]; + Arrays.setAll(a5, new Count.Integer()::get); + show(a5); + show(Stream.generate(new Count.Integer()) + .limit(SZ + 1).toArray()); + show(new Count.Integer().array(SZ + 2)); + a5 = IntStream.generate(new Count.int_()) + .limit(SZ + 1).toArray(); + show(a5); + show(new Count.int_().array(SZ + 3)); + + System.out.println("Long"); + long[] a6 = new long[SZ]; + Arrays.setAll(a6, new Count.Long()::get); + show(a6); + show(Stream.generate(new Count.Long()) + .limit(SZ + 1).toArray()); + show(new Count.Long().array(SZ + 2)); + a6 = LongStream.generate(new Count.long_()) + .limit(SZ + 1).toArray(); + show(a6); + show(new Count.long_().array(SZ + 3)); + + System.out.println("Float"); + Float[] a7 = new Float[SZ]; + Arrays.setAll(a7, new Count.Float()::get); + show(a7); + show(Stream.generate(new Count.Float()) + .limit(SZ + 1).toArray()); + show(new Count.Float().array(SZ + 2)); + show(new Count.float_().array(SZ + 3)); + + System.out.println("Double"); + double[] a8 = new double[SZ]; + Arrays.setAll(a8, new Count.Double()::get); + show(a8); + show(Stream.generate(new Count.Double()) + .limit(SZ + 1).toArray()); + show(new Count.Double().array(SZ + 2)); + a8 = DoubleStream.generate(new Count.double_()) + .limit(SZ + 1).toArray(); + show(a8); + show(new Count.double_().array(SZ + 3)); + } +} +/* Output: +Boolean +[false, true, false, true, false] +[false, true, false, true, false, true] +[false, true, false, true, false, true, false] +[false, true, false, true, false, true, false, true] +Byte +[0, 1, 2, 3, 4] +[0, 1, 2, 3, 4, 5] +[0, 1, 2, 3, 4, 5, 6] +[0, 1, 2, 3, 4, 5, 6, 7] +Character +[b, c, d, e, f] +[b, c, d, e, f, g] +[b, c, d, e, f, g, h] +[b, c, d, e, f, g, h, i] +Short +[0, 1, 2, 3, 4] +[0, 1, 2, 3, 4, 5] +[0, 1, 2, 3, 4, 5, 6] +[0, 1, 2, 3, 4, 5, 6, 7] +Integer +[0, 1, 2, 3, 4] +[0, 1, 2, 3, 4, 5] +[0, 1, 2, 3, 4, 5, 6] +[0, 1, 2, 3, 4, 5] +[0, 1, 2, 3, 4, 5, 6, 7] +Long +[0, 1, 2, 3, 4] +[0, 1, 2, 3, 4, 5] +[0, 1, 2, 3, 4, 5, 6] +[0, 1, 2, 3, 4, 5] +[0, 1, 2, 3, 4, 5, 6, 7] +Float +[0.0, 1.0, 2.0, 3.0, 4.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] +Double +[0.0, 1.0, 2.0, 3.0, 4.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0] +[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] +*/ diff --git a/arrays/TestGenerated.java b/arrays/TestGenerated.java deleted file mode 100644 index c957da5f..00000000 --- a/arrays/TestGenerated.java +++ /dev/null @@ -1,23 +0,0 @@ -// arrays/TestGenerated.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.util.*; -import onjava.*; - -public class TestGenerated { - public static void main(String[] args) { - Integer[] a = { 9, 8, 7, 6 }; - System.out.println(Arrays.toString(a)); - a = Generated.array(a, new CountingSupplier.Integer()); - System.out.println(Arrays.toString(a)); - Integer[] b = Generated.array(Integer.class, - new CountingSupplier.Integer(), 15); - System.out.println(Arrays.toString(b)); - } -} -/* Output: -[9, 8, 7, 6] -[0, 1, 2, 3] -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -*/ diff --git a/arrays/TestRand.java b/arrays/TestRand.java new file mode 100644 index 00000000..56ee188e --- /dev/null +++ b/arrays/TestRand.java @@ -0,0 +1,161 @@ +// arrays/TestRand.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Test random generators +import java.util.*; +import java.util.stream.*; +import onjava.*; +import static onjava.ArrayShow.*; + +public class TestRand { + static final int SZ = 5; + public static void main(String[] args) { + System.out.println("Boolean"); + Boolean[] a1 = new Boolean[SZ]; + Arrays.setAll(a1, new Rand.Boolean()::get); + show(a1); + show(Stream.generate(new Rand.Boolean()) + .limit(SZ + 1).toArray()); + show(new Rand.Boolean().array(SZ + 2)); + show(new Rand.boolean_().array(SZ + 3)); + + System.out.println("Byte"); + Byte[] a2 = new Byte[SZ]; + Arrays.setAll(a2, new Rand.Byte()::get); + show(a2); + show(Stream.generate(new Rand.Byte()) + .limit(SZ + 1).toArray()); + show(new Rand.Byte().array(SZ + 2)); + show(new Rand.byte_().array(SZ + 3)); + + System.out.println("Character"); + Character[] a3 = new Character[SZ]; + Arrays.setAll(a3, new Rand.Character()::get); + show(a3); + show(Stream.generate(new Rand.Character()) + .limit(SZ + 1).toArray()); + show(new Rand.Character().array(SZ + 2)); + show(new Rand.char_().array(SZ + 3)); + + System.out.println("Short"); + Short[] a4 = new Short[SZ]; + Arrays.setAll(a4, new Rand.Short()::get); + show(a4); + show(Stream.generate(new Rand.Short()) + .limit(SZ + 1).toArray()); + show(new Rand.Short().array(SZ + 2)); + show(new Rand.short_().array(SZ + 3)); + + System.out.println("Integer"); + int[] a5 = new int[SZ]; + Arrays.setAll(a5, new Rand.Integer()::get); + show(a5); + show(Stream.generate(new Rand.Integer()) + .limit(SZ + 1).toArray()); + show(new Rand.Integer().array(SZ + 2)); + a5 = IntStream.generate(new Rand.int_()) + .limit(SZ + 1).toArray(); + show(a5); + show(new Rand.int_().array(SZ + 3)); + + System.out.println("Long"); + long[] a6 = new long[SZ]; + Arrays.setAll(a6, new Rand.Long()::get); + show(a6); + show(Stream.generate(new Rand.Long()) + .limit(SZ + 1).toArray()); + show(new Rand.Long().array(SZ + 2)); + a6 = LongStream.generate(new Rand.long_()) + .limit(SZ + 1).toArray(); + show(a6); + show(new Rand.long_().array(SZ + 3)); + + System.out.println("Float"); + Float[] a7 = new Float[SZ]; + Arrays.setAll(a7, new Rand.Float()::get); + show(a7); + show(Stream.generate(new Rand.Float()) + .limit(SZ + 1).toArray()); + show(new Rand.Float().array(SZ + 2)); + show(new Rand.float_().array(SZ + 3)); + + System.out.println("Double"); + double[] a8 = new double[SZ]; + Arrays.setAll(a8, new Rand.Double()::get); + show(a8); + show(Stream.generate(new Rand.Double()) + .limit(SZ + 1).toArray()); + show(new Rand.Double().array(SZ + 2)); + a8 = DoubleStream.generate(new Rand.double_()) + .limit(SZ + 2).toArray(); + show(a8); + show(new Rand.double_().array(SZ + 3)); + + System.out.println("String"); + String[] s = new String[SZ - 1]; + Arrays.setAll(s, new Rand.String()::get); + show(s); + show(Stream.generate(new Rand.String()) + .limit(SZ).toArray()); + show(new Rand.String().array(SZ + 1)); + + Arrays.setAll(s, new Rand.String(4)::get); + show(s); + show(Stream.generate(new Rand.String(4)) + .limit(SZ).toArray()); + show(new Rand.String(4).array(SZ + 1)); + } +} +/* Output: +Boolean +[true, false, true, true, true] +[true, false, true, true, true, false] +[true, false, true, true, true, false, false] +[true, false, true, true, true, false, false, true] +Byte +[123, 33, 101, 112, 33] +[123, 33, 101, 112, 33, 31] +[123, 33, 101, 112, 33, 31, 0] +[123, 33, 101, 112, 33, 31, 0, -72] +Character +[b, t, p, e, n] +[b, t, p, e, n, p] +[b, t, p, e, n, p, c] +[b, t, p, e, n, p, c, c] +Short +[635, 8737, 3941, 4720, 6177] +[635, 8737, 3941, 4720, 6177, 8479] +[635, 8737, 3941, 4720, 6177, 8479, 6656] +[635, 8737, 3941, 4720, 6177, 8479, 6656, 3768] +Integer +[635, 8737, 3941, 4720, 6177] +[635, 8737, 3941, 4720, 6177, 8479] +[635, 8737, 3941, 4720, 6177, 8479, 6656] +[635, 8737, 3941, 4720, 6177, 8479] +[635, 8737, 3941, 4720, 6177, 8479, 6656, 3768] +Long +[6882, 3765, 692, 9575, 4439] +[6882, 3765, 692, 9575, 4439, 2638] +[6882, 3765, 692, 9575, 4439, 2638, 4011] +[6882, 3765, 692, 9575, 4439, 2638] +[6882, 3765, 692, 9575, 4439, 2638, 4011, 9610] +Float +[4.83, 2.89, 2.9, 1.97, 3.01] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99, 8.28] +Double +[4.83, 2.89, 2.9, 1.97, 3.01] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99] +[4.83, 2.89, 2.9, 1.97, 3.01, 0.18, 0.99, 8.28] +String +[btpenpc, cuxszgv, gmeinne, eloztdv] +[btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc] +[btpenpc, cuxszgv, gmeinne, eloztdv, ewcippc, ygpoalk] +[btpe, npcc, uxsz, gvgm] +[btpe, npcc, uxsz, gvgm, einn] +[btpe, npcc, uxsz, gvgm, einn, eelo] +*/ diff --git a/arrays/build.xml b/arrays/build.xml index 4aa4c976..97d2372d 100644 --- a/arrays/build.xml +++ b/arrays/build.xml @@ -8,59 +8,79 @@ + + + + - + + + + + - + + - + + - - - + + + + + + + - + + + + + - + + - + + - - - + + + diff --git a/assertions/Assert2.java b/assertions/Assert2.java index 03fd36ac..0549ede0 100644 --- a/assertions/Assert2.java +++ b/assertions/Assert2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Assert with an informative message +// Assert with an information-expression // {JVMArgs: -ea} // {ThrowsException} diff --git a/assertions/Queue.java b/assertions/Queue.java index 5708ef55..8d6b4356 100644 --- a/assertions/Queue.java +++ b/assertions/Queue.java @@ -2,8 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of Design by Contract (DbC) combined -// with white-box unit testing. +// Demonstration of Design by Contract (DbC) +// combined with white-box unit testing // (Install libraries from www.junit.org) import java.util.*; import org.junit.Test; @@ -24,7 +24,8 @@ public class Queue { } public Queue(int size) { data = new Object[size]; - assert invariant(); // Must be true after construction + // Must be true after construction: + assert invariant(); } public boolean empty() { return !wrapped && in == out; diff --git a/build.xml b/build.xml index 2c28e269..1cc30c7c 100644 --- a/build.xml +++ b/build.xml @@ -42,7 +42,7 @@ files/build.xml enums/build.xml annotations/build.xml - concurrency/build.xml + tasks/build.xml ui/build.xml swt/build.xml patterns/build.xml @@ -86,7 +86,7 @@ files/build.xml enums/build.xml annotations/build.xml - concurrency/build.xml + tasks/build.xml patterns/build.xml unittesting/build.xml assertions/build.xml diff --git a/collections/AdapterMethodIdiom.java b/collections/AdapterMethodIdiom.java index 17421236..5d7d4a27 100644 --- a/collections/AdapterMethodIdiom.java +++ b/collections/AdapterMethodIdiom.java @@ -3,17 +3,21 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // The "Adapter Method" idiom uses for-in -// with additional kinds of Iterables. +// with additional kinds of Iterables import java.util.*; class ReversibleArrayList extends ArrayList { - public ReversibleArrayList(Collection c) { super(c); } + public ReversibleArrayList(Collection c) { + super(c); + } public Iterable reversed() { return new Iterable() { public Iterator iterator() { return new Iterator() { int current = size() - 1; - public boolean hasNext() { return current > -1; } + public boolean hasNext() { + return current > -1; + } public T next() { return get(current--); } public void remove() { // Not implemented throw new UnsupportedOperationException(); diff --git a/collections/AddingGroups.java b/collections/AddingGroups.java index a124763b..9551639f 100644 --- a/collections/AddingGroups.java +++ b/collections/AddingGroups.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://mindviewinc.com/Books/OnJava/ for more book information. -// Adding groups of elements to Collection objects. +// Adding groups of elements to Collection objects import java.util.*; public class AddingGroups { @@ -16,9 +16,9 @@ public class AddingGroups { Collections.addAll(collection, 11, 12, 13, 14, 15); Collections.addAll(collection, moreInts); // Produces a list "backed by" an array: - List list = Arrays.asList(16, 17, 18, 19, 20); + List list = Arrays.asList(16,17,18,19,20); list.set(1, 99); // OK -- modify an element - // list.add(21); // Runtime error because the - // underlying array cannot be resized. + // list.add(21); // Runtime error; the underlying + // array cannot be resized. } } diff --git a/collections/ApplesAndOrangesWithGenerics.java b/collections/ApplesAndOrangesWithGenerics.java index c590888f..ee5db4f0 100644 --- a/collections/ApplesAndOrangesWithGenerics.java +++ b/collections/ApplesAndOrangesWithGenerics.java @@ -14,16 +14,10 @@ public class ApplesAndOrangesWithGenerics { for(Apple apple : apples) { System.out.println(apple.id()); } - // Using for-in: - for(Apple c : apples) - System.out.println(c.id()); } } /* Output: 0 1 2 -0 -1 -2 */ diff --git a/collections/ApplesAndOrangesWithoutGenerics.java b/collections/ApplesAndOrangesWithoutGenerics.java index 74b48b25..649dfbc4 100644 --- a/collections/ApplesAndOrangesWithoutGenerics.java +++ b/collections/ApplesAndOrangesWithoutGenerics.java @@ -20,7 +20,7 @@ public class ApplesAndOrangesWithoutGenerics { ArrayList apples = new ArrayList(); for(int i = 0; i < 3; i++) apples.add(new Apple()); - // Not prevented from adding an Orange to apples: + // No problem adding an Orange to apples: apples.add(new Orange()); for(Object apple : apples) { ((Apple) apple).id(); diff --git a/collections/AsListInference.java b/collections/AsListInference.java index 4ee116f2..1d47b3c5 100644 --- a/collections/AsListInference.java +++ b/collections/AsListInference.java @@ -2,7 +2,6 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Arrays.asList() makes its best guess about type. import java.util.*; class Snow {} @@ -16,21 +15,20 @@ public class AsListInference { public static void main(String[] args) { List snow1 = Arrays.asList( new Crusty(), new Slush(), new Powder()); + //- snow1.add(new Heavy()); // Exception - // Won't compile: - // List snow2 = Arrays.asList( - // new Light(), new Heavy()); - // Compiler says: - // found : java.util.List - // required: java.util.List + List snow2 = Arrays.asList( + new Light(), new Heavy()); + //- snow2.add(new Slush()); // Exception - // Collections.addAll() doesn't get confused: List snow3 = new ArrayList<>(); - Collections.addAll(snow3, new Light(), new Heavy()); + Collections.addAll(snow3, + new Light(), new Heavy(), new Powder()); + snow3.add(new Crusty()); - // Give a hint using an - // explicit type argument specification: + // Hint with explicit type argument specification: List snow4 = Arrays.asList( - new Light(), new Heavy()); + new Light(), new Heavy(), new Slush()); + //- snow4.add(new Powder()); // Exception } } diff --git a/collections/CrossCollectionIteration2.java b/collections/CrossCollectionIteration2.java new file mode 100644 index 00000000..8eb85f07 --- /dev/null +++ b/collections/CrossCollectionIteration2.java @@ -0,0 +1,33 @@ +// collections/CrossCollectionIteration2.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import typeinfo.pets.*; +import java.util.*; + +public class CrossCollectionIteration2 { + public static void display(Iterable ip) { + Iterator it = ip.iterator(); + while(it.hasNext()) { + Pet p = it.next(); + System.out.print(p.id() + ":" + p + " "); + } + System.out.println(); + } + public static void main(String[] args) { + List pets = Pets.list(8); + LinkedList petsLL = new LinkedList<>(pets); + HashSet petsHS = new HashSet<>(pets); + TreeSet petsTS = new TreeSet<>(pets); + display(pets); + display(petsLL); + display(petsHS); + display(petsTS); + } +} +/* Output: +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx +5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat +*/ diff --git a/collections/ForInCollections.java b/collections/ForInCollections.java index 56377dd7..b37f1766 100644 --- a/collections/ForInCollections.java +++ b/collections/ForInCollections.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://mindviewinc.com/Books/OnJava/ for more book information. -// All collections work with for-in. +// All collections work with for-in import java.util.*; public class ForInCollections { diff --git a/collections/GenericsAndUpcasting.java b/collections/GenericsAndUpcasting.java index 746f7782..37853d37 100644 --- a/collections/GenericsAndUpcasting.java +++ b/collections/GenericsAndUpcasting.java @@ -16,8 +16,8 @@ public class GenericsAndUpcasting { apples.add(new Gala()); apples.add(new Fuji()); apples.add(new Braeburn()); - for(Apple c : apples) - System.out.println(c); + for(Apple apple : apples) + System.out.println(apple); } } /* Output: diff --git a/collections/IterableClass.java b/collections/IterableClass.java index 66556051..8f1d43fa 100644 --- a/collections/IterableClass.java +++ b/collections/IterableClass.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://mindviewinc.com/Books/OnJava/ for more book information. -// Anything Iterable works with for-in. +// Anything Iterable works with for-in import java.util.*; public class IterableClass implements Iterable { diff --git a/collections/ListFeatures.java b/collections/ListFeatures.java index a273c1ff..68c32664 100644 --- a/collections/ListFeatures.java +++ b/collections/ListFeatures.java @@ -16,7 +16,8 @@ public class ListFeatures { System.out.println("3: " + pets.contains(h)); pets.remove(h); // Remove by object Pet p = pets.get(2); - System.out.println("4: " + p + " " + pets.indexOf(p)); + System.out.println( + "4: " + p + " " + pets.indexOf(p)); Pet cymric = new Cymric(); System.out.println("5: " + pets.indexOf(cymric)); System.out.println("6: " + pets.remove(cymric)); diff --git a/collections/MapOfList.java b/collections/MapOfList.java index 3173efa8..c4ea6f0e 100644 --- a/collections/MapOfList.java +++ b/collections/MapOfList.java @@ -11,7 +11,9 @@ public class MapOfList { petPeople = new HashMap<>(); static { petPeople.put(new Person("Dawn"), - Arrays.asList(new Cymric("Molly"), new Mutt("Spot"))); + Arrays.asList( + new Cymric("Molly"), + new Mutt("Spot"))); petPeople.put(new Person("Kate"), Arrays.asList(new Cat("Shackleton"), new Cat("Elsie May"), new Dog("Margrett"))); diff --git a/collections/MultiIterableClass.java b/collections/MultiIterableClass.java index 1edef3c2..00f4245f 100644 --- a/collections/MultiIterableClass.java +++ b/collections/MultiIterableClass.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://mindviewinc.com/Books/OnJava/ for more book information. -// Adding several Adapter Methods. +// Adding several Adapter Methods import java.util.*; public class MultiIterableClass extends IterableClass { @@ -11,8 +11,12 @@ public class MultiIterableClass extends IterableClass { public Iterator iterator() { return new Iterator() { int current = words.length - 1; - public boolean hasNext() { return current > -1; } - public String next() { return words[current--]; } + public boolean hasNext() { + return current > -1; + } + public String next() { + return words[current--]; + } public void remove() { // Not implemented throw new UnsupportedOperationException(); } diff --git a/collections/NonCollectionSequence.java b/collections/NonCollectionSequence.java index f7269278..5ca490cf 100644 --- a/collections/NonCollectionSequence.java +++ b/collections/NonCollectionSequence.java @@ -26,7 +26,8 @@ public class NonCollectionSequence extends PetSequence { }; } public static void main(String[] args) { - NonCollectionSequence nc = new NonCollectionSequence(); + NonCollectionSequence nc = + new NonCollectionSequence(); InterfaceVsIterator.display(nc.iterator()); } } diff --git a/collections/PrintingCollections.java b/collections/PrintingCollections.java index 9d1f39a8..c5d75af4 100644 --- a/collections/PrintingCollections.java +++ b/collections/PrintingCollections.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://mindviewinc.com/Books/OnJava/ for more book information. -// Collections print themselves automatically. +// Collections print themselves automatically import java.util.*; public class PrintingCollections { diff --git a/collections/QueueDemo.java b/collections/QueueDemo.java index 972c3174..066decc2 100644 --- a/collections/QueueDemo.java +++ b/collections/QueueDemo.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://mindviewinc.com/Books/OnJava/ for more book information. -// Upcasting to a Queue from a LinkedList. +// Upcasting to a Queue from a LinkedList import java.util.*; public class QueueDemo { diff --git a/collections/SetOfString.java b/collections/SetOfString.java new file mode 100644 index 00000000..4d0201b8 --- /dev/null +++ b/collections/SetOfString.java @@ -0,0 +1,25 @@ +// collections/SetOfString.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; + +public class SetOfString { + public static void main(String[] args) { + Set colors = new HashSet<>(); + for(int i = 0; i < 100; i++) { + colors.add("Yellow"); + colors.add("Blue"); + colors.add("Red"); + colors.add("Red"); + colors.add("Orange"); + colors.add("Yellow"); + colors.add("Blue"); + colors.add("Purple"); + } + System.out.println(colors); + } +} +/* Output: +[Red, Yellow, Blue, Purple, Orange] +*/ diff --git a/collections/SortedSetOfInteger.java b/collections/SortedSetOfInteger.java deleted file mode 100644 index 566d1219..00000000 --- a/collections/SortedSetOfInteger.java +++ /dev/null @@ -1,19 +0,0 @@ -// collections/SortedSetOfInteger.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.util.*; - -public class SortedSetOfInteger { - public static void main(String[] args) { - Random rand = new Random(47); - SortedSet intset = new TreeSet<>(); - for(int i = 0; i < 10000; i++) - intset.add(rand.nextInt(30)); - System.out.println(intset); - } -} -/* Output: -[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] -*/ diff --git a/collections/SortedSetOfString.java b/collections/SortedSetOfString.java new file mode 100644 index 00000000..139a7469 --- /dev/null +++ b/collections/SortedSetOfString.java @@ -0,0 +1,25 @@ +// collections/SortedSetOfString.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; + +public class SortedSetOfString { + public static void main(String[] args) { + Set colors = new TreeSet<>(); + for(int i = 0; i < 100; i++) { + colors.add("Yellow"); + colors.add("Blue"); + colors.add("Red"); + colors.add("Red"); + colors.add("Orange"); + colors.add("Yellow"); + colors.add("Blue"); + colors.add("Purple"); + } + System.out.println(colors); + } +} +/* Output: +[Blue, Orange, Purple, Red, Yellow] +*/ diff --git a/collections/Statistics.java b/collections/Statistics.java index e3069fe9..862b17d0 100644 --- a/collections/Statistics.java +++ b/collections/Statistics.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple demonstration of HashMap. +// Simple demonstration of HashMap import java.util.*; public class Statistics { @@ -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); + Integer freq = m.get(r); // (1) m.put(r, freq == null ? 1 : freq + 1); } System.out.println(m); diff --git a/collections/UniqueWords.java b/collections/UniqueWords.java index 6fefd9cd..f8c3b096 100644 --- a/collections/UniqueWords.java +++ b/collections/UniqueWords.java @@ -6,7 +6,8 @@ import java.util.*; import java.nio.file.*; public class UniqueWords { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { List lines = Files.readAllLines(Paths.get("SetOperations.java")); Set words = new TreeSet<>(); diff --git a/collections/UniqueWordsAlphabetic.java b/collections/UniqueWordsAlphabetic.java index 0839ab24..584fa650 100644 --- a/collections/UniqueWordsAlphabetic.java +++ b/collections/UniqueWordsAlphabetic.java @@ -2,12 +2,13 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Producing an alphabetic listing. +// Producing an alphabetic listing import java.util.*; import java.nio.file.*; public class UniqueWordsAlphabetic { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { List lines = Files.readAllLines(Paths.get("SetOperations.java")); Set words = diff --git a/collections/build.xml b/collections/build.xml index 31b27a9f..b5ffcc1a 100644 --- a/collections/build.xml +++ b/collections/build.xml @@ -16,6 +16,7 @@ + @@ -33,10 +34,11 @@ + - + @@ -54,6 +56,7 @@ + @@ -71,10 +74,11 @@ + - + diff --git a/collectionsindepth/AssociativeArray.java b/collectionsindepth/AssociativeArray.java index 60b2d68c..cbc7448b 100644 --- a/collectionsindepth/AssociativeArray.java +++ b/collectionsindepth/AssociativeArray.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://mindviewinc.com/Books/OnJava/ for more book information. -// Associates keys with values. +// Associates keys with values public class AssociativeArray { private Object[][] pairs; diff --git a/collectionsindepth/Bits.java b/collectionsindepth/Bits.java index 9160be29..e51b836b 100644 --- a/collectionsindepth/Bits.java +++ b/collectionsindepth/Bits.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of BitSet. +// Demonstration of BitSet import java.util.*; public class Bits { @@ -14,7 +14,7 @@ public class Bits { System.out.println("bit pattern: " + bbits); } public static void main(String[] args) { - Random rand = new Random(47); + SplittableRandom rand = new SplittableRandom(47); // Take the LSB of nextInt(): byte bt = (byte)rand.nextInt(); BitSet bb = new BitSet(); diff --git a/collectionsindepth/CanonicalMapping.java b/collectionsindepth/CanonicalMapping.java index b59065bf..a1b241ac 100644 --- a/collectionsindepth/CanonicalMapping.java +++ b/collectionsindepth/CanonicalMapping.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates WeakHashMap. +// Demonstrates WeakHashMap import java.util.*; class Element { diff --git a/collectionsindepth/CollectionMethods.java b/collectionsindepth/CollectionMethods.java index 8e3f1314..a25e4358 100644 --- a/collectionsindepth/CollectionMethods.java +++ b/collectionsindepth/CollectionMethods.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://mindviewinc.com/Books/OnJava/ for more book information. -// Things you can do with all Collections. +// Things you can do with all Collections import java.util.*; import onjava.*; diff --git a/collectionsindepth/CountedString.java b/collectionsindepth/CountedString.java index 973563ff..8c1bb480 100644 --- a/collectionsindepth/CountedString.java +++ b/collectionsindepth/CountedString.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating a good hashCode(). +// Creating a good hashCode() import java.util.*; public class CountedString { diff --git a/collectionsindepth/Enumerations.java b/collectionsindepth/Enumerations.java index 3d3bd9a3..531ae0a4 100644 --- a/collectionsindepth/Enumerations.java +++ b/collectionsindepth/Enumerations.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://mindviewinc.com/Books/OnJava/ for more book information. -// Java 1.0/1.1 Vector and Enumeration. +// Java 1.0/1.1 Vector and Enumeration import java.util.*; import onjava.*; diff --git a/collectionsindepth/FailFast.java b/collectionsindepth/FailFast.java index 5327d5bb..60a4244c 100644 --- a/collectionsindepth/FailFast.java +++ b/collectionsindepth/FailFast.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the "fail-fast" behavior. +// Demonstrates the "fail-fast" behavior import java.util.*; public class FailFast { diff --git a/collectionsindepth/CollectionDataGeneration.java b/collectionsindepth/FilledCollectionGeneration.java similarity index 62% rename from collectionsindepth/CollectionDataGeneration.java rename to collectionsindepth/FilledCollectionGeneration.java index d2de41a4..22458de9 100644 --- a/collectionsindepth/CollectionDataGeneration.java +++ b/collectionsindepth/FilledCollectionGeneration.java @@ -1,19 +1,19 @@ -// collectionsindepth/CollectionDataGeneration.java +// collectionsindepth/FilledCollectionGeneration.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using the Suppliers defined in the Arrays chapter. +// Using the Suppliers defined in the Arrays chapter import java.util.*; import onjava.*; -public class CollectionDataGeneration { +public class FilledCollectionGeneration { public static void main(String[] args) { System.out.println(new ArrayList<>( - CollectionData.list( // Convenience method - new RandomSupplier.String(9), 10))); + FilledCollection.list( // Convenience method + new Rand.String(9), 10))); System.out.println(new HashSet<>( - new CollectionData<>( - new RandomSupplier.Integer(), 10))); + new FilledCollection<>( + new Rand.Integer(), 10))); } } /* Output: diff --git a/collectionsindepth/CollectionDataTest.java b/collectionsindepth/FilledCollectionTest.java similarity index 79% rename from collectionsindepth/CollectionDataTest.java rename to collectionsindepth/FilledCollectionTest.java index aa43e53e..4f707b4f 100644 --- a/collectionsindepth/CollectionDataTest.java +++ b/collectionsindepth/FilledCollectionTest.java @@ -1,4 +1,4 @@ -// collectionsindepth/CollectionDataTest.java +// collectionsindepth/FilledCollectionTest.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -15,12 +15,13 @@ class Government implements Supplier { public String get() { return foundation[index++]; } } -public class CollectionDataTest { +public class FilledCollectionTest { public static void main(String[] args) { Set set = new LinkedHashSet<>( - new CollectionData<>(new Government(), 15)); + new FilledCollection<>(new Government(), 15)); // Using the convenience method: - set.addAll(CollectionData.list(new Government(), 15)); + set.addAll( + FilledCollection.list(new Government(), 15)); System.out.println(set); } } diff --git a/collectionsindepth/FillingLists.java b/collectionsindepth/FillingLists.java index 913dd7a2..37f7b1bd 100644 --- a/collectionsindepth/FillingLists.java +++ b/collectionsindepth/FillingLists.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://mindviewinc.com/Books/OnJava/ for more book information. -// The Collections.fill() & Collections.nCopies() methods. +// The Collections.fill() & Collections.nCopies() methods import java.util.*; class StringAddress { diff --git a/collectionsindepth/Groundhog.java b/collectionsindepth/Groundhog.java index b6b637ee..2b0f5a4c 100644 --- a/collectionsindepth/Groundhog.java +++ b/collectionsindepth/Groundhog.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://mindviewinc.com/Books/OnJava/ for more book information. -// Looks plausible, but doesn't work as a HashMap key. +// Looks plausible, but doesn't work as a HashMap key public class Groundhog { protected int number; diff --git a/collectionsindepth/Groundhog2.java b/collectionsindepth/Groundhog2.java index d84bbbfe..256e0768 100644 --- a/collectionsindepth/Groundhog2.java +++ b/collectionsindepth/Groundhog2.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // A class that's used as a key in a HashMap -// must override hashCode() and equals(). +// must override hashCode() and equals() public class Groundhog2 extends Groundhog { public Groundhog2(int n) { super(n); } diff --git a/collectionsindepth/LinkedHashMapDemo.java b/collectionsindepth/LinkedHashMapDemo.java index f70325ef..16441751 100644 --- a/collectionsindepth/LinkedHashMapDemo.java +++ b/collectionsindepth/LinkedHashMapDemo.java @@ -2,18 +2,18 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// What you can do with a LinkedHashMap. +// What you can do with a LinkedHashMap import java.util.*; import onjava.*; public class LinkedHashMapDemo { public static void main(String[] args) { LinkedHashMap linkedMap = - new LinkedHashMap<>(new CountingMapData(9)); + new LinkedHashMap<>(new CountingFilledMap(9)); System.out.println(linkedMap); // Least-recently-used order: linkedMap = new LinkedHashMap<>(16, 0.75f, true); - linkedMap.putAll(new CountingMapData(9)); + linkedMap.putAll(new CountingFilledMap(9)); System.out.println(linkedMap); for(int i = 0; i < 6; i++) // Cause accesses: linkedMap.get(i); diff --git a/collectionsindepth/ListPerformance.java b/collectionsindepth/ListPerformance.java index 45cad994..51e37eef 100644 --- a/collectionsindepth/ListPerformance.java +++ b/collectionsindepth/ListPerformance.java @@ -2,13 +2,13 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates performance differences in Lists. +// Demonstrates performance differences in Lists // {Args: 100 500} Small to keep build testing short import java.util.*; import onjava.*; public class ListPerformance { - static Random rand = new Random(); + static SplittableRandom rand = new SplittableRandom(); static int reps = 1000; static List>> tests = new ArrayList<>(); @@ -53,7 +53,8 @@ public class ListPerformance { int test(List list, TestParam tp) { final int LOOPS = 1000000; int half = list.size() / 2; - ListIterator it = list.listIterator(half); + ListIterator it = + list.listIterator(half); for(int i = 0; i < LOOPS; i++) it.add(47); return LOOPS; @@ -145,7 +146,8 @@ public class ListPerformance { super(collection, tests); } // Fill to the appropriate size before each test: - @Override protected List initialize(int size){ + @Override + protected List initialize(int size) { collection.clear(); collection.addAll(new CountingIntegerList(size)); return collection; @@ -161,13 +163,14 @@ public class ListPerformance { Tester.defaultParams = TestParam.array(args); // Can only do these two tests on an array: Tester> arrayTest = - new Tester>(null, tests.subList(1, 3)){ + new Tester>(null, + tests.subList(1, 3)) { // This is called before each test. It // produces a non-resizeable array-backed list: @Override protected List initialize(int size) { - Integer[] ia = Generated.array(Integer.class, - new CountingSupplier.Integer(), size); + Integer[] ia = new Integer[size]; + Arrays.setAll(ia, new Count.Integer()::get); return Arrays.asList(ia); } }; diff --git a/collectionsindepth/ListSortSearch.java b/collectionsindepth/ListSortSearch.java index f84807e8..5811de41 100644 --- a/collectionsindepth/ListSortSearch.java +++ b/collectionsindepth/ListSortSearch.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://mindviewinc.com/Books/OnJava/ for more book information. -// Sorting and searching Lists with Collections utilities. +// Sorting and searching Lists with Collections utilities import java.util.*; public class ListSortSearch { @@ -28,7 +28,8 @@ public class ListSortSearch { "Location of " + key + " is " + index + ", list.get(" + index + ") = " + list.get(index)); Collections.sort(list, String.CASE_INSENSITIVE_ORDER); - System.out.println("Case-insensitive sorted: " + list); + System.out.println( + "Case-insensitive sorted: " + list); key = list.get(7); index = Collections.binarySearch(list, key, String.CASE_INSENSITIVE_ORDER); diff --git a/collectionsindepth/Lists.java b/collectionsindepth/Lists.java index 4fb8ba17..5cf731ac 100644 --- a/collectionsindepth/Lists.java +++ b/collectionsindepth/Lists.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://mindviewinc.com/Books/OnJava/ for more book information. -// Things you can do with Lists. +// Things you can do with Lists import java.util.*; import onjava.*; diff --git a/collectionsindepth/MapDataTest.java b/collectionsindepth/MapDataTest.java deleted file mode 100644 index 403c9240..00000000 --- a/collectionsindepth/MapDataTest.java +++ /dev/null @@ -1,58 +0,0 @@ -// collectionsindepth/MapDataTest.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.util.*; -import java.util.function.*; -import onjava.*; - -class Letters implements Supplier>, - Iterable { - private int size = 9; - private int number = 1; - private char letter = 'A'; - @Override - public Pair get() { - return new Pair<>(number++, "" + letter++); - } - @Override - public Iterator iterator() { - return new Iterator() { - @Override - public Integer next() { return number++; } - @Override - public boolean hasNext() { return number < size; } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } -} - -public class MapDataTest { - public static void main(String[] args) { - // Pair Supplier: - System.out.println(MapData.map(new Letters(), 11)); - // Two separate generators: - System.out.println( - MapData.map(new CountingSupplier.Character(), - new RandomSupplier.String(3), 8)); - // A key Supplier and a single value: - System.out.println( - MapData.map(new CountingSupplier.Character(), - "Value", 6)); - // An Iterable and a value Supplier: - System.out.println(MapData.map(new Letters(), - new RandomSupplier.String(3))); - // An Iterable and a single value: - System.out.println(MapData.map(new Letters(), "Pop")); - } -} -/* Output: -{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, 11=K} -{a=YNz, b=brn, c=yGc, d=FOW, e=ZnT, f=cQr, g=Gse, h=GZM} -{a=Value, b=Value, c=Value, d=Value, e=Value, f=Value} -{1=mJM, 2=RoE, 3=suE, 4=cUO, 5=neO, 6=EdL, 7=smw, 8=HLG} -{1=Pop, 2=Pop, 3=Pop, 4=Pop, 5=Pop, 6=Pop, 7=Pop, 8=Pop} -*/ diff --git a/collectionsindepth/MapEntry.java b/collectionsindepth/MapEntry.java index 9634d9f8..c14712c7 100644 --- a/collectionsindepth/MapEntry.java +++ b/collectionsindepth/MapEntry.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://mindviewinc.com/Books/OnJava/ for more book information. -// A simple Map.Entry for sample Map implementations. +// A simple Map.Entry for sample Map implementations import java.util.*; public class MapEntry implements Map.Entry { @@ -33,10 +33,11 @@ public class MapEntry implements Map.Entry { @SuppressWarnings("unchecked") MapEntry me = (MapEntry)o; return - (key == null ? - me.getKey() == null : key.equals(me.getKey())) && - (value == null ? - me.getValue()== null : value.equals(me.getValue())); + (key == null ? me.getKey() == null : + key.equals(me.getKey())) + && + (value == null ? me.getValue() == null : + value.equals(me.getValue())); } @Override public String toString() { return key + "=" + value; } diff --git a/collectionsindepth/MapPerformance.java b/collectionsindepth/MapPerformance.java index b7b647de..02aca5d7 100644 --- a/collectionsindepth/MapPerformance.java +++ b/collectionsindepth/MapPerformance.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates performance differences in Maps. +// Demonstrates performance differences in Maps // {Args: 100 5000} Small to keep build testing short import java.util.*; diff --git a/collectionsindepth/Maps.java b/collectionsindepth/Maps.java index 4acf65ca..1f568878 100644 --- a/collectionsindepth/Maps.java +++ b/collectionsindepth/Maps.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://mindviewinc.com/Books/OnJava/ for more book information. -// Things you can do with Maps. +// Things you can do with Maps import java.util.concurrent.*; import java.util.*; import onjava.*; @@ -16,9 +16,9 @@ public class Maps { } public static void test(Map map) { System.out.println(map.getClass().getSimpleName()); - map.putAll(new CountingMapData(25)); + map.putAll(new CountingFilledMap(25)); // Map has 'Set' behavior for keys: - map.putAll(new CountingMapData(25)); + map.putAll(new CountingFilledMap(25)); printKeys(map); // Producing a Collection of the values: System.out.print("Values: "); @@ -35,7 +35,7 @@ public class Maps { printKeys(map); map.clear(); System.out.println("map.isEmpty(): " + map.isEmpty()); - map.putAll(new CountingMapData(25)); + map.putAll(new CountingFilledMap(25)); // Operations on the Set change the Map: map.keySet().removeAll(map.keySet()); System.out.println("map.isEmpty(): " + map.isEmpty()); diff --git a/collectionsindepth/Prediction.java b/collectionsindepth/Prediction.java index 460a11f0..4cbb27f6 100644 --- a/collectionsindepth/Prediction.java +++ b/collectionsindepth/Prediction.java @@ -2,11 +2,11 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Predicting the weather with groundhogs. +// Predicting the weather with groundhogs import java.util.*; public class Prediction { - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); private boolean shadow = rand.nextDouble() > 0.5; @Override public String toString() { diff --git a/collectionsindepth/ReadOnly.java b/collectionsindepth/ReadOnly.java index 2f5afd74..d8fc7851 100644 --- a/collectionsindepth/ReadOnly.java +++ b/collectionsindepth/ReadOnly.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using the Collections.unmodifiable methods. +// Using the Collections.unmodifiable methods import java.util.*; import onjava.*; diff --git a/collectionsindepth/SetPerformance.java b/collectionsindepth/SetPerformance.java index 7a557f74..368384e5 100644 --- a/collectionsindepth/SetPerformance.java +++ b/collectionsindepth/SetPerformance.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates performance differences in Sets. +// Demonstrates performance differences in Sets // {Args: 100 5000} Small to keep build testing short import java.util.*; diff --git a/collectionsindepth/SimpleHashMap.java b/collectionsindepth/SimpleHashMap.java index ad27e27b..f1c5b331 100644 --- a/collectionsindepth/SimpleHashMap.java +++ b/collectionsindepth/SimpleHashMap.java @@ -2,11 +2,12 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A demonstration hashed Map. +// A demonstration hashed Map import java.util.*; import onjava.*; -public class SimpleHashMap extends AbstractMap { +public +class SimpleHashMap extends AbstractMap { // Choose a prime number for the hash table // size, to achieve a uniform distribution: static final int SIZE = 997; @@ -24,7 +25,8 @@ public class SimpleHashMap extends AbstractMap { LinkedList> bucket = buckets[index]; MapEntry pair = new MapEntry<>(key, value); boolean found = false; - ListIterator> it = bucket.listIterator(); + ListIterator> it = + bucket.listIterator(); while(it.hasNext()) { MapEntry iPair = it.next(); if(iPair.getKey().equals(key)) { @@ -58,7 +60,8 @@ public class SimpleHashMap extends AbstractMap { return set; } public static void main(String[] args) { - SimpleHashMap m = new SimpleHashMap<>(); + SimpleHashMap m = + new SimpleHashMap<>(); m.putAll(Countries.capitals(25)); System.out.println(m); System.out.println(m.get("ERITREA")); diff --git a/collectionsindepth/SlowMap.java b/collectionsindepth/SlowMap.java index 12d2e217..e80d14a0 100644 --- a/collectionsindepth/SlowMap.java +++ b/collectionsindepth/SlowMap.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://mindviewinc.com/Books/OnJava/ for more book information. -// A Map implemented with ArrayLists. +// A Map implemented with ArrayLists import java.util.*; import onjava.*; diff --git a/collectionsindepth/SortedMapDemo.java b/collectionsindepth/SortedMapDemo.java index 12123268..681c8866 100644 --- a/collectionsindepth/SortedMapDemo.java +++ b/collectionsindepth/SortedMapDemo.java @@ -2,14 +2,14 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// What you can do with a TreeMap. +// What you can do with a TreeMap import java.util.*; import onjava.*; public class SortedMapDemo { public static void main(String[] args) { TreeMap sortedMap = - new TreeMap<>(new CountingMapData(10)); + new TreeMap<>(new CountingFilledMap(10)); System.out.println(sortedMap); Integer low = sortedMap.firstKey(); Integer high = sortedMap.lastKey(); diff --git a/collectionsindepth/SortedSetDemo.java b/collectionsindepth/SortedSetDemo.java index 49201751..6dad6425 100644 --- a/collectionsindepth/SortedSetDemo.java +++ b/collectionsindepth/SortedSetDemo.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://mindviewinc.com/Books/OnJava/ for more book information. -// What you can do with a TreeSet. +// What you can do with a TreeSet import java.util.*; public class SortedSetDemo { diff --git a/collectionsindepth/SpringDetector.java b/collectionsindepth/SpringDetector.java index 4780f262..7a9e259c 100644 --- a/collectionsindepth/SpringDetector.java +++ b/collectionsindepth/SpringDetector.java @@ -22,7 +22,8 @@ public class SpringDetector { else System.out.println("Key not found: " + gh); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { detectSpring(Groundhog.class); } } diff --git a/collectionsindepth/SpringDetector2.java b/collectionsindepth/SpringDetector2.java index ac558f61..4a2081cb 100644 --- a/collectionsindepth/SpringDetector2.java +++ b/collectionsindepth/SpringDetector2.java @@ -2,10 +2,11 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A working key. +// A working key public class SpringDetector2 { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { SpringDetector.detectSpring(Groundhog2.class); } } diff --git a/collectionsindepth/Stacks.java b/collectionsindepth/Stacks.java index 3f188c4a..0c12efae 100644 --- a/collectionsindepth/Stacks.java +++ b/collectionsindepth/Stacks.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of Stack Class. +// Demonstration of Stack Class import java.util.*; enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, @@ -16,7 +16,8 @@ public class Stacks { System.out.println("stack = " + stack); // Treating a stack as a Vector: stack.addElement("The last line"); - System.out.println("element 5 = " + stack.elementAt(5)); + System.out.println( + "element 5 = " + stack.elementAt(5)); System.out.println("popping elements:"); while(!stack.empty()) System.out.print(stack.pop() + " "); diff --git a/collectionsindepth/Synchronization.java b/collectionsindepth/Synchronization.java index 6791d257..9d2adcfd 100644 --- a/collectionsindepth/Synchronization.java +++ b/collectionsindepth/Synchronization.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using the Collections.synchronized methods. +// Using the Collections.synchronized methods import java.util.*; public class Synchronization { diff --git a/collectionsindepth/Test.java b/collectionsindepth/Test.java index d91c3cdb..0a9f1b98 100644 --- a/collectionsindepth/Test.java +++ b/collectionsindepth/Test.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://mindviewinc.com/Books/OnJava/ for more book information. -// Framework for performing timed tests of collections. +// Framework for performing timed tests of collections public abstract class Test { String name; diff --git a/collectionsindepth/Tester.java b/collectionsindepth/Tester.java index 48b350b5..abc49add 100644 --- a/collectionsindepth/Tester.java +++ b/collectionsindepth/Tester.java @@ -2,24 +2,20 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Applies Test objects to lists of different collections. +// Applies Test objects to lists of different collections import java.util.*; +import java.time.*; public class Tester { public static int fieldWidth = 8; - public static TestParam[] defaultParams= TestParam.array( + public static + TestParam[] defaultParams= TestParam.array( 10, 5000, 100, 5000, 1000, 5000, 10000, 500); // Override this to modify pre-test initialization: protected C initialize(int size) { return collection; } protected C collection; private String headline = ""; private List> tests; - private static String stringField() { - return "%" + fieldWidth + "s"; - } - private static String numberField() { - return "%" + fieldWidth + "d"; - } private static int sizeWidth = 5; private static String sizeField = "%" + sizeWidth + "s"; private TestParam[] paramList = defaultParams; @@ -38,7 +34,8 @@ public class Tester { headline = newHeadline; } // Generic methods for convenience : - public static void run(C cntnr, List> tests){ + public static + void run(C cntnr, List> tests) { new Tester<>(cntnr, tests).timedTest(); } public static void run(C cntnr, @@ -61,7 +58,8 @@ public class Tester { // Print column headers: System.out.format(sizeField, "size"); for(Test test : tests) - System.out.format(stringField(), test.name); + System.out.format( + "%" + fieldWidth + "s", test.name); System.out.println(); } // Run the tests for this collection: @@ -71,12 +69,14 @@ public class Tester { System.out.format(sizeField, param.size); for(Test test : tests) { C kontainer = initialize(param.size); - long start = System.nanoTime(); + Instant start = Instant.now(); // Call the overriden method: int reps = test.test(kontainer, param); - long duration = System.nanoTime() - start; - long timePerRep = duration / reps; // Nanoseconds - System.out.format(numberField(), timePerRep); + Duration elapsed = + Duration.between(start, Instant.now()); + Duration timePerRep = elapsed.dividedBy(reps); + System.out.format("%" + fieldWidth + "d", + timePerRep.toNanos()); } System.out.println(); } diff --git a/collectionsindepth/ToDoList.java b/collectionsindepth/ToDoList.java index 07f3676c..fc97aa1c 100644 --- a/collectionsindepth/ToDoList.java +++ b/collectionsindepth/ToDoList.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://mindviewinc.com/Books/OnJava/ for more book information. -// A more complex use of PriorityQueue. +// A more complex use of PriorityQueue import java.util.*; class ToDoList extends PriorityQueue { diff --git a/collectionsindepth/TypesForSets.java b/collectionsindepth/TypesForSets.java index 57c7e0d3..d8952772 100644 --- a/collectionsindepth/TypesForSets.java +++ b/collectionsindepth/TypesForSets.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://mindviewinc.com/Books/OnJava/ for more book information. -// Methods necessary to put your own type in a Set. +// Methods necessary to put your own type in a Set import java.lang.reflect.InvocationTargetException; import java.util.*; @@ -36,8 +36,8 @@ public class TypesForSets { static Set fill(Set set, Class type) { try { for(int i = 0; i < 10; i++) - set.add( - type.getConstructor(int.class).newInstance(i)); + set.add(type.getConstructor(int.class) + .newInstance(i)); } catch(NoSuchMethodException | SecurityException | InstantiationException | diff --git a/collectionsindepth/Unsupported.java b/collectionsindepth/Unsupported.java index a66311a9..18e52cc1 100644 --- a/collectionsindepth/Unsupported.java +++ b/collectionsindepth/Unsupported.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://mindviewinc.com/Books/OnJava/ for more book information. -// Unsupported operations in Java collections. +// Unsupported operations in Java collections import java.util.*; public class Unsupported { @@ -44,7 +44,8 @@ public class Unsupported { test("Modifiable Copy", new ArrayList<>(list)); test("Arrays.asList()", list); test("unmodifiableList()", - Collections.unmodifiableList(new ArrayList<>(list))); + Collections.unmodifiableList( + new ArrayList<>(list))); } } /* Output: diff --git a/collectionsindepth/Utilities.java b/collectionsindepth/Utilities.java index 681c62b0..2c45de60 100644 --- a/collectionsindepth/Utilities.java +++ b/collectionsindepth/Utilities.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple demonstrations of the Collections utilities. +// Simple demonstrations of the Collections utilities import java.util.*; public class Utilities { diff --git a/collectionsindepth/build.xml b/collectionsindepth/build.xml index 2f373734..3c003129 100644 --- a/collectionsindepth/build.xml +++ b/collectionsindepth/build.xml @@ -10,20 +10,19 @@ - - + + - @@ -50,20 +49,19 @@ - - + + - diff --git a/com/mindviewinc/simple/List.java b/com/mindviewinc/simple/List.java index 9f46a00d..8f9d5787 100644 --- a/com/mindviewinc/simple/List.java +++ b/com/mindviewinc/simple/List.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating a package. +// Creating a package package com.mindviewinc.simple; public class List { diff --git a/com/mindviewinc/simple/Vector.java b/com/mindviewinc/simple/Vector.java index 60323780..086b1339 100644 --- a/com/mindviewinc/simple/Vector.java +++ b/com/mindviewinc/simple/Vector.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating a package. +// Creating a package package com.mindviewinc.simple; public class Vector { diff --git a/compression/GZIPcompress.java b/compression/GZIPcompress.java index b3ebc9ca..b313a3ff 100644 --- a/compression/GZIPcompress.java +++ b/compression/GZIPcompress.java @@ -7,8 +7,8 @@ import java.util.zip.*; import java.io.*; public class GZIPcompress { - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { if(args.length == 0) { System.out.println( "Usage: \nGZIPcompress file\n" + @@ -18,13 +18,14 @@ public class GZIPcompress { } try(InputStream in = new BufferedInputStream( new FileInputStream(args[0])); - BufferedOutputStream out = new BufferedOutputStream( - new GZIPOutputStream( - new FileOutputStream("test.gz")))) { + BufferedOutputStream out = + new BufferedOutputStream( + new GZIPOutputStream( + new FileOutputStream("test.gz")))) { System.out.println("Writing file"); int c; while((c = in.read()) != -1) - out.write(c); + out.write(c); } System.out.println("Reading file"); try(BufferedReader in2 = new BufferedReader( diff --git a/compression/ZipCompress.java b/compression/ZipCompress.java index ae4c63f8..12fe0439 100644 --- a/compression/ZipCompress.java +++ b/compression/ZipCompress.java @@ -3,16 +3,17 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Uses Zip compression to compress any -// number of files given on the command line. +// number of files given on the command line // {Args: ZipCompress.java} import java.util.zip.*; import java.io.*; import java.util.*; public class ZipCompress { - public static void main(String[] args) - throws IOException { - try(FileOutputStream f = new FileOutputStream("test.zip"); + public static void + main(String[] args) throws IOException { + try(FileOutputStream f = + new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); @@ -23,7 +24,7 @@ public class ZipCompress { for(String arg : args) { System.out.println("Writing file " + arg); try(InputStream in = new BufferedInputStream( - new FileInputStream(arg))) { + new FileInputStream(arg))) { zos.putNextEntry(new ZipEntry(arg)); int c; while((c = in.read()) != -1) @@ -37,7 +38,8 @@ public class ZipCompress { } // Now extract the files: System.out.println("Reading file"); - try(FileInputStream fi = new FileInputStream("test.zip"); + try(FileInputStream fi = + new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csumi); diff --git a/control/BreakAndContinue.java b/control/BreakAndContinue.java index ed3d46a7..82a369cc 100644 --- a/control/BreakAndContinue.java +++ b/control/BreakAndContinue.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates break and continue keywords. +// Break and continue keywords import static onjava.Range.*; public class BreakAndContinue { diff --git a/control/LabeledWhile.java b/control/LabeledWhile.java index c4e27e8e..4ebb27c5 100644 --- a/control/LabeledWhile.java +++ b/control/LabeledWhile.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://mindviewinc.com/Books/OnJava/ for more book information. -// While loops with "labeled break" and "labeled continue." +// "While" with "labeled break" and "labeled continue." public class LabeledWhile { public static void main(String[] args) { diff --git a/control/ListCharacters.java b/control/ListCharacters.java index e7825126..281c9e4e 100644 --- a/control/ListCharacters.java +++ b/control/ListCharacters.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates "for" loop by listing -// all the lowercase ASCII letters. +// List all the lowercase ASCII letters public class ListCharacters { public static void main(String[] args) { diff --git a/control/VowelsAndConsonants.java b/control/VowelsAndConsonants.java index 7916dafe..fbe9a631 100644 --- a/control/VowelsAndConsonants.java +++ b/control/VowelsAndConsonants.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the switch statement. +// Demonstrates the switch statement import java.util.*; public class VowelsAndConsonants { diff --git a/control/WhileTest.java b/control/WhileTest.java index d3643b1b..e3d044de 100644 --- a/control/WhileTest.java +++ b/control/WhileTest.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the while loop. +// Demonstrates the while loop public class WhileTest { static boolean condition() { diff --git a/enums/Burrito.java b/enums/Burrito.java index 9e13b632..8d785200 100644 --- a/enums/Burrito.java +++ b/enums/Burrito.java @@ -7,9 +7,13 @@ import static enums.Spiciness.*; public class Burrito { Spiciness degree; - public Burrito(Spiciness degree) { this.degree = degree;} + public Burrito(Spiciness degree) { + this.degree = degree; + } @Override - public String toString() { return "Burrito is "+ degree;} + public String toString() { + return "Burrito is "+ degree; + } public static void main(String[] args) { System.out.println(new Burrito(NOT)); System.out.println(new Burrito(MEDIUM)); diff --git a/enums/Competitor.java b/enums/Competitor.java index 9ed18979..234008d4 100644 --- a/enums/Competitor.java +++ b/enums/Competitor.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://mindviewinc.com/Books/OnJava/ for more book information. -// Switching one enum on another. +// Switching one enum on another package enums; public interface Competitor> { diff --git a/enums/EnumMaps.java b/enums/EnumMaps.java index 14c85d84..92cbbc04 100644 --- a/enums/EnumMaps.java +++ b/enums/EnumMaps.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://mindviewinc.com/Books/OnJava/ for more book information. -// Basics of EnumMaps. +// Basics of EnumMaps package enums; import java.util.*; import static enums.AlarmPoints.*; @@ -17,7 +17,7 @@ public class EnumMaps { () -> System.out.println("Kitchen fire!")); em.put(BATHROOM, () -> System.out.println("Bathroom alert!")); - for(Map.Entry e : em.entrySet()){ + for(Map.Entry e: em.entrySet()) { System.out.print(e.getKey() + ": "); e.getValue().action(); } diff --git a/enums/Input.java b/enums/Input.java index e700db06..56dc2dc9 100644 --- a/enums/Input.java +++ b/enums/Input.java @@ -23,7 +23,7 @@ public enum Input { Input(int value) { this.value = value; } Input() {} int amount() { return value; }; // In cents - static Random rand = new Random(47); + static SplittableRandom rand = new SplittableRandom(47); public static Input randomSelection() { // Don't include STOP: return values()[rand.nextInt(values().length - 1)]; diff --git a/enums/OzWitch.java b/enums/OzWitch.java index 5292c94b..9d56b7fb 100644 --- a/enums/OzWitch.java +++ b/enums/OzWitch.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://mindviewinc.com/Books/OnJava/ for more book information. -// The witches in the land of Oz. +// The witches in the land of Oz public enum OzWitch { // Instances must be defined first, before methods: diff --git a/enums/PostOffice.java b/enums/PostOffice.java index 282e956c..7b1837e4 100644 --- a/enums/PostOffice.java +++ b/enums/PostOffice.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://mindviewinc.com/Books/OnJava/ for more book information. -// Modeling a post office. +// Modeling a post office import java.util.*; import onjava.*; @@ -33,14 +33,16 @@ class Mail { // Generate test Mail: public static Mail randomMail() { Mail m = new Mail(); - m.generalDelivery= Enums.random(GeneralDelivery.class); + m.generalDelivery = + Enums.random(GeneralDelivery.class); m.scannability = Enums.random(Scannability.class); m.readability = Enums.random(Readability.class); m.address = Enums.random(Address.class); m.returnAddress = Enums.random(ReturnAddress.class); return m; } - public static Iterable generator(final int count) { + public static + Iterable generator(final int count) { return new Iterable() { int n = count; @Override diff --git a/enums/RandomTest.java b/enums/RandomTest.java index 56783fbe..70dbc443 100644 --- a/enums/RandomTest.java +++ b/enums/RandomTest.java @@ -10,7 +10,8 @@ enum Activity { SITTING, LYING, STANDING, HOPPING, public class RandomTest { public static void main(String[] args) { for(int i = 0; i < 20; i++) - System.out.print(Enums.random(Activity.class) + " "); + System.out.print( + Enums.random(Activity.class) + " "); } } /* Output: diff --git a/enums/Reflection.java b/enums/Reflection.java index 173b117b..c1359eb0 100644 --- a/enums/Reflection.java +++ b/enums/Reflection.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://mindviewinc.com/Books/OnJava/ for more book information. -// Analyzing enums using reflection. +// Analyzing enums using reflection import java.lang.reflect.*; import java.util.*; import onjava.*; diff --git a/enums/RoShamBo.java b/enums/RoShamBo.java index 0b9c6488..168b3202 100644 --- a/enums/RoShamBo.java +++ b/enums/RoShamBo.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://mindviewinc.com/Books/OnJava/ for more book information. -// Common tools for RoShamBo examples. +// Common tools for RoShamBo examples package enums; import onjava.*; diff --git a/enums/RoShamBo1.java b/enums/RoShamBo1.java index 25fa3af3..50ae9a0b 100644 --- a/enums/RoShamBo1.java +++ b/enums/RoShamBo1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of multiple dispatching. +// Demonstration of multiple dispatching package enums; import java.util.*; import static enums.Outcome.*; @@ -16,7 +16,9 @@ interface Item { class Paper implements Item { @Override - public Outcome compete(Item it) { return it.eval(this); } + public Outcome compete(Item it) { + return it.eval(this); + } @Override public Outcome eval(Paper p) { return DRAW; } @Override @@ -29,7 +31,9 @@ class Paper implements Item { class Scissors implements Item { @Override - public Outcome compete(Item it) { return it.eval(this); } + public Outcome compete(Item it) { + return it.eval(this); + } @Override public Outcome eval(Paper p) { return LOSE; } @Override @@ -42,7 +46,9 @@ class Scissors implements Item { class Rock implements Item { @Override - public Outcome compete(Item it) { return it.eval(this); } + public Outcome compete(Item it) { + return it.eval(this); + } @Override public Outcome eval(Paper p) { return WIN; } @Override @@ -55,7 +61,7 @@ class Rock implements Item { public class RoShamBo1 { static final int SIZE = 20; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); public static Item newItem() { switch(rand.nextInt(3)) { default: diff --git a/enums/RoShamBo2.java b/enums/RoShamBo2.java index de5c6080..ce009b7c 100644 --- a/enums/RoShamBo2.java +++ b/enums/RoShamBo2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Switching one enum on another. +// Switching one enum on another package enums; import static enums.Outcome.*; diff --git a/enums/RoShamBo3.java b/enums/RoShamBo3.java index 33ec6704..734a5eed 100644 --- a/enums/RoShamBo3.java +++ b/enums/RoShamBo3.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using constant-specific methods. +// Using constant-specific methods package enums; import static enums.Outcome.*; diff --git a/enums/RoShamBo5.java b/enums/RoShamBo5.java index bc43c2ce..d705aca9 100644 --- a/enums/RoShamBo5.java +++ b/enums/RoShamBo5.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://mindviewinc.com/Books/OnJava/ for more book information. -// Multiple dispatching using an EnumMap of EnumMaps. +// Multiple dispatching using an EnumMap of EnumMaps package enums; import java.util.*; import static enums.Outcome.*; diff --git a/enums/RoShamBo6.java b/enums/RoShamBo6.java index 6185c499..54b08f8e 100644 --- a/enums/RoShamBo6.java +++ b/enums/RoShamBo6.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://mindviewinc.com/Books/OnJava/ for more book information. -// Enums using "tables" instead of multiple dispatch. +// Enums using "tables" instead of multiple dispatch package enums; import static enums.Outcome.*; diff --git a/enums/SecurityCategory.java b/enums/SecurityCategory.java index bc4a4dd2..357980d6 100644 --- a/enums/SecurityCategory.java +++ b/enums/SecurityCategory.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://mindviewinc.com/Books/OnJava/ for more book information. -// More succinct subcategorization of enums. +// More succinct subcategorization of enums import onjava.*; enum SecurityCategory { diff --git a/enums/SpaceShip.java b/enums/SpaceShip.java index c0f0d56a..9ff2e3b7 100644 --- a/enums/SpaceShip.java +++ b/enums/SpaceShip.java @@ -5,7 +5,8 @@ import java.util.stream.*; public enum SpaceShip { - SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP; + SCOUT, CARGO, TRANSPORT, + CRUISER, BATTLESHIP, MOTHERSHIP; @Override public String toString() { String id = name(); diff --git a/enums/TrafficLight.java b/enums/TrafficLight.java index a2457a8d..f315f8d2 100644 --- a/enums/TrafficLight.java +++ b/enums/TrafficLight.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://mindviewinc.com/Books/OnJava/ for more book information. -// Enums in switch statements. +// Enums in switch statements // Define an enum type: enum Signal { GREEN, YELLOW, RED, } diff --git a/enums/build.xml b/enums/build.xml index 4257f771..e624bc0b 100644 --- a/enums/build.xml +++ b/enums/build.xml @@ -50,7 +50,7 @@ - + @@ -69,4 +69,4 @@ - + \ No newline at end of file diff --git a/enums/cartoons/EnumImplementation.java b/enums/cartoons/EnumImplementation.java index 970f434d..013aa360 100644 --- a/enums/cartoons/EnumImplementation.java +++ b/enums/cartoons/EnumImplementation.java @@ -10,7 +10,7 @@ import java.util.function.*; enum CartoonCharacter implements Supplier { SLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB; - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); @Override public CartoonCharacter get() { return values()[rand.nextInt(values().length)]; diff --git a/enums/menu/Food.java b/enums/menu/Food.java index b1caa9e0..4c226678 100644 --- a/enums/menu/Food.java +++ b/enums/menu/Food.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://mindviewinc.com/Books/OnJava/ for more book information. -// Subcategorization of enums within interfaces. +// Subcategorization of enums within interfaces package enums.menu; public interface Food { diff --git a/exceptions/AlwaysFinally.java b/exceptions/AlwaysFinally.java index 521a21db..29ab2b7e 100644 --- a/exceptions/AlwaysFinally.java +++ b/exceptions/AlwaysFinally.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://mindviewinc.com/Books/OnJava/ for more book information. -// Finally is always executed. +// Finally is always executed class FourException extends Exception {} diff --git a/exceptions/BodyException.java b/exceptions/BodyException.java index dab0a31d..12d953d2 100644 --- a/exceptions/BodyException.java +++ b/exceptions/BodyException.java @@ -8,7 +8,7 @@ class Third extends Reporter {} public class BodyException { public static void main(String[] args) { try(First f = new First(); - Second s2 = new Second();) { + Second s2 = new Second()) { System.out.println("In body"); Third t = new Third(); new SecondExcept(); diff --git a/exceptions/Cleanup.java b/exceptions/Cleanup.java index c0cd387c..43be678f 100644 --- a/exceptions/Cleanup.java +++ b/exceptions/Cleanup.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://mindviewinc.com/Books/OnJava/ for more book information. -// Guaranteeing proper cleanup of a resource. +// Guaranteeing proper cleanup of a resource public class Cleanup { public static void main(String[] args) { diff --git a/exceptions/CleanupIdiom.java b/exceptions/CleanupIdiom.java index bcf4d590..2728d045 100644 --- a/exceptions/CleanupIdiom.java +++ b/exceptions/CleanupIdiom.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://mindviewinc.com/Books/OnJava/ for more book information. -// Each disposable object must be followed by a try-finally +// Disposable objects must be followed by a try-finally class NeedsCleanup { // Construction can't fail private static long counter = 1; @@ -52,12 +52,12 @@ public class CleanupIdiom { } finally { nc5.dispose(); } - } catch(ConstructionException e) { // nc5 constructor + } catch(ConstructionException e) { // nc5 const. System.out.println(e); } finally { nc4.dispose(); } - } catch(ConstructionException e) { // nc4 constructor + } catch(ConstructionException e) { // nc4 const. System.out.println(e); } } diff --git a/exceptions/ConstructorException.java b/exceptions/ConstructorException.java index b89c2230..8d970cbe 100644 --- a/exceptions/ConstructorException.java +++ b/exceptions/ConstructorException.java @@ -16,7 +16,7 @@ public class ConstructorException { public static void main(String[] args) { try(First f = new First(); SecondExcept s = new SecondExcept(); - Second s2 = new Second();) { + Second s2 = new Second()) { System.out.println("In body"); } catch(CE e) { System.out.println("Caught: " + e); diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index 09f3c878..1e115500 100644 --- a/exceptions/DynamicFields.java +++ b/exceptions/DynamicFields.java @@ -2,8 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A Class that dynamically adds fields to itself. -// Demonstrates exception chaining. +// A Class that dynamically adds fields to itself to +// demonstrate exception chaining class DynamicFieldsException extends Exception {} diff --git a/exceptions/ExceptionMethods.java b/exceptions/ExceptionMethods.java index e8220b24..ac4c6261 100644 --- a/exceptions/ExceptionMethods.java +++ b/exceptions/ExceptionMethods.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrating the Exception Methods. +// Demonstrating the Exception Methods public class ExceptionMethods { public static void main(String[] args) { @@ -10,7 +10,8 @@ public class ExceptionMethods { throw new Exception("My Exception"); } catch(Exception e) { System.out.println("Caught Exception"); - System.out.println("getMessage():" + e.getMessage()); + System.out.println( + "getMessage():" + e.getMessage()); System.out.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.out.println("toString():" + e); diff --git a/exceptions/ExtraFeatures.java b/exceptions/ExtraFeatures.java index c4e662e1..57200ce9 100644 --- a/exceptions/ExtraFeatures.java +++ b/exceptions/ExtraFeatures.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://mindviewinc.com/Books/OnJava/ for more book information. -// Further embellishment of exception classes. +// Further embellishment of exception classes class MyException2 extends Exception { private int x; @@ -15,7 +15,8 @@ class MyException2 extends Exception { public int val() { return x; } @Override public String getMessage() { - return "Detail Message: "+ x + " "+ super.getMessage(); + return "Detail Message: "+ x + + " "+ super.getMessage(); } } diff --git a/exceptions/FinallyWorks.java b/exceptions/FinallyWorks.java index 42a1b9e1..9856af23 100644 --- a/exceptions/FinallyWorks.java +++ b/exceptions/FinallyWorks.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://mindviewinc.com/Books/OnJava/ for more book information. -// The finally clause is always executed. +// The finally clause is always executed class ThreeException extends Exception {} diff --git a/exceptions/Human.java b/exceptions/Human.java index fe313f52..a382a908 100644 --- a/exceptions/Human.java +++ b/exceptions/Human.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://mindviewinc.com/Books/OnJava/ for more book information. -// Catching exception hierarchies. +// Catching exception hierarchies class Annoyance extends Exception {} class Sneeze extends Annoyance {} diff --git a/exceptions/InheritingExceptions.java b/exceptions/InheritingExceptions.java index 47c39c37..2e853411 100644 --- a/exceptions/InheritingExceptions.java +++ b/exceptions/InheritingExceptions.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating your own exceptions. +// Creating your own exceptions class SimpleException extends Exception {} diff --git a/exceptions/InputFile.java b/exceptions/InputFile.java index 9f854645..7522d848 100644 --- a/exceptions/InputFile.java +++ b/exceptions/InputFile.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://mindviewinc.com/Books/OnJava/ for more book information. -// Paying attention to exceptions in constructors. +// Paying attention to exceptions in constructors import java.io.*; public class InputFile { diff --git a/exceptions/InputFile2.java b/exceptions/InputFile2.java index 0fb3af7e..2544da60 100644 --- a/exceptions/InputFile2.java +++ b/exceptions/InputFile2.java @@ -8,18 +8,21 @@ import java.util.stream.*; public class InputFile2 { private String fname; - public InputFile2(String fname) { this.fname = fname; } - public Stream getLines() throws IOException { + public InputFile2(String fname) { + this.fname = fname; + } + public + Stream getLines() throws IOException { return Files.lines(Paths.get(fname)); } - public static - void main(String[] args) throws IOException { + public static void + main(String[] args) throws IOException { new InputFile2("InputFile2.java").getLines() - .skip(12) + .skip(15) .limit(1) .forEach(System.out::println); } } /* Output: - void main(String[] args) throws IOException { + main(String[] args) throws IOException { */ diff --git a/exceptions/LoggingExceptions.java b/exceptions/LoggingExceptions.java index fc4ee1e6..2fe1f024 100644 --- a/exceptions/LoggingExceptions.java +++ b/exceptions/LoggingExceptions.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://mindviewinc.com/Books/OnJava/ for more book information. -// An exception that reports through a Logger. +// An exception that reports through a Logger // {ErrorOutputExpected} import java.util.logging.*; import java.io.*; diff --git a/exceptions/LoggingExceptions2.java b/exceptions/LoggingExceptions2.java index b706bff4..ae7cffd4 100644 --- a/exceptions/LoggingExceptions2.java +++ b/exceptions/LoggingExceptions2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Logging caught exceptions. +// Logging caught exceptions // {ErrorOutputExpected} import java.util.logging.*; import java.io.*; diff --git a/exceptions/LostMessage.java b/exceptions/LostMessage.java index 226cdbb5..e4876e67 100644 --- a/exceptions/LostMessage.java +++ b/exceptions/LostMessage.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://mindviewinc.com/Books/OnJava/ for more book information. -// How an exception can be lost. +// How an exception can be lost class VeryImportantException extends Exception { @Override diff --git a/exceptions/MainException.java b/exceptions/MainException.java index 90d55900..d42e01a8 100644 --- a/exceptions/MainException.java +++ b/exceptions/MainException.java @@ -7,7 +7,8 @@ import java.nio.file.*; public class MainException { // Pass exceptions to the console: - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { // Open the file: List lines = Files.readAllLines( Paths.get("MainException.java")); diff --git a/exceptions/NeverCaught.java b/exceptions/NeverCaught.java index 820613ff..63341738 100644 --- a/exceptions/NeverCaught.java +++ b/exceptions/NeverCaught.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://mindviewinc.com/Books/OnJava/ for more book information. -// Ignoring RuntimeExceptions. +// Ignoring RuntimeExceptions // {ThrowsException} public class NeverCaught { diff --git a/exceptions/RethrowNew.java b/exceptions/RethrowNew.java index 4584b035..8e327ffb 100644 --- a/exceptions/RethrowNew.java +++ b/exceptions/RethrowNew.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://mindviewinc.com/Books/OnJava/ for more book information. -// Rethrow a different object from the one you caught. +// Rethrow a different object from the one you caught class OneException extends Exception { public OneException(String s) { super(s); } diff --git a/exceptions/StormyInning.java b/exceptions/StormyInning.java index c9cbac60..6a792bd2 100644 --- a/exceptions/StormyInning.java +++ b/exceptions/StormyInning.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Overridden methods can throw only the exceptions // specified in their base-class versions, or exceptions -// derived from the base-class exceptions. +// derived from the base-class exceptions class BaseballException extends Exception {} class Foul extends BaseballException {} diff --git a/exceptions/StreamsAreAutoCloseable.java b/exceptions/StreamsAreAutoCloseable.java index ac22742f..153c73a9 100644 --- a/exceptions/StreamsAreAutoCloseable.java +++ b/exceptions/StreamsAreAutoCloseable.java @@ -7,8 +7,8 @@ import java.nio.file.*; import java.util.stream.*; public class StreamsAreAutoCloseable { - public static - void main(String[] args) throws IOException{ + public static void + main(String[] args) throws IOException{ try(Stream in = Files.lines( Paths.get("StreamsAreAutoCloseable.java")); PrintWriter outfile = new PrintWriter( diff --git a/exceptions/TurnOffChecking.java b/exceptions/TurnOffChecking.java index 0c4abbd4..7f916aee 100644 --- a/exceptions/TurnOffChecking.java +++ b/exceptions/TurnOffChecking.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://mindviewinc.com/Books/OnJava/ for more book information. -// "Turning off" Checked exceptions. +// "Turning off" Checked exceptions import java.io.*; class WrapCheckedException { @@ -42,7 +42,8 @@ public class TurnOffChecking { try { throw re.getCause(); } catch(FileNotFoundException e) { - System.out.println("FileNotFoundException: " + e); + System.out.println( + "FileNotFoundException: " + e); } catch(IOException e) { System.out.println("IOException: " + e); } catch(Throwable e) { diff --git a/exceptions/WhoCalled.java b/exceptions/WhoCalled.java index 5c2d75ad..dbe1ff7c 100644 --- a/exceptions/WhoCalled.java +++ b/exceptions/WhoCalled.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://mindviewinc.com/Books/OnJava/ for more book information. -// Programmatic access to stack trace information. +// Programmatic access to stack trace information public class WhoCalled { static void f() { @@ -18,20 +18,20 @@ public class WhoCalled { static void h() { g(); } public static void main(String[] args) { f(); - System.out.println("--------------------------------"); + System.out.println("-------------------------------"); g(); - System.out.println("--------------------------------"); + System.out.println("-------------------------------"); h(); } } /* Output: f main --------------------------------- +------------------------------- f g main --------------------------------- +------------------------------- f g h diff --git a/exceptions/WithFinally.java b/exceptions/WithFinally.java index 3af524e5..40bb5c27 100644 --- a/exceptions/WithFinally.java +++ b/exceptions/WithFinally.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://mindviewinc.com/Books/OnJava/ for more book information. -// Finally Guarantees cleanup. +// Finally Guarantees cleanup public class WithFinally { static Switch sw = new Switch(); diff --git a/files/AddAndSubtractPaths.java b/files/AddAndSubtractPaths.java index f09791d6..d107bf95 100644 --- a/files/AddAndSubtractPaths.java +++ b/files/AddAndSubtractPaths.java @@ -16,7 +16,8 @@ public class AddAndSubtractPaths { else System.out.println("(" + id + ") " + result); try { - System.out.println("RealPath: " + result.toRealPath()); + System.out.println("RealPath: " + + result.toRealPath()); } catch (IOException e) { System.out.println(e); } diff --git a/files/Directories.java b/files/Directories.java index 1b709063..434bf01e 100644 --- a/files/Directories.java +++ b/files/Directories.java @@ -22,7 +22,8 @@ public class Directories { if(!Files.exists(test)) Files.createDirectory(test); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { refreshTestDir(); Files.createFile(test.resolve("Hello.txt")); Path variant = makeVariant(); diff --git a/files/Find.java b/files/Find.java index 8f993f40..babf8eb5 100644 --- a/files/Find.java +++ b/files/Find.java @@ -5,7 +5,8 @@ import java.nio.file.*; public class Find { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Path test = Paths.get("test"); Directories.refreshTestDir(); Directories.populateTestDir(); diff --git a/files/ListOfLines.java b/files/ListOfLines.java index e1e14e1a..21c4ebc0 100644 --- a/files/ListOfLines.java +++ b/files/ListOfLines.java @@ -6,7 +6,8 @@ import java.util.*; import java.nio.file.*; public class ListOfLines { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { List lines = Files.readAllLines( Paths.get("../streams/Cheese.dat")); for(String line : lines) { diff --git a/files/PathAnalysis.java b/files/PathAnalysis.java index d7563c52..77b4603d 100644 --- a/files/PathAnalysis.java +++ b/files/PathAnalysis.java @@ -10,8 +10,8 @@ public class PathAnalysis { System.out.print(id + ": "); System.out.println(result); } - public - static void main(String[] args) throws IOException { + public static void + main(String[] args) throws IOException { System.out.println(System.getProperty("os.name")); Path p = Paths.get("PathAnalysis.java").toAbsolutePath(); diff --git a/files/PathWatcher.java b/files/PathWatcher.java index 3bcce67b..bee1dcdd 100644 --- a/files/PathWatcher.java +++ b/files/PathWatcher.java @@ -26,7 +26,8 @@ public class PathWatcher { throw new RuntimeException(e); } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Directories.refreshTestDir(); Directories.populateTestDir(); Files.createFile(test.resolve("Hello.txt")); diff --git a/files/ReadLineStream.java b/files/ReadLineStream.java index 015c338d..d33a37b4 100644 --- a/files/ReadLineStream.java +++ b/files/ReadLineStream.java @@ -5,7 +5,8 @@ import java.nio.file.*; public class ReadLineStream { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Files.lines(Paths.get("PathInfo.java")) .skip(13) .findFirst() diff --git a/files/TreeWatcher.java b/files/TreeWatcher.java index ff478c2e..fa7abeeb 100644 --- a/files/TreeWatcher.java +++ b/files/TreeWatcher.java @@ -31,7 +31,8 @@ public class TreeWatcher { throw new RuntimeException(e); } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Directories.refreshTestDir(); Directories.populateTestDir(); Files.walk(Paths.get("test")) diff --git a/files/Writing.java b/files/Writing.java index 9318c4b4..f26d1fb4 100644 --- a/files/Writing.java +++ b/files/Writing.java @@ -8,7 +8,8 @@ import java.nio.file.*; public class Writing { static Random rand = new Random(47); static final int sz = 1000; - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { // Write bytes to a file: byte[] bytes = new byte[sz]; rand.nextBytes(bytes); diff --git a/files/build.xml b/files/build.xml index 29a320ec..e7be8758 100644 --- a/files/build.xml +++ b/files/build.xml @@ -28,6 +28,7 @@ + @@ -38,4 +39,4 @@ - + \ No newline at end of file diff --git a/functional/UnboundMethodReference.java b/functional/UnboundMethodReference.java index bddf0173..99b72c91 100644 --- a/functional/UnboundMethodReference.java +++ b/functional/UnboundMethodReference.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://mindviewinc.com/Books/OnJava/ for more book information. -// Method reference without an object. +// Method reference without an object class X { String f() { return "X::f()"; } diff --git a/generics/Apply.java b/generics/Apply.java index 1b14decf..115a8482 100644 --- a/generics/Apply.java +++ b/generics/Apply.java @@ -2,12 +2,11 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// {main: ApplyTest} import java.lang.reflect.*; import java.util.*; public class Apply { - public static > + public static > void apply(S seq, Method f, Object... args) { try { for(T t: seq) @@ -20,79 +19,3 @@ public class Apply { } } } - -class Shape { - public void rotate() { - System.out.println(this + " rotate"); - } - public void resize(int newSize) { - System.out.println(this + " resize " + newSize); - } -} - -class Square extends Shape {} - -class FilledList extends ArrayList { - public FilledList(Class type, int size) { - try { - for(int i = 0; i < size; i++) - // Assumes no-arg constructor: - add(type.newInstance()); - } catch(InstantiationException | - IllegalAccessException e) { - throw new RuntimeException(e); - } - } -} - -class ApplyTest { - public static void main(String[] args) throws Exception { - List shapes = new ArrayList<>(); - for(int i = 0; i < 10; i++) - shapes.add(new Shape()); - Apply.apply(shapes, Shape.class.getMethod("rotate")); - Apply.apply(shapes, - Shape.class.getMethod("resize", int.class), 5); - List squares = new ArrayList<>(); - for(int i = 0; i < 10; i++) - squares.add(new Square()); - Apply.apply(squares, Shape.class.getMethod("rotate")); - Apply.apply(squares, - Shape.class.getMethod("resize", int.class), 5); - - Apply.apply(new FilledList<>(Shape.class, 10), - Shape.class.getMethod("rotate")); - Apply.apply(new FilledList<>(Square.class, 10), - Shape.class.getMethod("rotate")); - - SimpleQueue shapeQ = new SimpleQueue<>(); - for(int i = 0; i < 5; i++) { - shapeQ.add(new Shape()); - shapeQ.add(new Square()); - } - Apply.apply(shapeQ, Shape.class.getMethod("rotate")); - } -} -/* Output: (First and last 10 Lines) -Shape@139a55 rotate -Shape@106d69c rotate -Shape@52e922 rotate -Shape@25154f rotate -Shape@10dea4e rotate -Shape@647e05 rotate -Shape@1909752 rotate -Shape@1f96302 rotate -Shape@14eac69 rotate -Shape@a57993 rotate -________...________...________...________...________ -Shape@d3c617 rotate -Square@1947c6b rotate -Shape@1193f2d rotate -Square@15da254 rotate -Shape@1c63996 rotate -Square@1716361 rotate -Shape@1f3c5b5 rotate -Square@164951d rotate -Shape@11210ee rotate -Square@17e1886 rotate -*/ diff --git a/generics/ApplyFunctional.java b/generics/ApplyFunctional.java new file mode 100644 index 00000000..bda661f4 --- /dev/null +++ b/generics/ApplyFunctional.java @@ -0,0 +1,49 @@ +// generics/ApplyFunctional.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import java.util.stream.*; +import java.util.function.*; +import onjava.*; + +public class ApplyFunctional { + public static void main(String[] args) { + Stream.of( + Stream.generate(Shape::new).limit(2), + Stream.generate(Square::new).limit(2)) + .flatMap(c -> c) // flatten into one stream + .peek(Shape::rotate) + .forEach(s -> s.resize(7)); + + new FilledList<>(Shape::new, 2) + .forEach(Shape::rotate); + new FilledList<>(Square::new, 2) + .forEach(Shape::rotate); + + SimpleQueue shapeQ = Suppliers.fill( + new SimpleQueue<>(), SimpleQueue::add, + Shape::new, 2); + Suppliers.fill(shapeQ, SimpleQueue::add, + Square::new, 2); + shapeQ.forEach(Shape::rotate); + } +} +/* Output: +Shape 0 rotate +Shape 0 resize 7 +Shape 1 rotate +Shape 1 resize 7 +Square 2 rotate +Square 2 resize 7 +Square 3 rotate +Square 3 resize 7 +Shape 4 rotate +Shape 5 rotate +Square 6 rotate +Square 7 rotate +Shape 8 rotate +Shape 9 rotate +Square 10 rotate +Square 11 rotate +*/ diff --git a/generics/ApplyTest.java b/generics/ApplyTest.java new file mode 100644 index 00000000..2bf45ad0 --- /dev/null +++ b/generics/ApplyTest.java @@ -0,0 +1,84 @@ +// generics/ApplyTest.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import java.util.function.*; +import onjava.*; + +class Shape { + private static long counter = 0; + private final long id = counter++; + @Override + public String toString() { + return getClass().getSimpleName() + " " + id; + } + public void rotate() { + System.out.println(this + " rotate"); + } + public void resize(int newSize) { + System.out.println(this + " resize " + newSize); + } +} + +class Square extends Shape {} + +class FilledList extends ArrayList { + public FilledList(Supplier gen, int size) { + Suppliers.fill(this, gen, size); + } +} + +public class ApplyTest { + public static void main(String[] args) throws Exception { + List shapes = + Suppliers.create(ArrayList::new, Shape::new, 3); + Apply.apply(shapes, Shape.class.getMethod("rotate")); + Apply.apply(shapes, + Shape.class.getMethod("resize", int.class), 7); + + List squares = + Suppliers.create(ArrayList::new, Square::new, 3); + Apply.apply(squares, Shape.class.getMethod("rotate")); + Apply.apply(squares, + Shape.class.getMethod("resize", int.class), 7); + + Apply.apply(new FilledList<>(Shape::new, 3), + Shape.class.getMethod("rotate")); + Apply.apply(new FilledList<>(Square::new, 3), + Shape.class.getMethod("rotate")); + + SimpleQueue shapeQ = Suppliers.fill( + new SimpleQueue<>(), SimpleQueue::add, + Shape::new, 3); + Suppliers.fill(shapeQ, SimpleQueue::add, + Square::new, 3); + Apply.apply(shapeQ, Shape.class.getMethod("rotate")); + } +} +/* Output: +Shape 0 rotate +Shape 1 rotate +Shape 2 rotate +Shape 0 resize 7 +Shape 1 resize 7 +Shape 2 resize 7 +Square 3 rotate +Square 4 rotate +Square 5 rotate +Square 3 resize 7 +Square 4 resize 7 +Square 5 resize 7 +Shape 6 rotate +Shape 7 rotate +Shape 8 rotate +Square 9 rotate +Square 10 rotate +Square 11 rotate +Shape 12 rotate +Shape 13 rotate +Shape 14 rotate +Square 15 rotate +Square 16 rotate +Square 17 rotate +*/ diff --git a/generics/ArrayOfGeneric.java b/generics/ArrayOfGeneric.java index 70bea798..43b9d460 100644 --- a/generics/ArrayOfGeneric.java +++ b/generics/ArrayOfGeneric.java @@ -8,8 +8,11 @@ public class ArrayOfGeneric { static Generic[] gia; @SuppressWarnings("unchecked") public static void main(String[] args) { - // Compiles; produces ClassCastException: - //- gia = (Generic[])new Object[SIZE]; + try { + gia = (Generic[])new Object[SIZE]; + } catch(ClassCastException e) { + System.out.println(e.getMessage()); + } // Runtime type is the raw (erased) type: gia = (Generic[])new Generic[SIZE]; System.out.println(gia.getClass().getSimpleName()); @@ -20,5 +23,6 @@ public class ArrayOfGeneric { } } /* Output: +[Ljava.lang.Object; cannot be cast to [LGeneric; Generic[] */ diff --git a/generics/BankTeller.java b/generics/BankTeller.java index d7a1862e..4b282f13 100644 --- a/generics/BankTeller.java +++ b/generics/BankTeller.java @@ -2,30 +2,27 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A very simple bank teller simulation. +// A very simple bank teller simulation import java.util.*; -import java.util.function.*; +import onjava.*; class Customer { private static long counter = 1; private final long id = counter++; - private Customer() {} @Override public String toString() { return "Customer " + id; } - // A method to produce Supplier objects: - public static Supplier generator() { - return Customer::new; // Constructor reference - } } class Teller { private static long counter = 1; private final long id = counter++; - private Teller() {} @Override public String toString() { return "Teller " + id; } - // A single Supplier object: - public static Supplier generator = Teller::new; +} + +class Bank { + private List tellers = new ArrayList<>(); + public void put(BankTeller bt) { tellers.add(bt); } } public class BankTeller { @@ -33,13 +30,19 @@ public class BankTeller { System.out.println(t + " serves " + c); } public static void main(String[] args) { - Random rand = new Random(47); - Queue line = new LinkedList<>(); - Suppliers.fill(line, Customer.generator(), 15); - List tellers = new ArrayList<>(); - Suppliers.fill(tellers, Teller.generator, 4); - for(Customer c : line) - serve(tellers.get(rand.nextInt(tellers.size())), c); + // Demonstrate create(): + RandomList tellers = + Suppliers.create(RandomList::new, Teller::new, 4); + // Demonstrate fill(): + List customers = Suppliers.fill( + new ArrayList<>(), Customer::new, 12); + customers.forEach(c -> serve(tellers.select(), c)); + // Demonstrate assisted latent typing: + Bank bank = Suppliers.fill( + new Bank(), Bank::put, BankTeller::new, 3); + // Can also use second version of fill(): + List customers2 = Suppliers.fill( + new ArrayList<>(), List::add, Customer::new, 12); } } /* Output: @@ -55,7 +58,4 @@ Teller 3 serves Customer 9 Teller 3 serves Customer 10 Teller 2 serves Customer 11 Teller 4 serves Customer 12 -Teller 2 serves Customer 13 -Teller 1 serves Customer 14 -Teller 1 serves Customer 15 */ diff --git a/generics/BasicBounds.java b/generics/BasicBounds.java index 7c44b7f5..2a33cc53 100644 --- a/generics/BasicBounds.java +++ b/generics/BasicBounds.java @@ -5,23 +5,23 @@ interface HasColor { java.awt.Color getColor(); } -class Colored { +class WithColor { T item; - Colored(T item) { this.item = item; } + WithColor(T item) { this.item = item; } T getItem() { return item; } // The bound allows you to call a method: java.awt.Color color() { return item.getColor(); } } -class Dimension { public int x, y, z; } +class Coord { public int x, y, z; } -// This won't work -- class must be first, then interfaces: -// class ColoredDimension { +// This won't work. Class must be first, then interfaces: +// class WithColorCoord { // Multiple bounds: -class ColoredDimension { +class WithColorCoord { T item; - ColoredDimension(T item) { this.item = item; } + WithColorCoord(T item) { this.item = item; } T getItem() { return item; } java.awt.Color color() { return item.getColor(); } int getX() { return item.x; } @@ -33,7 +33,7 @@ interface Weight { int weight(); } // As with inheritance, you can have only one // concrete class but multiple interfaces: -class Solid { +class Solid { T item; Solid(T item) { this.item = item; } T getItem() { return item; } @@ -45,7 +45,7 @@ class Solid { } class Bounded -extends Dimension implements HasColor, Weight { +extends Coord implements HasColor, Weight { @Override public java.awt.Color getColor() { return null; } @Override diff --git a/generics/BasicHolder.java b/generics/BasicHolder.java index fa33fe83..5d63c599 100644 --- a/generics/BasicHolder.java +++ b/generics/BasicHolder.java @@ -8,6 +8,7 @@ public class BasicHolder { void set(T arg) { element = arg; } T get() { return element; } void f() { - System.out.println(element.getClass().getSimpleName()); + System.out.println( + element.getClass().getSimpleName()); } } diff --git a/generics/BasicSupplierDemo.java b/generics/BasicSupplierDemo.java index da0ca13b..6613fb9e 100644 --- a/generics/BasicSupplierDemo.java +++ b/generics/BasicSupplierDemo.java @@ -3,14 +3,14 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. import onjava.*; -import java.util.function.*; +import java.util.stream.*; public class BasicSupplierDemo { public static void main(String[] args) { - Supplier gen = - BasicSupplier.create(CountedObject.class); - for(int i = 0; i < 5; i++) - System.out.println(gen.get()); + Stream.generate( + BasicSupplier.create(CountedObject.class)) + .limit(5) + .forEach(System.out::println); } } /* Output: diff --git a/generics/CaptureConversion.java b/generics/CaptureConversion.java index 5bc5aa4d..702e50d4 100644 --- a/generics/CaptureConversion.java +++ b/generics/CaptureConversion.java @@ -14,10 +14,40 @@ public class CaptureConversion { @SuppressWarnings("unchecked") public static void main(String[] args) { Holder raw = new Holder<>(1); - // f1(raw); // Produces warnings + + f1(raw); + // warning: [unchecked] unchecked method invocation: + // method f1 in class CaptureConversion + // is applied to given types + // f1(raw); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method f1(Holder) + // warning: [unchecked] unchecked conversion + // f1(raw); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method f1(Holder) + // 2 warnings + f2(raw); // No warnings Holder rawBasic = new Holder(); - rawBasic.set(new Object()); // Warning + + rawBasic.set(new Object()); + // warning: [unchecked] unchecked call to set(T) + // as a member of the raw type Holder + // rawBasic.set(new Object()); + // ^ + // where T is a type-variable: + // T extends Object declared in class Holder + // 1 warning + f2(rawBasic); // No warnings // Upcast to Holder, still figures it out: Holder wildcarded = new Holder<>(1.0); @@ -26,6 +56,7 @@ public class CaptureConversion { } /* Output: Integer +Integer Object Double */ diff --git a/generics/CheckedList.java b/generics/CheckedList.java index e2024083..e287dbf0 100644 --- a/generics/CheckedList.java +++ b/generics/CheckedList.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using Collection.checkedList(). +// Using Collection.checkedList() import typeinfo.pets.*; import java.util.*; diff --git a/generics/CountedObject.java b/generics/CountedObject.java index aed23370..b49b5e8c 100644 --- a/generics/CountedObject.java +++ b/generics/CountedObject.java @@ -8,5 +8,7 @@ public class CountedObject { private final long id = counter++; public long id() { return id; } @Override - public String toString() { return "CountedObject " + id;} + public String toString() { + return "CountedObject " + id; + } } diff --git a/generics/CreatorGeneric.java b/generics/CreatorGeneric.java index 1b14fdb7..571df572 100644 --- a/generics/CreatorGeneric.java +++ b/generics/CreatorGeneric.java @@ -11,18 +11,19 @@ abstract class GenericWithCreate { class X {} -class Creator extends GenericWithCreate { +class XCreator extends GenericWithCreate { @Override X create() { return new X(); } void f() { - System.out.println(element.getClass().getSimpleName()); + System.out.println( + element.getClass().getSimpleName()); } } public class CreatorGeneric { public static void main(String[] args) { - Creator c = new Creator(); - c.f(); + XCreator xc = new XCreator(); + xc.f(); } } /* Output: diff --git a/generics/DogsAndRobotMethodReferences.java b/generics/DogsAndRobotMethodReferences.java new file mode 100644 index 00000000..2a2328b3 --- /dev/null +++ b/generics/DogsAndRobotMethodReferences.java @@ -0,0 +1,44 @@ +// generics/DogsAndRobotMethodReferences.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// "Assisted Latent Typing" +import typeinfo.pets.*; +import java.util.function.*; + +class PerformingDog_ extends Dog { + public void speak() { System.out.println("Woof!"); } + public void sit() { System.out.println("Sitting"); } + public void reproduce() {} +} + +class Robot_ { + public void speak() { System.out.println("Click!"); } + public void sit() { System.out.println("Clank!"); } + public void oilChange() {} +} + +class Communicate_ { + public static

void perform(P performer, + Consumer

action1, Consumer

action2) { + action1.accept(performer); + action2.accept(performer); + } +} + +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(), + Mime::walkAgainstTheWind, Mime::pushInvisibleWalls); + } +} +/* Output: +Woof! +Sitting +Click! +Clank! +*/ diff --git a/generics/DogsAndRobots.cpp b/generics/DogsAndRobots.cpp index a6d9dbea..354a2fa3 100644 --- a/generics/DogsAndRobots.cpp +++ b/generics/DogsAndRobots.cpp @@ -2,19 +2,21 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. +#include +using namespace std; class Dog { public: - void speak() {} - void sit() {} + void speak() { cout << "Arf!" << endl; } + void sit() { cout << "Sitting" << endl; } void reproduce() {} }; class Robot { public: - void speak() {} - void sit() {} - void oilChange() { + void speak() { cout << "Click!" << endl; } + void sit() { cout << "Clank!" << endl; } + void oilChange() {} }; template void perform(T anything) { @@ -28,3 +30,9 @@ int main() { perform(d); perform(r); } +/* Output: +Arf! +Sitting +Click! +Clank! +*/ diff --git a/generics/DogsAndRobots.java b/generics/DogsAndRobots.java index 79e31190..2d145452 100644 --- a/generics/DogsAndRobots.java +++ b/generics/DogsAndRobots.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://mindviewinc.com/Books/OnJava/ for more book information. -// No latent typing in Java +// No (direct) latent typing in Java import typeinfo.pets.*; class PerformingDog extends Dog implements Performs { @@ -29,10 +29,8 @@ class Communicate { public class DogsAndRobots { public static void main(String[] args) { - PerformingDog d = new PerformingDog(); - Robot r = new Robot(); - Communicate.perform(d); - Communicate.perform(r); + Communicate.perform(new PerformingDog()); + Communicate.perform(new Robot()); } } /* Output: diff --git a/generics/DogsAndRobots.py b/generics/DogsAndRobots.py index 565cce26..33cce802 100644 --- a/generics/DogsAndRobots.py +++ b/generics/DogsAndRobots.py @@ -5,17 +5,17 @@ class Dog: def speak(self): - System.out.println("Arf!") + print("Arf!") def sit(self): - System.out.println("Sitting") + print("Sitting") def reproduce(self): pass class Robot: def speak(self): - System.out.println("Click!") + print("Click!") def sit(self): - System.out.println("Clank!") + print("Clank!") def oilChange(self): pass @@ -27,3 +27,10 @@ a = Dog() b = Robot() perform(a) perform(b) + +output = """ +Arf! +Sitting +Click! +Clank! +""" diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index 1b114ef7..ddca21c2 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -8,11 +8,11 @@ import onjava.*; import static onjava.Tuple.*; class MixinProxy implements InvocationHandler { - Map delegatesByMethod; + Map delegatesByMethod; @SuppressWarnings("unchecked") - public MixinProxy(Tuple2>... pairs) { + public MixinProxy(Tuple2>... pairs) { delegatesByMethod = new HashMap<>(); - for(Tuple2> pair : pairs) { + for(Tuple2> pair : pairs) { for(Method method : pair._2.getMethods()) { String methodName = method.getName(); // The first interface in the map @@ -47,7 +47,8 @@ public class DynamicProxyMixin { Object mixin = MixinProxy.newInstance( tuple(new BasicImp(), Basic.class), tuple(new TimeStampedImp(), TimeStamped.class), - tuple(new SerialNumberedImp(),SerialNumbered.class)); + tuple(new SerialNumberedImp(), + SerialNumbered.class)); Basic b = (Basic)mixin; TimeStamped t = (TimeStamped)mixin; SerialNumbered s = (SerialNumbered)mixin; diff --git a/generics/EpicBattle.java b/generics/EpicBattle.java index 1e6c70c6..87729083 100644 --- a/generics/EpicBattle.java +++ b/generics/EpicBattle.java @@ -2,16 +2,19 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrating bounds in Java generics. +// Bounds in Java generics import java.util.*; interface SuperPower {} + interface XRayVision extends SuperPower { void seeThroughWalls(); } + interface SuperHearing extends SuperPower { void hearSubtleNoises(); } + interface SuperSmell extends SuperPower { void trackBySmell(); } @@ -42,8 +45,8 @@ class SuperHearSmell implements SuperHearing, SuperSmell { public void trackBySmell() {} } -class DogBoy extends CanineHero { - DogBoy() { super(new SuperHearSmell()); } +class DogPerson extends CanineHero { + DogPerson() { super(new SuperHearSmell()); } } public class EpicBattle { @@ -58,12 +61,12 @@ public class EpicBattle { hero.getPower().trackBySmell(); } public static void main(String[] args) { - DogBoy dogBoy = new DogBoy(); - useSuperHearing(dogBoy); - superFind(dogBoy); + DogPerson dogPerson = new DogPerson(); + useSuperHearing(dogPerson); + superFind(dogPerson); // You can do this: - List audioBoys; + List audioPeople; // But you can't do this: - // List dogBoys; + // List dogPs; } } diff --git a/generics/Erased.java b/generics/Erased.java index 92500508..ff097663 100644 --- a/generics/Erased.java +++ b/generics/Erased.java @@ -6,10 +6,19 @@ public class Erased { private final int SIZE = 100; - public static void f(Object arg) { - if(arg instanceof T) {} // Error - T var = new T(); // Error - T[] array = new T[SIZE]; // Error - T[] array = (T)new Object[SIZE]; // Unchecked warning + public void f(Object arg) { + + // error: illegal generic type for instanceof + if(arg instanceof T) {} + + // error: unexpected type + T var = new T(); + + // error: generic array creation + T[] array = new T[SIZE]; + + // warning: [unchecked] unchecked cast + T[] array = (T[])new Object[SIZE]; + } } diff --git a/generics/ErasureAndInheritance.java b/generics/ErasureAndInheritance.java index 19788e9d..f31e0355 100644 --- a/generics/ErasureAndInheritance.java +++ b/generics/ErasureAndInheritance.java @@ -15,7 +15,7 @@ class Derived2 extends GenericBase {} // No warning // class Derived3 extends GenericBase {} // Strange error: -// unexpected type found : ? +// unexpected type // required: class or interface without bounds public class ErasureAndInheritance { diff --git a/generics/FactoryConstraint.java b/generics/FactoryConstraint.java index 32a43e82..6e6aaa99 100644 --- a/generics/FactoryConstraint.java +++ b/generics/FactoryConstraint.java @@ -2,38 +2,58 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.*; +import java.util.function.*; +import onjava.*; -interface FactoryI { - T create(); -} - -class Foo2 { - private T x; - public > Foo2(F factory) { - x = factory.create(); - } - // ... -} - -class IntegerFactory implements FactoryI { +class IntegerFactory implements Supplier { + private int i = 0; @Override - public Integer create() { - return 0; + public Integer get() { + return ++i; } } class Widget { - public static class Factory implements FactoryI { - @Override - public Widget create() { - return new Widget(); - } + private int id; + public Widget(int n) { id = n; } + @Override + public String toString() { + return "Widget " + id; } + public static + class Factory implements Supplier { + private int i = 0; + @Override + public Widget get() { return new Widget(++i); } + } +} + +class Fudge { + private static int count = 1; + private int n = count++; + @Override + public String toString() { return "Fudge " + n; } +} + +class Foo2 { + private List x = new ArrayList<>(); + public Foo2(Supplier factory) { + Suppliers.fill(x, factory, 5); + } + @Override + public String toString() { return x.toString(); } } public class FactoryConstraint { public static void main(String[] args) { - new Foo2<>(new IntegerFactory()); - new Foo2<>(new Widget.Factory()); + System.out.println(new Foo2<>(new IntegerFactory())); + System.out.println(new Foo2<>(new Widget.Factory())); + System.out.println(new Foo2<>(Fudge::new)); } } +/* Output: +[1, 2, 3, 4, 5] +[Widget 1, Widget 2, Widget 3, Widget 4, Widget 5] +[Fudge 1, Fudge 2, Fudge 3, Fudge 4, Fudge 5] +*/ diff --git a/generics/Fibonacci.java b/generics/Fibonacci.java index acb1af9c..48725bd7 100644 --- a/generics/Fibonacci.java +++ b/generics/Fibonacci.java @@ -2,8 +2,9 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Generate a Fibonacci sequence. +// Generate a Fibonacci sequence import java.util.function.*; +import java.util.stream.*; public class Fibonacci implements Supplier { private int count = 0; @@ -14,9 +15,10 @@ public class Fibonacci implements Supplier { return fib(n-2) + fib(n-1); } public static void main(String[] args) { - Fibonacci gen = new Fibonacci(); - for(int i = 0; i < 18; i++) - System.out.print(gen.get() + " "); + Stream.generate(new Fibonacci()) + .limit(18) + .map(n -> n + " ") + .forEach(System.out::print); } } /* Output: diff --git a/generics/Fill.java b/generics/Fill.java deleted file mode 100644 index 56923764..00000000 --- a/generics/Fill.java +++ /dev/null @@ -1,57 +0,0 @@ -// generics/Fill.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Generalizing the FilledList idea -// {main: FillTest} -import java.util.*; - -// Doesn't work with "anything that has an add()." There is -// no "Addable" interface so we are narrowed to using a -// Collection. We cannot generalize using generics in -// this case. -public class Fill { - public static void fill(Collection collection, - Class classToken, int size) { - for(int i = 0; i < size; i++) - // Assumes no-arg constructor: - try { - collection.add(classToken.newInstance()); - } catch(InstantiationException | - IllegalAccessException e) { - throw new RuntimeException(e); - } - } -} - -class Contract { - private static long counter = 0; - private final long id = counter++; - @Override - public String toString() { - return getClass().getName() + " " + id; - } -} - -class TitleTransfer extends Contract {} - -class FillTest { - public static void main(String[] args) { - List contracts = new ArrayList<>(); - Fill.fill(contracts, Contract.class, 3); - Fill.fill(contracts, TitleTransfer.class, 2); - for(Contract c: contracts) - System.out.println(c); - SimpleQueue contractQueue = - new SimpleQueue<>(); - // Won't work. fill() is not generic enough: - // Fill.fill(contractQueue, Contract.class, 3); - } -} -/* Output: -Contract 0 -Contract 1 -Contract 2 -TitleTransfer 3 -TitleTransfer 4 -*/ diff --git a/generics/Fill2.java b/generics/Fill2.java deleted file mode 100644 index 0475839f..00000000 --- a/generics/Fill2.java +++ /dev/null @@ -1,94 +0,0 @@ -// generics/Fill2.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using adapters to simulate latent typing. -// {main: Fill2Test} -import generics.coffee.*; -import java.util.*; -import java.util.function.*; - -interface Addable { void add(T t); } - -public class Fill2 { - // Classtoken version: - public static void fill(Addable addable, - Class classToken, int size) { - for(int i = 0; i < size; i++) - try { - addable.add(classToken.newInstance()); - } catch(InstantiationException | - IllegalAccessException e) { - throw new RuntimeException(e); - } - } - // Supplier version: - public static void fill(Addable addable, - Supplier generator, int size) { - for(int i = 0; i < size; i++) - addable.add(generator.get()); - } -} - -// To adapt a base type, you must use composition. -// Make any Collection Addable using composition: -class AddableCollectionAdapter implements Addable { - private Collection c; - public AddableCollectionAdapter(Collection c) { - this.c = c; - } - @Override - public void add(T item) { c.add(item); } -} - -// A Helper to capture the type automatically: -class Adapter { - public static - Addable collectionAdapter(Collection c) { - return new AddableCollectionAdapter<>(c); - } -} - -// To adapt a specific type, you can use inheritance. -// Make a SimpleQueue Addable using inheritance: -class AddableSimpleQueue -extends SimpleQueue implements Addable { - @Override - public void add(T item) { super.add(item); } -} - -class Fill2Test { - public static void main(String[] args) { - // Adapt a Collection: - List carrier = new ArrayList<>(); - Fill2.fill( - new AddableCollectionAdapter<>(carrier), - Coffee.class, 3); - // Helper method captures the type: - Fill2.fill(Adapter.collectionAdapter(carrier), - Latte.class, 2); - for(Coffee c: carrier) - System.out.println(c); - System.out.println("----------------------"); - // Use an adapted class: - AddableSimpleQueue coffeeQueue = - new AddableSimpleQueue<>(); - Fill2.fill(coffeeQueue, Mocha.class, 4); - Fill2.fill(coffeeQueue, Latte.class, 1); - for(Coffee c: coffeeQueue) - System.out.println(c); - } -} -/* Output: -Coffee 0 -Coffee 1 -Coffee 2 -Latte 3 -Latte 4 ----------------------- -Mocha 5 -Mocha 6 -Mocha 7 -Mocha 8 -Latte 9 -*/ diff --git a/generics/Functional.java b/generics/Functional.java deleted file mode 100644 index e383c778..00000000 --- a/generics/Functional.java +++ /dev/null @@ -1,191 +0,0 @@ -// generics/Functional.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.math.*; -import java.util.concurrent.atomic.*; -import java.util.*; - -// Different types of function objects: -interface Combiner { T combine(T x, T y); } -interface UnaryFunction { R function(T x); } -interface Collector extends UnaryFunction { - T result(); // Extract result of collecting parameter -} -interface UnaryPredicate { boolean test(T x); } - -public class Functional { - // Calls the Combiner object on each element to combine - // it with a running result, which is finally returned: - public static T - reduce(Iterable seq, Combiner combiner) { - Iterator it = seq.iterator(); - if(it.hasNext()) { - T result = it.next(); - while(it.hasNext()) - result = combiner.combine(result, it.next()); - return result; - } - // If seq is the empty list: - return null; // Or throw exception - } - // Take a function object and call it on each object in - // the list, ignoring the return value. The function - // object can act as a collecting parameter, so it is - // returned at the end. - public static Collector - forIn(Iterable seq, Collector func) { - for(T t : seq) - func.function(t); - return func; - } - // Creates a list of results by calling a - // function object for each object in the list: - public static List - transform(Iterable seq, UnaryFunction func) { - List result = new ArrayList<>(); - for(T t : seq) - result.add(func.function(t)); - return result; - } - // Applies a unary predicate to each item in a sequence, - // and returns a list of items that produced "true": - public static List - filter(Iterable seq, UnaryPredicate pred) { - List result = new ArrayList<>(); - for(T t : seq) - if(pred.test(t)) - result.add(t); - return result; - } - // To use the above generic methods, we create - // function objects to adapt to our particular needs: - static class IntegerAdder implements Combiner { - @Override - public Integer combine(Integer x, Integer y) { - return x + y; - } - } - static class - IntegerSubtracter implements Combiner { - @Override - public Integer combine(Integer x, Integer y) { - return x - y; - } - } - static class - BigDecimalAdder implements Combiner { - @Override - public BigDecimal combine(BigDecimal x, BigDecimal y){ - return x.add(y); - } - } - static class - BigIntegerAdder implements Combiner { - @Override - public BigInteger combine(BigInteger x, BigInteger y){ - return x.add(y); - } - } - static class - AtomicLongAdder implements Combiner { - @Override - public AtomicLong combine(AtomicLong x, AtomicLong y){ - // Not clear whether this is meaningful: - return new AtomicLong(x.addAndGet(y.get())); - } - } - // We can even make a UnaryFunction with an "ulp" - // (Units in the last place): - static class BigDecimalUlp - implements UnaryFunction { - @Override - public BigDecimal function(BigDecimal x) { - return x.ulp(); - } - } - static class GreaterThan> - implements UnaryPredicate { - private T bound; - public GreaterThan(T bound) { this.bound = bound; } - @Override - public boolean test(T x) { - return x.compareTo(bound) > 0; - } - } - static class MultiplyingIntegerCollector - implements Collector { - private Integer val = 1; - @Override - public Integer function(Integer x) { - val *= x; - return val; - } - @Override - public Integer result() { return val; } - } - public static void main(String[] args) { - // Generics, varargs & boxing working together: - List li = Arrays.asList(1, 2, 3, 4, 5, 6, 7); - Integer result = reduce(li, new IntegerAdder()); - System.out.println(result); - - result = reduce(li, new IntegerSubtracter()); - System.out.println(result); - - System.out.println(filter(li, new GreaterThan<>(4))); - - System.out.println(forIn(li, - new MultiplyingIntegerCollector()).result()); - - System.out.println( - forIn(filter(li, new GreaterThan<>(4)), - new MultiplyingIntegerCollector()).result()); - - MathContext mc = new MathContext(7); - List lbd = Arrays.asList( - new BigDecimal(1.1, mc), new BigDecimal(2.2, mc), - new BigDecimal(3.3, mc), new BigDecimal(4.4, mc)); - BigDecimal rbd = reduce(lbd, new BigDecimalAdder()); - System.out.println(rbd); - - System.out.println(filter(lbd, - new GreaterThan<>(new BigDecimal(3)))); - - // Use the prime-generation facility of BigInteger: - List lbi = new ArrayList<>(); - BigInteger bi = BigInteger.valueOf(11); - for(int i = 0; i < 11; i++) { - lbi.add(bi); - bi = bi.nextProbablePrime(); - } - System.out.println(lbi); - - BigInteger rbi = reduce(lbi, new BigIntegerAdder()); - System.out.println(rbi); - // The sum of this list of primes is also prime: - System.out.println(rbi.isProbablePrime(5)); - - List lal = Arrays.asList( - new AtomicLong(11), new AtomicLong(47), - new AtomicLong(74), new AtomicLong(133)); - AtomicLong ral = reduce(lal, new AtomicLongAdder()); - System.out.println(ral); - - System.out.println(transform(lbd, new BigDecimalUlp())); - } -} -/* Output: -28 --26 -[5, 6, 7] -5040 -210 -11.000000 -[3.300000, 4.400000] -[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] -311 -true -265 -[0.000001, 0.000001, 0.000001, 0.000001] -*/ diff --git a/generics/GenericArray.java b/generics/GenericArray.java index cc469d93..022630e2 100644 --- a/generics/GenericArray.java +++ b/generics/GenericArray.java @@ -17,9 +17,15 @@ public class GenericArray { public T[] rep() { return array; } public static void main(String[] args) { GenericArray gai = new GenericArray<>(10); - // This causes a ClassCastException: - //- Integer[] ia = gai.rep(); + try { + Integer[] ia = gai.rep(); + } catch(ClassCastException e) { + System.out.println(e.getMessage()); + } // This is OK: Object[] oa = gai.rep(); } } +/* Output: +[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; +*/ diff --git a/generics/GenericArray2.java b/generics/GenericArray2.java index f1e42205..d3df5a9a 100644 --- a/generics/GenericArray2.java +++ b/generics/GenericArray2.java @@ -15,7 +15,7 @@ public class GenericArray2 { public T get(int index) { return (T)array[index]; } @SuppressWarnings("unchecked") public T[] rep() { - return (T[])array; // Warning: unchecked cast + return (T[])array; // Unchecked cast } public static void main(String[] args) { GenericArray2 gai = diff --git a/generics/GenericArrayWithTypeToken.java b/generics/GenericArrayWithTypeToken.java index 6af6b0c2..46e42754 100644 --- a/generics/GenericArrayWithTypeToken.java +++ b/generics/GenericArrayWithTypeToken.java @@ -7,7 +7,8 @@ import java.lang.reflect.*; public class GenericArrayWithTypeToken { private T[] array; @SuppressWarnings("unchecked") - public GenericArrayWithTypeToken(Class type, int sz) { + public + GenericArrayWithTypeToken(Class type, int sz) { array = (T[])Array.newInstance(type, sz); } public void put(int index, T item) { diff --git a/generics/GenericCast.java b/generics/GenericCast.java index 7b750ea7..6c4470ce 100644 --- a/generics/GenericCast.java +++ b/generics/GenericCast.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://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.stream.*; class FixedSizeStack { private int index = 0; @@ -19,12 +20,10 @@ public class GenericCast { public static void main(String[] args) { FixedSizeStack strings = new FixedSizeStack<>(SIZE); - for(String s : "A B C D E F G H I J".split(" ")) - strings.push(s); - for(int i = 0; i < SIZE; i++) { - String s = strings.pop(); - System.out.print(s + " "); - } + Stream.of("A B C D E F G H I J".split(" ")) + .forEach(s -> strings.push(s)); + for(int i = 0; i < SIZE; i++) + System.out.print(strings.pop() + " "); } } /* Output: diff --git a/generics/GenericHolder.java b/generics/GenericHolder.java index 7dfbcd8f..185d4660 100644 --- a/generics/GenericHolder.java +++ b/generics/GenericHolder.java @@ -13,7 +13,7 @@ public class GenericHolder { new GenericHolder(); h3.set(new Automobile()); // type checked Automobile a = h3.get(); // No cast needed - // h3.set("Not an Automobile"); // Error - // h3.set(1); // Error + //- h3.set("Not an Automobile"); // Error + //- h3.set(1); // Error } } diff --git a/generics/GenericReading.java b/generics/GenericReading.java index 78cae0d3..95964b23 100644 --- a/generics/GenericReading.java +++ b/generics/GenericReading.java @@ -5,18 +5,18 @@ import java.util.*; public class GenericReading { + static List apples = Arrays.asList(new Apple()); + static List fruit = Arrays.asList(new Fruit()); static T readExact(List list) { return list.get(0); } - static List apples = Arrays.asList(new Apple()); - static List fruit = Arrays.asList(new Fruit()); // A static method adapts to each call: static void f1() { Apple a = readExact(apples); Fruit f = readExact(fruit); f = readExact(apples); } - // If, however, you have a class, then its type is + // If you have a class, its type is // established when the class is instantiated: static class Reader { T readExact(List list) { return list.get(0); } @@ -24,9 +24,9 @@ public class GenericReading { static void f2() { Reader fruitReader = new Reader<>(); Fruit f = fruitReader.readExact(fruit); - // Fruit a = fruitReader.readExact(apples); // Error: - // readExact(List) cannot be - // applied to (List). + //- Fruit a = fruitReader.readExact(apples); + // error: incompatible types: List + // cannot be converted to List } static class CovariantReader { T readCovariant(List list) { diff --git a/generics/GenericVarargs.java b/generics/GenericVarargs.java index f91cf822..e93383fc 100644 --- a/generics/GenericVarargs.java +++ b/generics/GenericVarargs.java @@ -5,7 +5,7 @@ import java.util.*; public class GenericVarargs { - @SuppressWarnings("unchecked") + @SafeVarargs public static List makeList(T... args) { List result = new ArrayList<>(); for(T item : args) diff --git a/generics/GenericWriting.java b/generics/GenericWriting.java deleted file mode 100644 index ddd0661b..00000000 --- a/generics/GenericWriting.java +++ /dev/null @@ -1,26 +0,0 @@ -// generics/GenericWriting.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -import java.util.*; - -public class GenericWriting { - static void writeExact(List list, T item) { - list.add(item); - } - static List apples = new ArrayList<>(); - static List fruit = new ArrayList<>(); - static void f1() { - writeExact(apples, new Apple()); - writeExact(fruit, new Apple()); - } - static void - writeWithWildcard(List list, T item) { - list.add(item); - } - static void f2() { - writeWithWildcard(apples, new Apple()); - writeWithWildcard(fruit, new Apple()); - } - public static void main(String[] args) { f1(); f2(); } -} diff --git a/generics/HijackedInterface.java b/generics/HijackedInterface.java index c3542784..843694fa 100644 --- a/generics/HijackedInterface.java +++ b/generics/HijackedInterface.java @@ -4,8 +4,13 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {CompileTimeError} (Won't compile) -class Cat extends ComparablePet implements Comparable{ - // Error: Comparable cannot be inherited with - // different arguments: and +class Cat + extends ComparablePet implements Comparable{ + // error: Comparable cannot be inherited with + // different arguments: and + // class Cat + // ^ + // 1 error + public int compareTo(Cat arg) { return 0; } } diff --git a/generics/Holder.java b/generics/Holder.java index 7d92f306..75c6a59e 100644 --- a/generics/Holder.java +++ b/generics/Holder.java @@ -14,11 +14,11 @@ public class Holder { return value.equals(obj); } public static void main(String[] args) { - Holder Apple = new Holder<>(new Apple()); - Apple d = Apple.get(); - Apple.set(d); - // Holder Fruit = Apple; // Cannot upcast - Holder fruit = Apple; // OK + Holder apple = new Holder<>(new Apple()); + Apple d = apple.get(); + apple.set(d); + // Holder Fruit = apple; // Cannot upcast + Holder fruit = apple; // OK Fruit p = fruit.get(); d = (Apple)fruit.get(); // Returns 'Object' try { diff --git a/generics/InheritBounds.java b/generics/InheritBounds.java index 5158352e..fea74c3d 100644 --- a/generics/InheritBounds.java +++ b/generics/InheritBounds.java @@ -9,21 +9,21 @@ class HoldItem { T getItem() { return item; } } -class Colored2 extends HoldItem { - Colored2(T item) { super(item); } +class WithColor2 extends HoldItem { + WithColor2(T item) { super(item); } java.awt.Color color() { return item.getColor(); } } -class ColoredDimension2 -extends Colored2 { - ColoredDimension2(T item) { super(item); } +class WithColorCoord2 +extends WithColor2 { + WithColorCoord2(T item) { super(item); } int getX() { return item.x; } int getY() { return item.y; } int getZ() { return item.z; } } -class Solid2 -extends ColoredDimension2 { +class Solid2 +extends WithColorCoord2 { Solid2(T item) { super(item); } int weight() { return item.weight(); } } diff --git a/generics/InstantiateGenericType.java b/generics/InstantiateGenericType.java index 9925f16a..d4a05636 100644 --- a/generics/InstantiateGenericType.java +++ b/generics/InstantiateGenericType.java @@ -2,12 +2,17 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. +import java.util.function.*; -class ClassAsFactory { - T x; +class ClassAsFactory implements Supplier { + Class kind; public ClassAsFactory(Class kind) { + this.kind = kind; + } + @Override + public T get() { try { - x = kind.newInstance(); + return kind.newInstance(); } catch(InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); @@ -15,23 +20,26 @@ class ClassAsFactory { } } -class Employee {} +class Employee { + @Override + public String toString() { return "Employee"; } +} public class InstantiateGenericType { public static void main(String[] args) { ClassAsFactory fe = new ClassAsFactory<>(Employee.class); - System.out.println( - "ClassAsFactory succeeded"); + System.out.println(fe.get()); + ClassAsFactory fi = + new ClassAsFactory<>(Integer.class); try { - ClassAsFactory fi = - new ClassAsFactory<>(Integer.class); + System.out.println(fi.get()); } catch(Exception e) { - System.out.println("ClassAsFactory failed"); + System.out.println(e.getMessage()); } } } /* Output: -ClassAsFactory succeeded -ClassAsFactory failed +Employee +java.lang.InstantiationException: java.lang.Integer */ diff --git a/generics/IterableFibonacci.java b/generics/IterableFibonacci.java index ecb84681..ff34d040 100644 --- a/generics/IterableFibonacci.java +++ b/generics/IterableFibonacci.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://mindviewinc.com/Books/OnJava/ for more book information. -// Adapt the Fibonacci class to make it Iterable. +// Adapt the Fibonacci class to make it Iterable import java.util.*; public class IterableFibonacci diff --git a/generics/LatentReflection.java b/generics/LatentReflection.java index 66ece0b8..4a49a139 100644 --- a/generics/LatentReflection.java +++ b/generics/LatentReflection.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using Reflection to produce latent typing. +// Using reflection for latent typing import java.lang.reflect.*; // Does not implement Performs: diff --git a/generics/LinkedStack.java b/generics/LinkedStack.java index b2a2d74a..8b9a9b7d 100644 --- a/generics/LinkedStack.java +++ b/generics/LinkedStack.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://mindviewinc.com/Books/OnJava/ for more book information. -// A stack implemented with an internal linked structure. +// A stack implemented with an internal linked structure public class LinkedStack { private static class Node { @@ -13,7 +13,9 @@ public class LinkedStack { this.item = item; this.next = next; } - boolean end() { return item == null && next == null; } + boolean end() { + return item == null && next == null; + } } private Node top = new Node<>(); // End sentinel public void push(T item) { diff --git a/generics/ListMaker.java b/generics/ListMaker.java index 94bfaa8a..2760aaee 100644 --- a/generics/ListMaker.java +++ b/generics/ListMaker.java @@ -7,7 +7,7 @@ import java.util.*; public class ListMaker { List create() { return new ArrayList<>(); } public static void main(String[] args) { - ListMaker stringMaker= new ListMaker<>(); + ListMaker stringMaker = new ListMaker<>(); List stringList = stringMaker.create(); } } diff --git a/generics/ListOfInt.java b/generics/ListOfInt.java index 50b0c66d..0d08a5a2 100644 --- a/generics/ListOfInt.java +++ b/generics/ListOfInt.java @@ -2,19 +2,19 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Autoboxing compensates for the inability to use -// primitives in generics. +// Autoboxing compensates for the inability +// to use primitives in generics import java.util.*; +import java.util.stream.*; public class ListOfInt { public static void main(String[] args) { - List li = new ArrayList<>(); - for(int i = 0; i < 5; i++) - li.add(i); - for(int i : li) - System.out.print(i + " "); + List li = IntStream.range(38, 48) + .boxed() // Converts ints to Integers + .collect(Collectors.toList()); + System.out.println(li); } } /* Output: -0 1 2 3 4 +[38, 39, 40, 41, 42, 43, 44, 45, 46, 47] */ diff --git a/generics/LostInformation.java b/generics/LostInformation.java index 8d9e859f..140cb46e 100644 --- a/generics/LostInformation.java +++ b/generics/LostInformation.java @@ -7,14 +7,14 @@ import java.util.*; class Frob {} class Fnorkle {} class Quark {} -class Particle {} +class Particle {} public class LostInformation { public static void main(String[] args) { List list = new ArrayList<>(); - Map map = new HashMap<>(); + Map map = new HashMap<>(); Quark quark = new Quark<>(); - Particle p = new Particle<>(); + Particle p = new Particle<>(); System.out.println(Arrays.toString( list.getClass().getTypeParameters())); System.out.println(Arrays.toString( diff --git a/generics/Mixins.cpp b/generics/Mixins.cpp index 03fb4b55..e7bba20e 100644 --- a/generics/Mixins.cpp +++ b/generics/Mixins.cpp @@ -41,3 +41,7 @@ int main() { cout << mixin2.get() << " " << mixin2.getStamp() << " " << mixin2.getSerialNumber() << endl; } +/* Output: +test string 1 1452987605 1 +test string 2 1452987605 2 +*/ diff --git a/generics/Mixins.java b/generics/Mixins.java index 0df21c4e..1234958e 100644 --- a/generics/Mixins.java +++ b/generics/Mixins.java @@ -56,9 +56,11 @@ public class Mixins { mixin1.set("test string 1"); mixin2.set("test string 2"); System.out.println(mixin1.get() + " " + - mixin1.getStamp() + " " + mixin1.getSerialNumber()); + mixin1.getStamp() + " " + + mixin1.getSerialNumber()); System.out.println(mixin2.get() + " " + - mixin2.getStamp() + " " + mixin2.getSerialNumber()); + mixin2.getStamp() + " " + + mixin2.getSerialNumber()); } } /* Output: diff --git a/generics/MultipleInterfaceVariants.java b/generics/MultipleInterfaceVariants.java index f8d4611c..e65baefd 100644 --- a/generics/MultipleInterfaceVariants.java +++ b/generics/MultipleInterfaceVariants.java @@ -7,5 +7,6 @@ interface Payable {} class Employee implements Payable {} + class Hourly extends Employee - implements Payable {} +implements Payable {} diff --git a/generics/PlainGenericInheritance.java b/generics/PlainGenericInheritance.java index 699fae9c..6365d653 100644 --- a/generics/PlainGenericInheritance.java +++ b/generics/PlainGenericInheritance.java @@ -4,13 +4,13 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. class GenericSetter { // Not self-bounded - void set(T arg){ + void set(T arg) { System.out.println("GenericSetter.set(Base)"); } } class DerivedGS extends GenericSetter { - void set(Derived derived){ + void set(Derived derived) { System.out.println("DerivedGS.set(Derived)"); } } @@ -21,7 +21,7 @@ public class PlainGenericInheritance { Derived derived = new Derived(); DerivedGS dgs = new DerivedGS(); dgs.set(derived); - dgs.set(base); // Compiles: overloaded, not overridden! + dgs.set(base); // Overloaded, not overridden! } } /* Output: diff --git a/generics/PrimitiveGenericTest.java b/generics/PrimitiveGenericTest.java index a548273c..e4f95e2f 100644 --- a/generics/PrimitiveGenericTest.java +++ b/generics/PrimitiveGenericTest.java @@ -3,45 +3,44 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. import onjava.*; +import java.util.*; import java.util.function.*; // Fill an array using a generator: -class FArray { - public static T[] fill(T[] a, Supplier gen) { +interface FillArray { + static T[] fill(T[] a, Supplier gen) { for(int i = 0; i < a.length; i++) a[i] = gen.get(); return a; } + static int[] fill(int[] a, IntSupplier gen) { + for(int i = 0; i < a.length; i++) + a[i] = gen.getAsInt(); + return a; + } + static long[] fill(long[] a, LongSupplier gen) { + for(int i = 0; i < a.length; i++) + a[i] = gen.getAsLong(); + return a; + } + static double[] fill(double[] a, DoubleSupplier gen) { + for(int i = 0; i < a.length; i++) + a[i] = gen.getAsDouble(); + return a; + } } public class PrimitiveGenericTest { public static void main(String[] args) { - String[] strings = FArray.fill( - new String[7], new RandomSupplier.String(10)); - for(String s : strings) - System.out.println(s); - Integer[] integers = FArray.fill( - new Integer[7], new RandomSupplier.Integer()); - for(int i: integers) - System.out.println(i); - // Autoboxing won't save you here. This won't compile: - // int[] b = - // FArray.fill(new int[7], new RandIntSupplier()); + String[] strings = FillArray.fill( + new String[5], new Rand.String(9)); + System.out.println(Arrays.toString(strings)); + int[] integers = FillArray.fill( + new int[9], new Rand.int_()); + System.out.println(Arrays.toString(integers)); } } /* Output: -YNzbrnyGcF -OWZnTcQrGs -eGZMmJMRoE -suEcUOneOE -dLsmwHLGEa -hKcxrEqUCB -bkInaMesbt -7052 -6665 -2654 -3909 -5202 -2209 -5458 +[YNzbrnyGc, FOWZnTcQr, GseGZMmJM, RoEsuEcUO, neOEdLsmw] +[8689, 7185, 6992, 5746, 3976, 2447, 5368, 1854, 1395] */ diff --git a/generics/RandomList.java b/generics/RandomList.java index 72047ab9..3d68999c 100644 --- a/generics/RandomList.java +++ b/generics/RandomList.java @@ -5,12 +5,10 @@ import java.util.*; import java.util.stream.*; -public class RandomList { - private ArrayList items = new ArrayList<>(); +public class RandomList extends ArrayList { private Random rand = new Random(47); - public void add(T item) { items.add(item); } public T select() { - return items.get(rand.nextInt(items.size())); + return get(rand.nextInt(size())); } public static void main(String[] args) { RandomList rs = new RandomList<>(); diff --git a/generics/SelfBoundingAndCovariantArguments.java b/generics/SelfBoundingAndCovariantArguments.java index 13d8e059..89d688d0 100644 --- a/generics/SelfBoundingAndCovariantArguments.java +++ b/generics/SelfBoundingAndCovariantArguments.java @@ -12,8 +12,18 @@ interface Setter extends SelfBoundSetter {} public class SelfBoundingAndCovariantArguments { void testA(Setter s1, Setter s2, SelfBoundSetter sbs) { s1.set(s2); - // s1.set(sbs); // Error: - // set(Setter) in SelfBoundSetter - // cannot be applied to (SelfBoundSetter) + //- s1.set(sbs); + // error: method set in interface SelfBoundSetter + // cannot be applied to given types; + // s1.set(sbs); + // ^ + // required: Setter + // found: SelfBoundSetter + // reason: argument mismatch; + // SelfBoundSetter cannot be converted to Setter + // where T is a type-variable: + // T extends SelfBoundSetter declared in + // interface SelfBoundSetter + // 1 error } } diff --git a/generics/SimpleDogsAndRobots.java b/generics/SimpleDogsAndRobots.java index 3a7473dd..564147d8 100644 --- a/generics/SimpleDogsAndRobots.java +++ b/generics/SimpleDogsAndRobots.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://mindviewinc.com/Books/OnJava/ for more book information. -// Removing the generic; code still works. +// Removing the generic; code still works class CommunicateSimply { static void perform(Performs performer) { diff --git a/generics/Store.java b/generics/Store.java index 02c096b2..fe514fb3 100644 --- a/generics/Store.java +++ b/generics/Store.java @@ -2,15 +2,17 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Building up a complex model using generic collections. +// Building a complex model using generic collections import java.util.*; import java.util.function.*; +import onjava.*; class Product { private final int id; private String description; private double price; - public Product(int IDnumber, String descr, double price){ + public + Product(int IDnumber, String descr, double price) { id = IDnumber; description = descr; this.price = price; diff --git a/generics/Suppliers.java b/generics/Suppliers.java deleted file mode 100644 index 3c744fd6..00000000 --- a/generics/Suppliers.java +++ /dev/null @@ -1,34 +0,0 @@ -// generics/Suppliers.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A utility to use with Suppliers. -import generics.coffee.*; -import java.util.*; -import java.util.function.*; - -public class Suppliers { - public static Collection - fill(Collection coll, Supplier gen, int n) { - for(int i = 0; i < n; i++) - coll.add(gen.get()); - return coll; - } - public static void main(String[] args) { - Collection coffee = fill( - new ArrayList<>(), new CoffeeSupplier(), 4); - for(Coffee c : coffee) - System.out.println(c); - Collection fnumbers = fill( - new ArrayList<>(), new Fibonacci(), 12); - for(int i : fnumbers) - System.out.print(i + ", "); - } -} -/* Output: -Americano 0 -Latte 1 -Americano 2 -Mocha 3 -1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, -*/ diff --git a/generics/Templates.cpp b/generics/Templates.cpp index abc9b23d..556c08d8 100644 --- a/generics/Templates.cpp +++ b/generics/Templates.cpp @@ -22,3 +22,6 @@ int main() { Manipulator manipulator(hf); manipulator.manipulate(); } +/* Output: +HasF::f() +*/ diff --git a/generics/ThrowGenericException.java b/generics/ThrowGenericException.java index 9d038d9f..679fc8bc 100644 --- a/generics/ThrowGenericException.java +++ b/generics/ThrowGenericException.java @@ -4,15 +4,15 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. import java.util.*; -interface Processor { +interface Processor { void process(List resultCollector) throws E; } -class ProcessRunner -extends ArrayList> { +class ProcessRunner +extends ArrayList> { List processAll() throws E { List resultCollector = new ArrayList<>(); - for(Processor processor : this) + for(Processor processor : this) processor.process(resultCollector); return resultCollector; } @@ -20,7 +20,7 @@ extends ArrayList> { class Failure1 extends Exception {} -class Processor1 implements Processor { +class Processor1 implements Processor { static int count = 3; @Override public void @@ -36,7 +36,7 @@ class Processor1 implements Processor { class Failure2 extends Exception {} -class Processor2 implements Processor { +class Processor2 implements Processor { static int count = 2; @Override public void @@ -53,7 +53,7 @@ class Processor2 implements Processor { public class ThrowGenericException { public static void main(String[] args) { - ProcessRunner runner = + ProcessRunner runner = new ProcessRunner<>(); for(int i = 0; i < 3; i++) runner.add(new Processor1()); @@ -63,7 +63,7 @@ public class ThrowGenericException { System.out.println(e); } - ProcessRunner runner2 = + ProcessRunner runner2 = new ProcessRunner<>(); for(int i = 0; i < 3; i++) runner2.add(new Processor2()); diff --git a/generics/TupleList.java b/generics/TupleList.java index 71b34f9e..2c96a07b 100644 --- a/generics/TupleList.java +++ b/generics/TupleList.java @@ -2,22 +2,22 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Combining generic types to make complex generic types. +// Combining generic types to make complex generic types import java.util.*; import onjava.*; +import java.util.stream.*; public class TupleList extends ArrayList> { public static void main(String[] args) { TupleList tl = new TupleList<>(); - tl.add(TupleTest.h()); - tl.add(TupleTest.h()); - for(Tuple4 i: tl) - System.out.println(i); + tl.add(TupleTest2.h()); + tl.add(TupleTest2.h()); + tl.forEach(System.out::println); } } /* Output: -(Vehicle@139a55, Amphibian@1db9742, hi, 47) -(Vehicle@106d69c, Amphibian@52e922, hi, 47) +(Vehicle@18025c, Amphibian@16f27d, hi, 47) +(Vehicle@7aac27, Amphibian@3abc88, hi, 47) */ diff --git a/generics/TupleTest.java b/generics/TupleTest.java index e484a145..8cafff70 100644 --- a/generics/TupleTest.java +++ b/generics/TupleTest.java @@ -22,7 +22,7 @@ public class TupleTest { new Vehicle(), new Amphibian(), "hi", 47); } static - Tuple5 k(){ + Tuple5 k() { return new Tuple5<>( new Vehicle(), new Amphibian(), "hi", 47, 11.1); diff --git a/generics/TupleTest2.java b/generics/TupleTest2.java index 2710972b..d1ad478f 100644 --- a/generics/TupleTest2.java +++ b/generics/TupleTest2.java @@ -15,10 +15,11 @@ public class TupleTest2 { } static Tuple4 h() { - return tuple(new Vehicle(), new Amphibian(), "hi", 47); + return tuple( + new Vehicle(), new Amphibian(), "hi", 47); } static - Tuple5 k(){ + Tuple5 k() { return tuple(new Vehicle(), new Amphibian(), "hi", 47, 11.1); } diff --git a/generics/UnboundedWildcards1.java b/generics/UnboundedWildcards1.java index 169343b2..513e5211 100644 --- a/generics/UnboundedWildcards1.java +++ b/generics/UnboundedWildcards1.java @@ -11,8 +11,12 @@ public class UnboundedWildcards1 { static void assign1(List list) { list1 = list; list2 = list; - // list3 = list; // Warning: unchecked conversion - // Found: List, Required: List + //- list3 = list; + // warning: [unchecked] unchecked conversion + // list3 = list; + // ^ + // required: List + // found: List } static void assign2(List list) { list1 = list; @@ -27,9 +31,20 @@ public class UnboundedWildcards1 { public static void main(String[] args) { assign1(new ArrayList()); assign2(new ArrayList()); - // assign3(new ArrayList()); // Warning: - // Unchecked conversion. Found: ArrayList - // Required: List + //- assign3(new ArrayList()); + // warning: [unchecked] unchecked method invocation: + // method assign3 in class UnboundedWildcards1 + // is applied to given types + // assign3(new ArrayList()); + // ^ + // required: List + // found: ArrayList + // warning: [unchecked] unchecked conversion + // assign3(new ArrayList()); + // ^ + // required: List + // found: ArrayList + // 2 warnings assign1(new ArrayList<>()); assign2(new ArrayList<>()); assign3(new ArrayList<>()); diff --git a/generics/UnboundedWildcards2.java b/generics/UnboundedWildcards2.java index 2ef1f716..a0146164 100644 --- a/generics/UnboundedWildcards2.java +++ b/generics/UnboundedWildcards2.java @@ -14,9 +14,20 @@ public class UnboundedWildcards2 { public static void main(String[] args) { assign1(new HashMap()); assign2(new HashMap()); - // assign3(new HashMap()); // Warning: - // Unchecked conversion. Found: HashMap - // Required: Map + //- assign3(new HashMap()); + // warning: [unchecked] unchecked method invocation: + // method assign3 in class UnboundedWildcards2 + // is applied to given types + // assign3(new HashMap()); + // ^ + // required: Map + // found: HashMap + // warning: [unchecked] unchecked conversion + // assign3(new HashMap()); + // ^ + // required: Map + // found: HashMap + // 2 warnings assign1(new HashMap<>()); assign2(new HashMap<>()); assign3(new HashMap<>()); diff --git a/generics/Unconstrained.java b/generics/Unconstrained.java index 404c12d2..051ccdb8 100644 --- a/generics/Unconstrained.java +++ b/generics/Unconstrained.java @@ -8,7 +8,8 @@ class BasicOther extends BasicHolder {} public class Unconstrained { public static void main(String[] args) { - BasicOther b = new BasicOther(), b2 = new BasicOther(); + BasicOther b = new BasicOther(); + BasicOther b2 = new BasicOther(); b.set(new Other()); Other other = b.get(); b.f(); diff --git a/generics/UseList.java b/generics/UseList.java index 6a2be6c9..29a7e53f 100644 --- a/generics/UseList.java +++ b/generics/UseList.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {CompileTimeError} (Will not compile) -public class UseList { +public class UseList { void f(List v) {} void f(List v) {} } diff --git a/generics/UseList2.java b/generics/UseList2.java index 3891b1dc..c6e05533 100644 --- a/generics/UseList2.java +++ b/generics/UseList2.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. import java.util.*; -public class UseList2 { +public class UseList2 { void f1(List v) {} void f2(List v) {} } diff --git a/generics/WatercolorSets.java b/generics/WatercolorSets.java index 05644c56..673bf0be 100644 --- a/generics/WatercolorSets.java +++ b/generics/WatercolorSets.java @@ -35,19 +35,19 @@ COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE] set2: [CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, BURNT_UMBER] -union(set1, set2): [BRILLIANT_RED, BURNT_UMBER, -CERULEAN_BLUE_HUE, PHTHALO_BLUE, VIOLET, COBALT_BLUE_HUE, -CRIMSON, BURNT_SIENNA, ULTRAMARINE, PERMANENT_GREEN, -RAW_UMBER, VIRIDIAN_HUE, MAGENTA, SAP_GREEN, YELLOW_OCHRE, -ROSE_MADDER] -intersection(set1, set2): [ULTRAMARINE, PERMANENT_GREEN, -CERULEAN_BLUE_HUE, PHTHALO_BLUE, VIRIDIAN_HUE, -COBALT_BLUE_HUE] -difference(set1, subset): [BRILLIANT_RED, CRIMSON, MAGENTA, -ROSE_MADDER, VIOLET] -difference(set2, subset): [BURNT_SIENNA, BURNT_UMBER, -RAW_UMBER, SAP_GREEN, YELLOW_OCHRE] -complement(set1, set2): [BRILLIANT_RED, BURNT_UMBER, -VIOLET, CRIMSON, BURNT_SIENNA, RAW_UMBER, MAGENTA, -SAP_GREEN, YELLOW_OCHRE, ROSE_MADDER] +union(set1, set2): [MAGENTA, ROSE_MADDER, CRIMSON, +PERMANENT_GREEN, BURNT_UMBER, SAP_GREEN, CERULEAN_BLUE_HUE, +RAW_UMBER, YELLOW_OCHRE, BRILLIANT_RED, ULTRAMARINE, +BURNT_SIENNA, COBALT_BLUE_HUE, VIRIDIAN_HUE, PHTHALO_BLUE, +VIOLET] +intersection(set1, set2): [COBALT_BLUE_HUE, +PERMANENT_GREEN, VIRIDIAN_HUE, PHTHALO_BLUE, +CERULEAN_BLUE_HUE, ULTRAMARINE] +difference(set1, subset): [MAGENTA, ROSE_MADDER, CRIMSON, +BRILLIANT_RED, VIOLET] +difference(set2, subset): [BURNT_UMBER, SAP_GREEN, +RAW_UMBER, YELLOW_OCHRE, BURNT_SIENNA] +complement(set1, set2): [MAGENTA, ROSE_MADDER, CRIMSON, +BURNT_UMBER, SAP_GREEN, RAW_UMBER, YELLOW_OCHRE, +BRILLIANT_RED, BURNT_SIENNA, VIOLET] */ diff --git a/generics/Wildcards.java b/generics/Wildcards.java index 9f56c507..549a93bc 100644 --- a/generics/Wildcards.java +++ b/generics/Wildcards.java @@ -2,15 +2,19 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Exploring the meaning of wildcards. +// Exploring the meaning of wildcards public class Wildcards { // Raw argument: static void rawArgs(Holder holder, Object arg) { - // holder.set(arg); // Warning: - // Unchecked call to set(T) as a - // member of the raw type Holder - // holder.set(new Wildcards()); // Same warning + //- holder.set(arg); + // warning: [unchecked] unchecked call to set(T) + // as a member of the raw type Holder + // holder.set(arg); + // ^ + // where T is a type-variable: + // T extends Object declared in class Holder + // 1 warning // Can't do this; don't have any 'T': // T t = holder.get(); @@ -20,10 +24,20 @@ public class Wildcards { } // Similar to rawArgs(), but errors instead of warnings: static void unboundedArg(Holder holder, Object arg) { - // holder.set(arg); // Error: - // set(capture of ?) in Holder - // cannot be applied to (Object) - // holder.set(new Wildcards()); // Same error + //- holder.set(arg); + // error: method set in class Holder + // cannot be applied to given types; + // holder.set(arg); + // ^ + // required: CAP#1 + // found: Object + // reason: argument mismatch; + // Object cannot be converted to CAP#1 + // where T is a type-variable: + // T extends Object declared in class Holder + // where CAP#1 is a fresh type-variable: + // CAP#1 extends Object from capture of ? + // 1 error // Can't do this; don't have any 'T': // T t = holder.get(); @@ -40,17 +54,40 @@ public class Wildcards { } static T wildSubtype(Holder holder, T arg) { - // holder.set(arg); // Error: - // set(capture of ? extends T) in - // Holder - // cannot be applied to (T) + //- holder.set(arg); + // error: method set in class Holder + // cannot be applied to given types; + // holder.set(arg); + // ^ + // required: CAP#1 + // found: T#1 + // reason: argument mismatch; + // T#1 cannot be converted to CAP#1 + // where T#1,T#2 are type-variables: + // T#1 extends Object declared in method + // wildSubtype(Holder,T#1) + // T#2 extends Object declared in class Holder + // where CAP#1 is a fresh type-variable: + // CAP#1 extends T#1 from capture of ? extends T#1 + // 1 error + return holder.get(); } static void wildSupertype(Holder holder, T arg) { holder.set(arg); - // T t = holder.get(); // Error: - // Incompatible types: found Object, required T + //- T t = holder.get(); + // error: incompatible types: + // CAP#1 cannot be converted to T + // T t = holder.get(); + // ^ + // where T is a type-variable: + // T extends Object declared in method + // wildSupertype(Holder,T) + // where CAP#1 is a fresh type-variable: + // CAP#1 extends Object super: + // T from capture of ? super T + // 1 error // OK, but type information is lost: Object obj = holder.get(); @@ -74,49 +111,173 @@ public class Wildcards { unboundedArg(unbounded, lng); unboundedArg(bounded, lng); - // Object r1 = exact1(raw); // Warnings: - // Unchecked conversion from Holder to Holder - // Unchecked method invocation: exact1(Holder) - // is applied to (Holder) + //- Object r1 = exact1(raw); + // warning: [unchecked] unchecked method invocation: + // method exact1 in class Wildcards is applied + // to given types + // Object r1 = exact1(raw); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method exact1(Holder) + // warning: [unchecked] unchecked conversion + // Object r1 = exact1(raw); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method exact1(Holder) + // 2 warnings + Long r2 = exact1(qualified); Object r3 = exact1(unbounded); // Must return Object Long r4 = exact1(bounded); - // Long r5 = exact2(raw, lng); // Warnings: - // Unchecked conversion from Holder to Holder - // Unchecked method invocation: exact2(Holder,T) - // is applied to (Holder,Long) - Long r6 = exact2(qualified, lng); - // Long r7 = exact2(unbounded, lng); // Error: - // exact2(Holder,T) cannot be applied to - // (Holder,Long) - // Long r8 = exact2(bounded, lng); // Error: - // exact2(Holder,T) cannot be applied - // to (Holder,Long) + //- Long r5 = exact2(raw, lng); + // warning: [unchecked] unchecked method invocation: + // method exact2 in class Wildcards is + // applied to given types + // Long r5 = exact2(raw, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // where T is a type-variable: + // T extends Object declared in + // method exact2(Holder,T) + // warning: [unchecked] unchecked conversion + // Long r5 = exact2(raw, lng); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method exact2(Holder,T) + // 2 warnings + + Long r6 = exact2(qualified, lng); + + //- Long r7 = exact2(unbounded, lng); + // error: method exact2 in class Wildcards + // cannot be applied to given types; + // Long r7 = exact2(unbounded, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // reason: inference variable T has + // incompatible bounds + // equality constraints: CAP#1 + // lower bounds: Long + // where T is a type-variable: + // T extends Object declared in + // method exact2(Holder,T) + // where CAP#1 is a fresh type-variable: + // CAP#1 extends Object from capture of ? + // 1 error + + //- Long r8 = exact2(bounded, lng); + // error: method exact2 in class Wildcards + // cannot be applied to given types; + // Long r8 = exact2(bounded, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // reason: inference variable T + // has incompatible bounds + // equality constraints: CAP#1 + // lower bounds: Long + // where T is a type-variable: + // T extends Object declared in + // method exact2(Holder,T) + // where CAP#1 is a fresh type-variable: + // CAP#1 extends Long from + // capture of ? extends Long + // 1 error + + //- Long r9 = wildSubtype(raw, lng); + // warning: [unchecked] unchecked method invocation: + // method wildSubtype in class Wildcards + // is applied to given types + // Long r9 = wildSubtype(raw, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // where T is a type-variable: + // T extends Object declared in + // method wildSubtype(Holder,T) + // warning: [unchecked] unchecked conversion + // Long r9 = wildSubtype(raw, lng); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method wildSubtype(Holder,T) + // 2 warnings - // Long r9 = wildSubtype(raw, lng); // Warnings: - // Unchecked conversion from Holder - // to Holder - // Unchecked method invocation: - // wildSubtype(Holder,T) is - // applied to (Holder,Long) Long r10 = wildSubtype(qualified, lng); // OK, but can only return Object: Object r11 = wildSubtype(unbounded, lng); Long r12 = wildSubtype(bounded, lng); - // wildSupertype(raw, lng); // Warnings: - // Unchecked conversion from Holder - // to Holder - // Unchecked method invocation: - // wildSupertype(Holder,T) - // is applied to (Holder,Long) + //- wildSupertype(raw, lng); + // warning: [unchecked] unchecked method invocation: + // method wildSupertype in class Wildcards + // is applied to given types + // wildSupertype(raw, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // where T is a type-variable: + // T extends Object declared in + // method wildSupertype(Holder,T) + // warning: [unchecked] unchecked conversion + // wildSupertype(raw, lng); + // ^ + // required: Holder + // found: Holder + // where T is a type-variable: + // T extends Object declared in + // method wildSupertype(Holder,T) + // 2 warnings + wildSupertype(qualified, lng); - // wildSupertype(unbounded, lng); // Error: - // wildSupertype(Holder,T) cannot be - // applied to (Holder,Long) - // wildSupertype(bounded, lng); // Error: - // wildSupertype(Holder,T) cannot be - // applied to (Holder,Long) + + //- wildSupertype(unbounded, lng); + // error: method wildSupertype in class Wildcards + // cannot be applied to given types; + // wildSupertype(unbounded, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // reason: cannot infer type-variable(s) T + // (argument mismatch; Holder + // cannot be converted to Holder) + // where T is a type-variable: + // T extends Object declared in + // method wildSupertype(Holder,T) + // where CAP#1 is a fresh type-variable: + // CAP#1 extends Object from capture of ? + // 1 error + + //- wildSupertype(bounded, lng); + // error: method wildSupertype in class Wildcards + // cannot be applied to given types; + // wildSupertype(bounded, lng); + // ^ + // required: Holder,T + // found: Holder,Long + // reason: cannot infer type-variable(s) T + // (argument mismatch; Holder + // cannot be converted to Holder) + // where T is a type-variable: + // T extends Object declared in + // method wildSupertype(Holder,T) + // where CAP#1 is a fresh type-variable: + // CAP#1 extends Long from capture of + // ? extends Long + // 1 error } } diff --git a/generics/build.xml b/generics/build.xml index 7779deb4..6b9ac5f9 100644 --- a/generics/build.xml +++ b/generics/build.xml @@ -7,6 +7,7 @@ + @@ -21,6 +22,7 @@ + @@ -28,10 +30,7 @@ - - - @@ -42,7 +41,6 @@ - @@ -63,7 +61,6 @@ - @@ -78,6 +75,7 @@ + @@ -92,6 +90,7 @@ + @@ -99,10 +98,7 @@ - - - @@ -113,7 +109,6 @@ - @@ -134,7 +129,6 @@ - diff --git a/generics/coffee/CoffeeSupplier.java b/generics/coffee/CoffeeSupplier.java index 98800e6d..464e6a4f 100644 --- a/generics/coffee/CoffeeSupplier.java +++ b/generics/coffee/CoffeeSupplier.java @@ -2,10 +2,10 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Generate different types of Coffee: package generics.coffee; import java.util.*; import java.util.function.*; +import java.util.stream.*; public class CoffeeSupplier implements Supplier, Iterable { @@ -46,9 +46,9 @@ implements Supplier, Iterable { return new CoffeeIterator(); } public static void main(String[] args) { - CoffeeSupplier gen = new CoffeeSupplier(); - for(int i = 0; i < 5; i++) - System.out.println(gen.get()); + Stream.generate(new CoffeeSupplier()) + .limit(5) + .forEach(System.out::println); for(Coffee c : new CoffeeSupplier(5)) System.out.println(c); } diff --git a/generics/dogsandrobots.go b/generics/dogsandrobots.go new file mode 100644 index 00000000..6c949302 --- /dev/null +++ b/generics/dogsandrobots.go @@ -0,0 +1,32 @@ +// generics/dogsandrobots.go +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +package main +import "fmt" + +type Dog struct {} +func (this Dog) speak() { fmt.Printf("Arf!\n")} +func (this Dog) sit() { fmt.Printf("Sitting\n")} +func (this Dog) reproduce() {} + +type Robot struct {} +func (this Robot) speak() { fmt.Printf("Click!\n") } +func (this Robot) sit() { fmt.Printf("Clank!\n") } +func (this Robot) oilChange() {} + +func perform(speaker interface { speak(); sit() }) { + speaker.speak(); + speaker.sit(); +} + +func main() { + perform(Dog{}) + perform(Robot{}) +} +/* Output: +Arf! +Sitting +Click! +Clank! +*/ diff --git a/hiding/Cake.java b/hiding/Cake.java index 28b43518..833149b3 100644 --- a/hiding/Cake.java +++ b/hiding/Cake.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://mindviewinc.com/Books/OnJava/ for more book information. -// Accesses a class in a separate compilation unit. +// Accesses a class in a separate compilation unit class Cake { public static void main(String[] args) { diff --git a/hiding/ChocolateChip.java b/hiding/ChocolateChip.java index 07066137..e058f14d 100644 --- a/hiding/ChocolateChip.java +++ b/hiding/ChocolateChip.java @@ -2,12 +2,12 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Can't use package-access member from another package. +// Can't use package-access member from another package import hiding.dessert.*; public class ChocolateChip extends Cookie { public ChocolateChip() { - System.out.println("ChocolateChip constructor"); + System.out.println("ChocolateChip constructor"); } public void chomp() { //- bite(); // Can't access bite diff --git a/hiding/Dinner.java b/hiding/Dinner.java index 7c653ce7..69f6e416 100644 --- a/hiding/Dinner.java +++ b/hiding/Dinner.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://mindviewinc.com/Books/OnJava/ for more book information. -// Uses the library. +// Uses the library import hiding.dessert.*; public class Dinner { diff --git a/hiding/IceCream.java b/hiding/IceCream.java index d6eacdb8..765b97f9 100644 --- a/hiding/IceCream.java +++ b/hiding/IceCream.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates "private" keyword. +// Demonstrates "private" keyword class Sundae { private Sundae() {} diff --git a/hiding/LibTest.java b/hiding/LibTest.java index 42b36ecf..70d092a0 100644 --- a/hiding/LibTest.java +++ b/hiding/LibTest.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://mindviewinc.com/Books/OnJava/ for more book information. -// Uses the library. +// Uses the library import com.mindviewinc.simple.*; public class LibTest { diff --git a/hiding/Pie.java b/hiding/Pie.java index 5519e650..1cf63321 100644 --- a/hiding/Pie.java +++ b/hiding/Pie.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://mindviewinc.com/Books/OnJava/ for more book information. -// The other class. +// The other class class Pie { void f() { System.out.println("Pie.f()"); } diff --git a/hiding/build.xml b/hiding/build.xml index b07b0ab6..a1bf2c12 100644 --- a/hiding/build.xml +++ b/hiding/build.xml @@ -2,7 +2,7 @@ - + diff --git a/hiding/dessert/Cookie.java b/hiding/dessert/Cookie.java index ab14b0fc..cb63ff69 100644 --- a/hiding/dessert/Cookie.java +++ b/hiding/dessert/Cookie.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creates a library. +// Creates a library package hiding.dessert; public class Cookie { diff --git a/hiding/foreign/Foreign.java b/hiding/foreign/Foreign.java deleted file mode 100644 index edb456e7..00000000 --- a/hiding/foreign/Foreign.java +++ /dev/null @@ -1,13 +0,0 @@ -// hiding/foreign/Foreign.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// {CompileTimeError} (Won't compile) -package hiding.foreign; -import hiding.local.*; - -public class Foreign { - public static void main(String[] args) { - PackagedClass pc = new PackagedClass(); - } -} diff --git a/hiding/local/PackagedClass.java b/hiding/local/PackagedClass.java deleted file mode 100644 index 7b594575..00000000 --- a/hiding/local/PackagedClass.java +++ /dev/null @@ -1,11 +0,0 @@ -// hiding/local/PackagedClass.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -package hiding.local; - -class PackagedClass { - public PackagedClass() { - System.out.println("Creating a packaged class"); - } -} diff --git a/housekeeping/ArrayClassObj.java b/housekeeping/ArrayClassObj.java index 686f48b6..397699ad 100644 --- a/housekeeping/ArrayClassObj.java +++ b/housekeeping/ArrayClassObj.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating an array of nonprimitive objects. +// Creating an array of nonprimitive objects import java.util.*; public class ArrayClassObj { diff --git a/housekeeping/ArrayInit.java b/housekeeping/ArrayInit.java index e5edf15d..0b59bde1 100644 --- a/housekeeping/ArrayInit.java +++ b/housekeeping/ArrayInit.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://mindviewinc.com/Books/OnJava/ for more book information. -// Array initialization. +// Array initialization import java.util.*; public class ArrayInit { diff --git a/housekeeping/ArrayNew.java b/housekeeping/ArrayNew.java index 2174a499..74a6466a 100644 --- a/housekeeping/ArrayNew.java +++ b/housekeeping/ArrayNew.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating arrays with new. +// Creating arrays with new import java.util.*; public class ArrayNew { diff --git a/housekeeping/Burrito.java b/housekeeping/Burrito.java index 00d5308c..d356d48a 100644 --- a/housekeeping/Burrito.java +++ b/housekeeping/Burrito.java @@ -5,11 +5,14 @@ public class Burrito { Spiciness degree; - public Burrito(Spiciness degree) { this.degree = degree;} + public Burrito(Spiciness degree) { + this.degree = degree; + } public void describe() { System.out.print("This burrito is "); switch(degree) { - case NOT: System.out.println("not spicy at all."); + case NOT: System.out.println( + "not spicy at all."); break; case MILD: case MEDIUM: System.out.println("a little hot."); diff --git a/housekeeping/Demotion.java b/housekeeping/Demotion.java index cd103a8b..cd87c11e 100644 --- a/housekeeping/Demotion.java +++ b/housekeeping/Demotion.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demotion of primitives. +// Demotion of primitives public class Demotion { void f1(double x) { System.out.println("f1(double)"); } diff --git a/housekeeping/DynamicArray.java b/housekeeping/DynamicArray.java index 91581de6..ac7a2770 100644 --- a/housekeeping/DynamicArray.java +++ b/housekeeping/DynamicArray.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://mindviewinc.com/Books/OnJava/ for more book information. -// Array initialization. +// Array initialization public class DynamicArray { public static void main(String[] args) { diff --git a/housekeeping/ExplicitStatic.java b/housekeeping/ExplicitStatic.java index 9f06c9fe..761beb96 100644 --- a/housekeeping/ExplicitStatic.java +++ b/housekeeping/ExplicitStatic.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://mindviewinc.com/Books/OnJava/ for more book information. -// Explicit static initialization with the "static" clause. +// Explicit static initialization with the "static" clause class Cup { Cup(int marker) { diff --git a/housekeeping/InitialValues.java b/housekeeping/InitialValues.java index 41b48da0..826a924c 100644 --- a/housekeeping/InitialValues.java +++ b/housekeeping/InitialValues.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://mindviewinc.com/Books/OnJava/ for more book information. -// Shows default initial values. +// Shows default initial values public class InitialValues { boolean t; diff --git a/housekeeping/InitialValues2.java b/housekeeping/InitialValues2.java index 90b7f605..9361381b 100644 --- a/housekeeping/InitialValues2.java +++ b/housekeeping/InitialValues2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Providing explicit initial values. +// Providing explicit initial values public class InitialValues2 { boolean bool = true; diff --git a/housekeeping/Leaf.java b/housekeeping/Leaf.java index e65ef450..b75ae315 100644 --- a/housekeeping/Leaf.java +++ b/housekeeping/Leaf.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple use of the "this" keyword. +// Simple use of the "this" keyword public class Leaf { int i = 0; diff --git a/housekeeping/Mugs.java b/housekeeping/Mugs.java index 3c08197a..645e3a77 100644 --- a/housekeeping/Mugs.java +++ b/housekeeping/Mugs.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://mindviewinc.com/Books/OnJava/ for more book information. -// Instance initialization. +// Instance initialization class Mug { Mug(int marker) { diff --git a/housekeeping/NewVarArgs.java b/housekeeping/NewVarArgs.java index bca5852a..749c2c1b 100644 --- a/housekeeping/NewVarArgs.java +++ b/housekeeping/NewVarArgs.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using array syntax to create variable argument lists. +// Using array syntax to create variable argument lists public class NewVarArgs { static void printArray(Object... args) { diff --git a/housekeeping/OrderOfInitialization.java b/housekeeping/OrderOfInitialization.java index 28b055af..6bb1977e 100644 --- a/housekeeping/OrderOfInitialization.java +++ b/housekeeping/OrderOfInitialization.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates initialization order. +// Demonstrates initialization order // When the constructor is called to create a // Window object, you'll see a message: diff --git a/housekeeping/Overloading.java b/housekeeping/Overloading.java index 8e449eb1..7cc506db 100644 --- a/housekeeping/Overloading.java +++ b/housekeeping/Overloading.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of both constructor -// and ordinary method overloading. +// Both constructor and ordinary method overloading class Tree { int height; diff --git a/housekeeping/OverloadingOrder.java b/housekeeping/OverloadingOrder.java index 8b3997d1..4d239dec 100644 --- a/housekeeping/OverloadingOrder.java +++ b/housekeeping/OverloadingOrder.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://mindviewinc.com/Books/OnJava/ for more book information. -// Overloading based on the order of the arguments. +// Overloading based on the order of the arguments public class OverloadingOrder { static void f(String s, int i) { diff --git a/housekeeping/PrimitiveOverloading.java b/housekeeping/PrimitiveOverloading.java index 7ac32551..d8dca151 100644 --- a/housekeeping/PrimitiveOverloading.java +++ b/housekeeping/PrimitiveOverloading.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://mindviewinc.com/Books/OnJava/ for more book information. -// Promotion of primitives and overloading. +// Promotion of primitives and overloading public class PrimitiveOverloading { void f1(char x) { System.out.print("f1(char) "); } diff --git a/housekeeping/SimpleConstructor.java b/housekeeping/SimpleConstructor.java index 30716b56..06a73e73 100644 --- a/housekeeping/SimpleConstructor.java +++ b/housekeeping/SimpleConstructor.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of a simple constructor. +// Demonstration of a simple constructor class Rock { Rock() { // This is the constructor diff --git a/housekeeping/SimpleConstructor2.java b/housekeeping/SimpleConstructor2.java index 36751553..e08e79e2 100644 --- a/housekeeping/SimpleConstructor2.java +++ b/housekeeping/SimpleConstructor2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Constructors can have arguments. +// Constructors can have arguments class Rock2 { Rock2(int i) { diff --git a/housekeeping/StaticInitialization.java b/housekeeping/StaticInitialization.java index 3b43517f..e7bd12a5 100644 --- a/housekeeping/StaticInitialization.java +++ b/housekeeping/StaticInitialization.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://mindviewinc.com/Books/OnJava/ for more book information. -// Specifying initial values in a class definition. +// Specifying initial values in a class definition class Bowl { Bowl(int marker) { diff --git a/housekeeping/TerminationCondition.java b/housekeeping/TerminationCondition.java index 7bcf7b88..32d05bc3 100644 --- a/housekeeping/TerminationCondition.java +++ b/housekeeping/TerminationCondition.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using finalize() to detect an object that -// hasn't been properly cleaned up. +// hasn't been properly cleaned up import onjava.*; class Book { @@ -15,7 +15,7 @@ class Book { checkedOut = false; } @Override - protected void finalize() { + public void finalize() { if(checkedOut) System.out.println("Error: checked out"); // Normally, you'll also do this: diff --git a/housekeeping/VarArgs.java b/housekeeping/VarArgs.java index e0477926..eb8b3bd5 100644 --- a/housekeeping/VarArgs.java +++ b/housekeeping/VarArgs.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using array syntax to create variable argument lists. +// Using array syntax to create variable argument lists class A {} diff --git a/innerclasses/AnonymousConstructor.java b/innerclasses/AnonymousConstructor.java index 30022b57..5398c0fc 100644 --- a/innerclasses/AnonymousConstructor.java +++ b/innerclasses/AnonymousConstructor.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating a constructor for an anonymous inner class. +// Creating a constructor for an anonymous inner class abstract class Base { public Base(int i) { @@ -14,7 +14,8 @@ abstract class Base { public class AnonymousConstructor { public static Base getBase(int i) { return new Base(i) { - { System.out.println("Inside instance initializer"); } + { System.out.println( + "Inside instance initializer"); } @Override public void f() { System.out.println("In anonymous f()"); diff --git a/innerclasses/BigEgg.java b/innerclasses/BigEgg.java index efb08ecf..6f430bd3 100644 --- a/innerclasses/BigEgg.java +++ b/innerclasses/BigEgg.java @@ -2,12 +2,14 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// An inner class cannot be overriden like a method. +// An inner class cannot be overriden like a method class Egg { private Yolk y; protected class Yolk { - public Yolk() { System.out.println("Egg.Yolk()"); } + public Yolk() { + System.out.println("Egg.Yolk()"); + } } public Egg() { System.out.println("New Egg()"); @@ -17,7 +19,9 @@ class Egg { public class BigEgg extends Egg { public class Yolk { - public Yolk() { System.out.println("BigEgg.Yolk()"); } + public Yolk() { + System.out.println("BigEgg.Yolk()"); + } } public static void main(String[] args) { new BigEgg(); diff --git a/innerclasses/BigEgg2.java b/innerclasses/BigEgg2.java index 3a0c50bd..5de93267 100644 --- a/innerclasses/BigEgg2.java +++ b/innerclasses/BigEgg2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Proper inheritance of an inner class. +// Proper inheritance of an inner class class Egg2 { protected class Yolk { diff --git a/innerclasses/Callbacks.java b/innerclasses/Callbacks.java index db5f9a53..94ff1cb0 100644 --- a/innerclasses/Callbacks.java +++ b/innerclasses/Callbacks.java @@ -40,7 +40,7 @@ class Callee2 extends MyIncrement { @Override public void increment() { // Specify outer-class method, otherwise - // you'd get an infinite recursion: + // you'll get an infinite recursion: Callee2.this.increment(); } } @@ -51,7 +51,9 @@ class Callee2 extends MyIncrement { class Caller { private Incrementable callbackReference; - Caller(Incrementable cbh) { callbackReference = cbh; } + Caller(Incrementable cbh) { + callbackReference = cbh; + } void go() { callbackReference.increment(); } } @@ -61,7 +63,8 @@ public class Callbacks { Callee2 c2 = new Callee2(); MyIncrement.f(c2); Caller caller1 = new Caller(c1); - Caller caller2 = new Caller(c2.getCallbackReference()); + Caller caller2 = + new Caller(c2.getCallbackReference()); caller1.go(); caller1.go(); caller2.go(); diff --git a/innerclasses/DotNew.java b/innerclasses/DotNew.java index 0909b4c7..2846907c 100644 --- a/innerclasses/DotNew.java +++ b/innerclasses/DotNew.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating an inner class directly using the .new syntax. +// Creating an inner class directly using the .new syntax public class DotNew { public class Inner {} diff --git a/innerclasses/DotThis.java b/innerclasses/DotThis.java index 86ee54fb..20b9ab8c 100644 --- a/innerclasses/DotThis.java +++ b/innerclasses/DotThis.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://mindviewinc.com/Books/OnJava/ for more book information. -// Qualifying access to the outer-class object. +// Accessing the outer-class object public class DotThis { void f() { System.out.println("DotThis.f()"); } diff --git a/innerclasses/GreenhouseController.java b/innerclasses/GreenhouseController.java index 4e6ca125..6b00feda 100644 --- a/innerclasses/GreenhouseController.java +++ b/innerclasses/GreenhouseController.java @@ -2,15 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Configure and execute the greenhouse system. +// Configure and execute the greenhouse system // {Args: 5000} import innerclasses.controller.*; public class GreenhouseController { public static void main(String[] args) { GreenhouseControls gc = new GreenhouseControls(); - // Instead of hard-wiring, you can parse - // configuration information from a text file here: + // Instead of using code, you could parse + // configuration information from a text file: gc.addEvent(gc.new Bell(900)); Event[] eventList = { gc.new ThermostatNight(0), diff --git a/innerclasses/GreenhouseControls.java b/innerclasses/GreenhouseControls.java index 1935d865..aac65a36 100644 --- a/innerclasses/GreenhouseControls.java +++ b/innerclasses/GreenhouseControls.java @@ -11,7 +11,9 @@ import innerclasses.controller.*; public class GreenhouseControls extends Controller { private boolean light = false; public class LightOn extends Event { - public LightOn(long delayTime) { super(delayTime); } + public LightOn(long delayTime) { + super(delayTime); + } @Override public void action() { // Put hardware control code here to @@ -19,10 +21,14 @@ public class GreenhouseControls extends Controller { light = true; } @Override - public String toString() { return "Light is on"; } + public String toString() { + return "Light is on"; + } } public class LightOff extends Event { - public LightOff(long delayTime) { super(delayTime); } + public LightOff(long delayTime) { + super(delayTime); + } @Override public void action() { // Put hardware control code here to @@ -30,11 +36,15 @@ public class GreenhouseControls extends Controller { light = false; } @Override - public String toString() { return "Light is off"; } + public String toString() { + return "Light is off"; + } } private boolean water = false; public class WaterOn extends Event { - public WaterOn(long delayTime) { super(delayTime); } + public WaterOn(long delayTime) { + super(delayTime); + } @Override public void action() { // Put hardware control code here. @@ -46,7 +56,9 @@ public class GreenhouseControls extends Controller { } } public class WaterOff extends Event { - public WaterOff(long delayTime) { super(delayTime); } + public WaterOff(long delayTime) { + super(delayTime); + } @Override public void action() { // Put hardware control code here. @@ -89,17 +101,22 @@ public class GreenhouseControls extends Controller { // An example of an action() that inserts a // new one of itself into the event list: public class Bell extends Event { - public Bell(long delayTime) { super(delayTime); } - @Override - public void action() { - addEvent(new Bell(delayTime)); + public Bell(long delayTime) { + super(delayTime); } @Override - public String toString() { return "Bing!"; } + public void action() { + addEvent(new Bell(delayTime.toMillis())); + } + @Override + public String toString() { + return "Bing!"; + } } public class Restart extends Event { private Event[] eventList; - public Restart(long delayTime, Event[] eventList) { + public + Restart(long delayTime, Event[] eventList) { super(delayTime); this.eventList = eventList; for(Event e : eventList) @@ -120,10 +137,14 @@ public class GreenhouseControls extends Controller { } } public static class Terminate extends Event { - public Terminate(long delayTime) { super(delayTime); } + public Terminate(long delayTime) { + super(delayTime); + } @Override public void action() { System.exit(0); } @Override - public String toString() { return "Terminating"; } + public String toString() { + return "Terminating"; + } } } diff --git a/innerclasses/InheritInner.java b/innerclasses/InheritInner.java index fa48df17..5450d5ce 100644 --- a/innerclasses/InheritInner.java +++ b/innerclasses/InheritInner.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://mindviewinc.com/Books/OnJava/ for more book information. -// Inheriting an inner class. +// Inheriting an inner class class WithInner { class Inner {} diff --git a/innerclasses/LocalInnerClass.java b/innerclasses/LocalInnerClass.java index 33a38f08..019dd4ce 100644 --- a/innerclasses/LocalInnerClass.java +++ b/innerclasses/LocalInnerClass.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://mindviewinc.com/Books/OnJava/ for more book information. -// Holds a sequence of Objects. +// Holds a sequence of Objects interface Counter { int next(); @@ -25,7 +25,7 @@ public class LocalInnerClass { } return new LocalCounter(); } - // The same thing with an anonymous inner class: + // Repeat, but with an anonymous inner class: Counter getCounter2(final String name) { return new Counter() { // Anonymous inner class cannot have a named diff --git a/innerclasses/MultiImplementation.java b/innerclasses/MultiImplementation.java index 7f3f5a24..d94017f4 100644 --- a/innerclasses/MultiImplementation.java +++ b/innerclasses/MultiImplementation.java @@ -2,9 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// With concrete or abstract classes, inner -// classes are the only way to produce the effect -// of "multiple implementation inheritance." +// For concrete or abstract classes, inner classes +// produce "multiple implementation inheritance" package innerclasses; class D {} diff --git a/innerclasses/MultiNestingAccess.java b/innerclasses/MultiNestingAccess.java index 99714233..c90999ee 100644 --- a/innerclasses/MultiNestingAccess.java +++ b/innerclasses/MultiNestingAccess.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Nested classes can access all members of all -// levels of the classes they are nested within. +// levels of the classes they are nested within class MNA { private void f() {} diff --git a/innerclasses/Parcel1.java b/innerclasses/Parcel1.java index 96d4d5a8..0fe971da 100644 --- a/innerclasses/Parcel1.java +++ b/innerclasses/Parcel1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating inner classes. +// Creating inner classes public class Parcel1 { class Contents { diff --git a/innerclasses/Parcel10.java b/innerclasses/Parcel10.java index e44f4737..7f0bfdc2 100644 --- a/innerclasses/Parcel10.java +++ b/innerclasses/Parcel10.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using "instance initialization" to perform -// construction on an anonymous inner class. +// construction on an anonymous inner class public class Parcel10 { public Destination diff --git a/innerclasses/Parcel11.java b/innerclasses/Parcel11.java index 0a684873..0a91afba 100644 --- a/innerclasses/Parcel11.java +++ b/innerclasses/Parcel11.java @@ -2,10 +2,11 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Nested classes (static inner classes). +// Nested classes (static inner classes) public class Parcel11 { - private static class ParcelContents implements Contents { + private static class + ParcelContents implements Contents { private int i = 11; @Override public int value() { return i; } diff --git a/innerclasses/Parcel2.java b/innerclasses/Parcel2.java index 962314e1..384d0028 100644 --- a/innerclasses/Parcel2.java +++ b/innerclasses/Parcel2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Returning a reference to an inner class. +// Returning a reference to an inner class public class Parcel2 { class Contents { diff --git a/innerclasses/Parcel3.java b/innerclasses/Parcel3.java index 74975e3c..18435451 100644 --- a/innerclasses/Parcel3.java +++ b/innerclasses/Parcel3.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using .new to create instances of inner classes. +// Using .new to create instances of inner classes public class Parcel3 { class Contents { diff --git a/innerclasses/Parcel5.java b/innerclasses/Parcel5.java index 1cd20a05..fe425975 100644 --- a/innerclasses/Parcel5.java +++ b/innerclasses/Parcel5.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://mindviewinc.com/Books/OnJava/ for more book information. -// Nesting a class within a method. +// Nesting a class within a method public class Parcel5 { public Destination destination(String s) { diff --git a/innerclasses/Parcel6.java b/innerclasses/Parcel6.java index 87fc0e68..20c9c5b6 100644 --- a/innerclasses/Parcel6.java +++ b/innerclasses/Parcel6.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://mindviewinc.com/Books/OnJava/ for more book information. -// Nesting a class within a scope. +// Nesting a class within a scope public class Parcel6 { private void internalTracking(boolean b) { diff --git a/innerclasses/Parcel7.java b/innerclasses/Parcel7.java index 9e091c84..36355523 100644 --- a/innerclasses/Parcel7.java +++ b/innerclasses/Parcel7.java @@ -2,15 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Returning an instance of an anonymous inner class. +// Returning an instance of an anonymous inner class public class Parcel7 { public Contents contents() { - return new Contents() { // Insert a class definition + return new Contents() { // Insert class definition private int i = 11; @Override public int value() { return i; } - }; // Semicolon required in this case + }; // Semicolon required } public static void main(String[] args) { Parcel7 p = new Parcel7(); diff --git a/innerclasses/Parcel7b.java b/innerclasses/Parcel7b.java index 7b489ecf..ab194144 100644 --- a/innerclasses/Parcel7b.java +++ b/innerclasses/Parcel7b.java @@ -10,7 +10,9 @@ public class Parcel7b { @Override public int value() { return i; } } - public Contents contents() { return new MyContents(); } + public Contents contents() { + return new MyContents(); + } public static void main(String[] args) { Parcel7b p = new Parcel7b(); Contents c = p.contents(); diff --git a/innerclasses/Parcel8.java b/innerclasses/Parcel8.java index 5fb75c24..3846839c 100644 --- a/innerclasses/Parcel8.java +++ b/innerclasses/Parcel8.java @@ -2,17 +2,17 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Calling the base-class constructor. +// Calling the base-class constructor public class Parcel8 { public Wrapping wrapping(int x) { // Base constructor call: - return new Wrapping(x) { // Pass constructor argument. + return new Wrapping(x) { // (1) @Override public int value() { return super.value() * 47; } - }; // Semicolon required + }; // (2) } public static void main(String[] args) { Parcel8 p = new Parcel8(); diff --git a/innerclasses/Parcel9.java b/innerclasses/Parcel9.java index 1e14cd02..c68a7247 100644 --- a/innerclasses/Parcel9.java +++ b/innerclasses/Parcel9.java @@ -2,12 +2,10 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// An anonymous inner class that performs -// initialization. A briefer version of Parcel5.java. public class Parcel9 { - // Argument must be final to use inside - // anonymous inner class: + // Argument must be final or "effectively final" + // to use within the anonymous inner class: public Destination destination(final String dest) { return new Destination() { private String label = dest; diff --git a/innerclasses/Sequence.java b/innerclasses/Sequence.java index 139951d3..983881a6 100644 --- a/innerclasses/Sequence.java +++ b/innerclasses/Sequence.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://mindviewinc.com/Books/OnJava/ for more book information. -// Holds a sequence of Objects. +// Holds a sequence of Objects interface Selector { boolean end(); @@ -13,7 +13,9 @@ interface Selector { public class Sequence { private Object[] items; private int next = 0; - public Sequence(int size) { items = new Object[size]; } + public Sequence(int size) { + items = new Object[size]; + } public void add(Object x) { if(next < items.length) items[next++] = x; diff --git a/innerclasses/TestBed.java b/innerclasses/TestBed.java index 3ea5e36a..b8ee7d3b 100644 --- a/innerclasses/TestBed.java +++ b/innerclasses/TestBed.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://mindviewinc.com/Books/OnJava/ for more book information. -// Putting test code in a nested class. +// Putting test code in a nested class // {main: TestBed$Tester} public class TestBed { diff --git a/innerclasses/controller/Controller.java b/innerclasses/controller/Controller.java index d7dae7b7..05c74b6b 100644 --- a/innerclasses/controller/Controller.java +++ b/innerclasses/controller/Controller.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://mindviewinc.com/Books/OnJava/ for more book information. -// The reusable framework for control systems. +// The reusable framework for control systems package innerclasses.controller; import java.util.*; diff --git a/innerclasses/controller/Event.java b/innerclasses/controller/Event.java index 44717842..bb21a2f5 100644 --- a/innerclasses/controller/Event.java +++ b/innerclasses/controller/Event.java @@ -2,21 +2,22 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// The common methods for any control event. +// The common methods for any control event package innerclasses.controller; +import java.time.*; // Java 8 time classes public abstract class Event { - private long eventTime; - protected final long delayTime; - public Event(long delayTime) { - this.delayTime = delayTime; + private Instant eventTime; + protected final Duration delayTime; + public Event(long millisecond_delay) { + delayTime = Duration.ofMillis(millisecond_delay); start(); } public void start() { // Allows restarting - eventTime = System.nanoTime() + delayTime; + eventTime = Instant.now().plus(delayTime); } public boolean ready() { - return System.nanoTime() >= eventTime; + return Instant.now().isAfter(eventTime); } public abstract void action(); } diff --git a/innerclasses/mui/MultiInterfaces.java b/innerclasses/mui/MultiInterfaces.java index 69b2b900..d7e27f4d 100644 --- a/innerclasses/mui/MultiInterfaces.java +++ b/innerclasses/mui/MultiInterfaces.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://mindviewinc.com/Books/OnJava/ for more book information. -// Two ways that a class can implement multiple interfaces. +// Two ways that a class can implement multiple interfaces package innerclasses.mui; interface A {} diff --git a/interfaces/AdaptedRandomDoubles.java b/interfaces/AdaptedRandomDoubles.java index 6c276f97..7dd6be66 100644 --- a/interfaces/AdaptedRandomDoubles.java +++ b/interfaces/AdaptedRandomDoubles.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating an adapter with inheritance. +// Creating an adapter with inheritance import java.nio.*; import java.util.*; diff --git a/interfaces/Adventure.java b/interfaces/Adventure.java index 7b1b265f..dacd9414 100644 --- a/interfaces/Adventure.java +++ b/interfaces/Adventure.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://mindviewinc.com/Books/OnJava/ for more book information. -// Multiple interfaces. +// Multiple interfaces interface CanFight { void fight(); diff --git a/interfaces/Applicator.java b/interfaces/Applicator.java index 9ce26002..ce148e75 100644 --- a/interfaces/Applicator.java +++ b/interfaces/Applicator.java @@ -41,7 +41,7 @@ public class Applicator { System.out.println(p.process(s)); } public static String s = - "Disagreement with beliefs is by definition incorrect"; + "Disagreement with beliefs is by definition incorrect"; public static void main(String[] args) { apply(new Upcase(), s); apply(new Downcase(), s); diff --git a/interfaces/Factories.java b/interfaces/Factories.java index acebac47..3d42dfed 100644 --- a/interfaces/Factories.java +++ b/interfaces/Factories.java @@ -47,7 +47,8 @@ class Service2Factory implements ServiceFactory { } public class Factories { - public static void serviceConsumer(ServiceFactory fact) { + public static void + serviceConsumer(ServiceFactory fact) { Service s = fact.getService(); s.method1(); s.method2(); diff --git a/interfaces/Games.java b/interfaces/Games.java index 385b044c..faa04206 100644 --- a/interfaces/Games.java +++ b/interfaces/Games.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://mindviewinc.com/Books/OnJava/ for more book information. -// A Game framework using Factory Methods. +// A Game framework using Factory Methods interface Game { boolean move(); } interface GameFactory { Game getGame(); } diff --git a/interfaces/HorrorShow.java b/interfaces/HorrorShow.java index aaeb2640..694ac606 100644 --- a/interfaces/HorrorShow.java +++ b/interfaces/HorrorShow.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://mindviewinc.com/Books/OnJava/ for more book information. -// Extending an interface with inheritance. +// Extending an interface with inheritance interface Monster { void menace(); diff --git a/interfaces/Months.java b/interfaces/Months.java index aa1b6950..baec9892 100644 --- a/interfaces/Months.java +++ b/interfaces/Months.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using interfaces to create groups of constants. +// Using interfaces to create groups of constants public interface Months { int diff --git a/interfaces/PureInterface.java b/interfaces/PureInterface.java index 4037d0d4..8b8ea0e6 100644 --- a/interfaces/PureInterface.java +++ b/interfaces/PureInterface.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://mindviewinc.com/Books/OnJava/ for more book information. -// Interface only looked like this before Java 8. +// Interface only looked like this before Java 8 public interface PureInterface { int m1(); diff --git a/interfaces/RandVals.java b/interfaces/RandVals.java index b5da0517..75631496 100644 --- a/interfaces/RandVals.java +++ b/interfaces/RandVals.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Initializing interface fields with -// non-constant initializers. +// non-constant initializers import java.util.*; public interface RandVals { diff --git a/interfaces/RandomDoubles.java b/interfaces/RandomDoubles.java index f22b02aa..c393c4ae 100644 --- a/interfaces/RandomDoubles.java +++ b/interfaces/RandomDoubles.java @@ -7,7 +7,7 @@ import java.util.*; public interface RandomDoubles { Random rand = new Random(47); default double next() { return rand.nextDouble(); } - static void main(String[] args) { + public 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 7c4842ac..e1769bbd 100644 --- a/interfaces/RandomWords.java +++ b/interfaces/RandomWords.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://mindviewinc.com/Books/OnJava/ for more book information. -// Implementing an interface to conform to a method. +// Implementing an interface to conform to a method import java.nio.*; import java.util.*; diff --git a/interfaces/build.xml b/interfaces/build.xml index 37cea728..4e978be1 100644 --- a/interfaces/build.xml +++ b/interfaces/build.xml @@ -19,9 +19,11 @@ + + @@ -40,9 +42,11 @@ + + diff --git a/interfaces/interfaceprocessor/StringProcessor.java b/interfaces/interfaceprocessor/StringProcessor.java index d0d237bd..4074aa03 100644 --- a/interfaces/interfaceprocessor/StringProcessor.java +++ b/interfaces/interfaceprocessor/StringProcessor.java @@ -10,7 +10,7 @@ interface StringProcessor extends Processor { String process(Object input); // (1) String s = // (2) "If she weighs the same as a duck, she's made of wood"; - static void main(String[] args) { // (3) + public static void main(String[] args) { // (3) Applicator.apply(new Upcase(), s); Applicator.apply(new Downcase(), s); Applicator.apply(new Splitter(), s); @@ -18,8 +18,8 @@ interface StringProcessor extends Processor { } class Upcase implements StringProcessor { - @Override - public String process(Object input) { // Covariant return + @Override // Covariant return: + public String process(Object input) { return ((String)input).toUpperCase(); } } diff --git a/interfaces/music4/Music4.java b/interfaces/music4/Music4.java index 4a093fba..776d80e6 100644 --- a/interfaces/music4/Music4.java +++ b/interfaces/music4/Music4.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://mindviewinc.com/Books/OnJava/ for more book information. -// Abstract classes and methods. +// Abstract classes and methods package interfaces.music4; import polymorphism.music.Note; diff --git a/iostreams/BasicFileOutput.java b/iostreams/BasicFileOutput.java index 4576c8d0..36a06c41 100644 --- a/iostreams/BasicFileOutput.java +++ b/iostreams/BasicFileOutput.java @@ -6,8 +6,8 @@ import java.io.*; public class BasicFileOutput { static String file = "BasicFileOutput.dat"; - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { try(BufferedReader in = new BufferedReader( new StringReader( BufferedInputFile.read( diff --git a/iostreams/BufferedInputFile.java b/iostreams/BufferedInputFile.java index 48da4de4..95006799 100644 --- a/iostreams/BufferedInputFile.java +++ b/iostreams/BufferedInputFile.java @@ -5,12 +5,10 @@ import java.io.*; public class BufferedInputFile { - // Throw exceptions to console: public static String read(String filename) throws IOException { - // Reading input by lines: try(BufferedReader in = new BufferedReader( - new FileReader(filename))) { + new FileReader(filename))) { String s; StringBuilder sb = new StringBuilder(); while((s = in.readLine())!= null) @@ -18,8 +16,8 @@ public class BufferedInputFile { return sb.toString(); } } - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { System.out.print(read("BufferedInputFile.java")); } } diff --git a/iostreams/FileOutputShortcut.java b/iostreams/FileOutputShortcut.java index aac50213..6e7607f6 100644 --- a/iostreams/FileOutputShortcut.java +++ b/iostreams/FileOutputShortcut.java @@ -6,11 +6,11 @@ import java.io.*; public class FileOutputShortcut { static String file = "FileOutputShortcut.dat"; - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { try(BufferedReader in = new BufferedReader( - new StringReader(BufferedInputFile.read( - "FileOutputShortcut.java"))); + new StringReader(BufferedInputFile.read( + "FileOutputShortcut.java"))); // Here's the shortcut: PrintWriter out = new PrintWriter(file)) { int lineCount = 1; diff --git a/iostreams/FormattedMemoryInput.java b/iostreams/FormattedMemoryInput.java index 0abe8bab..aa60ec52 100644 --- a/iostreams/FormattedMemoryInput.java +++ b/iostreams/FormattedMemoryInput.java @@ -5,13 +5,13 @@ import java.io.*; public class FormattedMemoryInput { - public static void main(String[] args) - throws IOException { - try { - DataInputStream in = new DataInputStream( - new ByteArrayInputStream( - BufferedInputFile.read( - "FormattedMemoryInput.java").getBytes())); + public static void + main(String[] args) throws IOException { + try(DataInputStream in = new DataInputStream( + new ByteArrayInputStream( + BufferedInputFile.read( + "FormattedMemoryInput.java") + .getBytes()))) { while(true) System.out.write((char)in.readByte()); } catch(EOFException e) { diff --git a/iostreams/MemoryInput.java b/iostreams/MemoryInput.java index dedb994c..9ef9e1f1 100644 --- a/iostreams/MemoryInput.java +++ b/iostreams/MemoryInput.java @@ -5,8 +5,8 @@ import java.io.*; public class MemoryInput { - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { StringReader in = new StringReader( BufferedInputFile.read("MemoryInput.java")); int c; diff --git a/iostreams/StoringAndRecoveringData.java b/iostreams/StoringAndRecoveringData.java index c89614d7..b5a00096 100644 --- a/iostreams/StoringAndRecoveringData.java +++ b/iostreams/StoringAndRecoveringData.java @@ -5,8 +5,8 @@ import java.io.*; public class StoringAndRecoveringData { - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { try(DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("Data.txt")))) { diff --git a/iostreams/TestEOF.java b/iostreams/TestEOF.java index 2f9bafca..e5cc1a1a 100644 --- a/iostreams/TestEOF.java +++ b/iostreams/TestEOF.java @@ -2,17 +2,18 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Testing for end of file while reading a byte at a time. +// Testing for end of file import java.io.*; public class TestEOF { - public static void main(String[] args) - throws IOException { - DataInputStream in = new DataInputStream( - new BufferedInputStream( - new FileInputStream("TestEOF.java"))); - while(in.available() != 0) - System.out.write(in.readByte()); + public static void + main(String[] args) throws IOException { + try(DataInputStream in = new DataInputStream( + new BufferedInputStream( + new FileInputStream("TestEOF.java")))) { + while(in.available() != 0) + System.out.write(in.readByte()); + } } } /* Output: (Execute to see) */ diff --git a/iostreams/UsingRandomAccessFile.java b/iostreams/UsingRandomAccessFile.java index 92b9138f..d7a6e0e7 100644 --- a/iostreams/UsingRandomAccessFile.java +++ b/iostreams/UsingRandomAccessFile.java @@ -8,15 +8,15 @@ public class UsingRandomAccessFile { static String file = "rtest.dat"; static void display() throws IOException { try(RandomAccessFile rf = - new RandomAccessFile(file, "r")) { + new RandomAccessFile(file, "r")) { for(int i = 0; i < 7; i++) System.out.println( "Value " + i + ": " + rf.readDouble()); System.out.println(rf.readUTF()); } } - public static - void main(String[] args) throws IOException { + public static void + main(String[] args) throws IOException { try(RandomAccessFile rf = new RandomAccessFile(file, "rw")) { for(int i = 0; i < 7; i++) diff --git a/network/ChatterClient.java b/network/ChatterClient.java index 17956c39..13ec4c4d 100644 --- a/network/ChatterClient.java +++ b/network/ChatterClient.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {ValidateByHand} // Tests the ChatterServer by starting multiple -// clients, each of which sends datagrams. +// clients, each of which sends datagrams import java.net.*; import java.io.*; import onjava.*; diff --git a/network/Dgram.java b/network/Dgram.java index dd7ed81f..f4d96ae8 100644 --- a/network/Dgram.java +++ b/network/Dgram.java @@ -2,8 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A utility class to convert back and forth -// Between Strings and DataGramPackets. +// Converts back and forth +// between Strings and DataGramPackets import java.net.*; public class Dgram { @@ -13,7 +13,7 @@ public class Dgram { return new DatagramPacket(buf, buf.length, destIA, destPort); } - public static String toString(DatagramPacket p){ + public static String toString(DatagramPacket p) { return new String(p.getData(), 0, p.getLength()); } diff --git a/network/LocalHost.java b/network/LocalHost.java index 986442a9..f191c114 100644 --- a/network/LocalHost.java +++ b/network/LocalHost.java @@ -6,8 +6,8 @@ import java.net.*; public class LocalHost { - public static void main(String[] args) - throws Exception { + public static void + main(String[] args) throws Exception { InetAddress local1 = InetAddress.getByName(null), local2 = InetAddress.getByName("localhost"), diff --git a/network/MultiSimpleClient.java b/network/MultiSimpleClient.java index 8324a765..18a41e5e 100644 --- a/network/MultiSimpleClient.java +++ b/network/MultiSimpleClient.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Client that tests the MultiSimpleServer -// by starting up multiple clients. +// Testing MultiSimpleServer with multiple clients // {ValidateByHand} import java.net.*; import java.io.*; @@ -74,8 +73,9 @@ class SimpleClientThread extends Thread { public class MultiSimpleClient { static final int MAX_THREADS = 40; - public static void main(String[] args) - throws IOException, InterruptedException { + public static void + main(String[] args) throws IOException, + InterruptedException { new TimedAbort(5); // Terminate after 5 seconds InetAddress addr = InetAddress.getByName(null); diff --git a/network/MultiSimpleServer.java b/network/MultiSimpleServer.java index 1c003b72..3a6bea58 100644 --- a/network/MultiSimpleServer.java +++ b/network/MultiSimpleServer.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A server that uses multithreading -// to handle any number of clients. +// Uses multithreading to handle any number of clients // {ValidateByHand} import java.io.*; import java.net.*; @@ -53,8 +52,8 @@ class ServeOneSimple extends Thread { public class MultiSimpleServer { static final int PORT = 8080; - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { new TimedAbort(5); // Terminate after 5 seconds ServerSocket s = new ServerSocket(PORT); System.out.println("Server Started"); diff --git a/network/SimpleClient.java b/network/SimpleClient.java index 3db279c7..ae6abd15 100644 --- a/network/SimpleClient.java +++ b/network/SimpleClient.java @@ -2,16 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Very simple client that just sends -// lines to the server and reads lines -// that the server sends. +// Sends lines to the server and +// reads lines the server sends // {ValidateByHand} import java.net.*; import java.io.*; public class SimpleClient { - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { // Passing null to getByName() produces the // special "Local Loopback" IP address, for // testing on one machine w/o a network: diff --git a/network/SimpleServer.java b/network/SimpleServer.java index c8d318ed..9295fd49 100644 --- a/network/SimpleServer.java +++ b/network/SimpleServer.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Very simple server that just -// echoes whatever the client sends. +// Just echoes whatever the client sends // {ValidateByHand} import java.io.*; import java.net.*; @@ -11,8 +10,8 @@ import java.net.*; public class SimpleServer { // Choose a port outside of the range 1-1024: public static final int PORT = 8080; - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Started: " + s); try { diff --git a/network/WhoAmI.java b/network/WhoAmI.java index 0bb9b840..aab56a1f 100644 --- a/network/WhoAmI.java +++ b/network/WhoAmI.java @@ -3,12 +3,12 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Finds out your machine name and network address -// when you're connected to the Internet. +// when you're connected to the Internet import java.net.*; public class WhoAmI { - public static void main(String[] args) - throws Exception { + public static void + main(String[] args) throws Exception { InetAddress whoami = InetAddress.getLocalHost(); System.out.println(whoami.getHostName()); System.out.println(whoami.getHostAddress()); diff --git a/newio/BufferToText.java b/newio/BufferToText.java index 68c83016..7de658b8 100644 --- a/newio/BufferToText.java +++ b/newio/BufferToText.java @@ -10,14 +10,17 @@ import java.io.*; public class BufferToText { private static final int BSIZE = 1024; - public static void main(String[] args) throws Exception { - FileChannel fc = - new FileOutputStream("data2.txt").getChannel(); - fc.write(ByteBuffer.wrap("Some text".getBytes())); - fc.close(); - fc = new FileInputStream("data2.txt").getChannel(); + public static void + main(String[] args) throws Exception { + try(FileChannel fc = new FileOutputStream( + "data2.txt").getChannel()) { + fc.write(ByteBuffer.wrap("Some text".getBytes())); + } ByteBuffer buff = ByteBuffer.allocate(BSIZE); - fc.read(buff); + try(FileChannel fc = new FileInputStream( + "data2.txt").getChannel()) { + fc.read(buff); + } buff.flip(); // Doesn't work: System.out.println(buff.asCharBuffer()); @@ -27,26 +30,32 @@ public class BufferToText { System.out.println("Decoded using " + encoding + ": " + Charset.forName(encoding).decode(buff)); // Or, we could encode with something that prints: - fc = new FileOutputStream("data2.txt").getChannel(); - fc.write(ByteBuffer.wrap( - "Some text".getBytes("UTF-16BE"))); - fc.close(); + try(FileChannel fc = new FileOutputStream( + "data2.txt").getChannel()) { + fc.write(ByteBuffer.wrap( + "Some text".getBytes("UTF-16BE"))); + } // Now try reading again: - fc = new FileInputStream("data2.txt").getChannel(); buff.clear(); - fc.read(buff); + try(FileChannel fc = new FileInputStream( + "data2.txt").getChannel()) { + fc.read(buff); + } buff.flip(); System.out.println(buff.asCharBuffer()); // Use a CharBuffer to write through: - fc = new FileOutputStream("data2.txt").getChannel(); buff = ByteBuffer.allocate(24); // More than needed buff.asCharBuffer().put("Some text"); - fc.write(buff); - fc.close(); + try(FileChannel fc = new FileOutputStream( + "data2.txt").getChannel()) { + fc.write(buff); + } // Read and display: - fc = new FileInputStream("data2.txt").getChannel(); buff.clear(); - fc.read(buff); + try(FileChannel fc = new FileInputStream( + "data2.txt").getChannel()) { + fc.read(buff); + } buff.flip(); System.out.println(buff.asCharBuffer()); } diff --git a/newio/ChannelCopy.java b/newio/ChannelCopy.java index 0decfd45..9af679cc 100644 --- a/newio/ChannelCopy.java +++ b/newio/ChannelCopy.java @@ -10,19 +10,23 @@ import java.io.*; public class ChannelCopy { private static final int BSIZE = 1024; - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length != 2) { - System.out.println("arguments: sourcefile destfile"); + System.out.println( + "arguments: sourcefile destfile"); System.exit(1); } - FileChannel - in = new FileInputStream(args[0]).getChannel(), - out = new FileOutputStream(args[1]).getChannel(); - ByteBuffer buffer = ByteBuffer.allocate(BSIZE); - while(in.read(buffer) != -1) { - buffer.flip(); // Prepare for writing - out.write(buffer); - buffer.clear(); // Prepare for reading + try(FileChannel in = new FileInputStream( + args[0]).getChannel(); + FileChannel out = new FileOutputStream( + args[1]).getChannel()) { + ByteBuffer buffer = ByteBuffer.allocate(BSIZE); + while(in.read(buffer) != -1) { + buffer.flip(); // Prepare for writing + out.write(buffer); + buffer.clear(); // Prepare for reading + } } } } diff --git a/newio/Endians.java b/newio/Endians.java index d92f2ca9..a0fc8760 100644 --- a/newio/Endians.java +++ b/newio/Endians.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://mindviewinc.com/Books/OnJava/ for more book information. -// Endian differences and data storage. +// Endian differences and data storage import java.nio.*; import java.util.*; diff --git a/newio/FileLocking.java b/newio/FileLocking.java index 60e5613d..0cfd1cd5 100644 --- a/newio/FileLocking.java +++ b/newio/FileLocking.java @@ -7,10 +7,11 @@ import java.util.concurrent.*; import java.io.*; public class FileLocking { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { try(FileOutputStream fos = new FileOutputStream("file.txt"); - FileLock fl = fos.getChannel().tryLock();) { + FileLock fl = fos.getChannel().tryLock()) { if(fl != null) { System.out.println("Locked File"); TimeUnit.MILLISECONDS.sleep(100); diff --git a/newio/GetChannel.java b/newio/GetChannel.java deleted file mode 100644 index cdf80364..00000000 --- a/newio/GetChannel.java +++ /dev/null @@ -1,35 +0,0 @@ -// newio/GetChannel.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Getting channels from streams -import java.nio.*; -import java.nio.channels.*; -import java.io.*; -public class GetChannel { - private static final int BSIZE = 1024; - public static void main(String[] args) throws Exception { - // Write a file: - FileChannel fc = - new FileOutputStream("data.txt").getChannel(); - fc.write(ByteBuffer.wrap("Some text ".getBytes())); - fc.close(); - // Add to the end of the file: - fc = - new RandomAccessFile("data.txt", "rw").getChannel(); - fc.position(fc.size()); // Move to the end - fc.write(ByteBuffer.wrap("Some more".getBytes())); - fc.close(); - // Read the file: - fc = new FileInputStream("data.txt").getChannel(); - ByteBuffer buff = ByteBuffer.allocate(BSIZE); - fc.read(buff); - buff.flip(); - while(buff.hasRemaining()) - System.out.write(buff.get()); - System.out.flush(); - } -} -/* Output: -Some text Some more -*/ diff --git a/newio/LargeMappedFiles.java b/newio/LargeMappedFiles.java index 434393dc..2b9e9ad2 100644 --- a/newio/LargeMappedFiles.java +++ b/newio/LargeMappedFiles.java @@ -2,22 +2,25 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Creating a very large file using mapping. +// Creating a very large file using mapping import java.nio.*; import java.nio.channels.*; import java.io.*; public class LargeMappedFiles { static int length = 0x8000000; // 128 MB - public static void main(String[] args) throws Exception { - MappedByteBuffer out = - new RandomAccessFile("test.dat", "rw").getChannel() - .map(FileChannel.MapMode.READ_WRITE, 0, length); - for(int i = 0; i < length; i++) - out.put((byte)'x'); - System.out.println("Finished writing"); - for(int i = length/2; i < length/2 + 6; i++) - System.out.print((char)out.get(i)); + public static void + main(String[] args) throws Exception { + try(RandomAccessFile tdat = + new RandomAccessFile("test.dat", "rw")) { + MappedByteBuffer out = tdat.getChannel() + .map(FileChannel.MapMode.READ_WRITE, 0, length); + for(int i = 0; i < length; i++) + out.put((byte)'x'); + System.out.println("Finished writing"); + for(int i = length/2; i < length/2 + 6; i++) + System.out.print((char)out.get(i)); + } } } /* Output: diff --git a/newio/LockingMappedFiles.java b/newio/LockingMappedFiles.java index fc15f98f..fb01d8f4 100644 --- a/newio/LockingMappedFiles.java +++ b/newio/LockingMappedFiles.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://mindviewinc.com/Books/OnJava/ for more book information. -// Locking portions of a mapped file. +// Locking portions of a mapped file import java.nio.*; import java.nio.channels.*; import java.io.*; @@ -10,7 +10,8 @@ import java.io.*; public class LockingMappedFiles { static final int LENGTH = 0x8FFFFFF; // 128 MB static FileChannel fc; - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { fc = new RandomAccessFile("test.dat", "rw").getChannel(); MappedByteBuffer out = @@ -36,12 +37,14 @@ public class LockingMappedFiles { try { // Exclusive lock with no overlap: FileLock fl = fc.lock(start, end, false); - System.out.println("Locked: "+ start +" to "+ end); + System.out.println( + "Locked: "+ start +" to "+ end); // Perform modification: while(buff.position() < buff.limit() - 1) buff.put((byte)(buff.get() + 1)); fl.release(); - System.out.println("Released: "+start+" to "+ end); + System.out.println( + "Released: " + start + " to " + end); } catch(IOException e) { throw new RuntimeException(e); } diff --git a/newio/MappedIO.java b/newio/MappedIO.java index 4bfac638..c1cbc0ed 100644 --- a/newio/MappedIO.java +++ b/newio/MappedIO.java @@ -7,8 +7,8 @@ import java.nio.channels.*; import java.io.*; public class MappedIO { - private static int numOfInts = 4000000; - private static int numOfUbuffInts = 200000; + private static int numOfInts = 4_000_000; + private static int numOfUbuffInts = 1_000_000; private abstract static class Tester { private String name; public Tester(String name) { this.name = name; } @@ -18,7 +18,7 @@ public class MappedIO { long start = System.nanoTime(); test(); double duration = System.nanoTime() - start; - System.out.format("%.2f\n", duration/1.0e9); + System.out.format("%.3f\n", duration/1.0e9); } catch(IOException e) { throw new RuntimeException(e); } @@ -42,8 +42,8 @@ public class MappedIO { @Override public void test() throws IOException { try(FileChannel fc = - new RandomAccessFile("temp.tmp", "rw") - .getChannel()) { + new RandomAccessFile("temp.tmp", "rw") + .getChannel()) { IntBuffer ib = fc.map( FileChannel.MapMode.READ_WRITE, 0, fc.size()) .asIntBuffer(); @@ -67,7 +67,7 @@ public class MappedIO { @Override public void test() throws IOException { try(FileChannel fc = new FileInputStream( - new File("temp.tmp")).getChannel()) { + new File("temp.tmp")).getChannel()) { IntBuffer ib = fc.map( FileChannel.MapMode.READ_ONLY, 0, fc.size()) .asIntBuffer(); @@ -110,10 +110,10 @@ public class MappedIO { } } /* Output: -Stream Write: 0.45 -Mapped Write: 0.04 -Stream Read: 0.42 -Mapped Read: 0.03 -Stream Read/Write: 3.43 -Mapped Read/Write: 0.00 +Stream Write: 0.329 +Mapped Write: 0.024 +Stream Read: 0.319 +Mapped Read: 0.019 +Stream Read/Write: 12.778 +Mapped Read/Write: 0.010 */ diff --git a/newio/TransferTo.java b/newio/TransferTo.java index 56d6e042..786955c0 100644 --- a/newio/TransferTo.java +++ b/newio/TransferTo.java @@ -8,16 +8,20 @@ import java.nio.channels.*; import java.io.*; public class TransferTo { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length != 2) { - System.out.println("arguments: sourcefile destfile"); + System.out.println( + "arguments: sourcefile destfile"); System.exit(1); } - FileChannel - in = new FileInputStream(args[0]).getChannel(), - out = new FileOutputStream(args[1]).getChannel(); - in.transferTo(0, in.size(), out); - // Or: - // out.transferFrom(in, 0, in.size()); + try(FileChannel in = new FileInputStream( + args[0]).getChannel(); + FileChannel out = new FileOutputStream( + args[1]).getChannel()) { + in.transferTo(0, in.size(), out); + // Or: + // out.transferFrom(in, 0, in.size()); + } } } diff --git a/newio/UsingBuffers.java b/newio/UsingBuffers.java index 5f22fa6b..3acf6c7a 100644 --- a/newio/UsingBuffers.java +++ b/newio/UsingBuffers.java @@ -5,7 +5,8 @@ import java.nio.*; public class UsingBuffers { - private static void symmetricScramble(CharBuffer buffer){ + private static + void symmetricScramble(CharBuffer buffer) { while(buffer.hasRemaining()) { buffer.mark(); char c1 = buffer.get(); diff --git a/newio/build.xml b/newio/build.xml index 772db621..1f0e5062 100644 --- a/newio/build.xml +++ b/newio/build.xml @@ -12,7 +12,6 @@ - @@ -29,7 +28,6 @@ - diff --git a/onjava/ArrayShow.java b/onjava/ArrayShow.java new file mode 100644 index 00000000..078d9373 --- /dev/null +++ b/onjava/ArrayShow.java @@ -0,0 +1,73 @@ +// onjava/ArrayShow.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +package onjava; +import java.util.*; + +public interface ArrayShow { + static void show(Object[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(boolean[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(byte[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(char[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(short[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(int[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(long[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(float[] a) { + System.out.println(Arrays.toString(a)); + } + static void show(double[] a) { + System.out.println(Arrays.toString(a)); + } + // Start with a description: + static void show(String info, Object[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, boolean[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, byte[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, char[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, short[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, int[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, long[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, float[] a) { + System.out.print(info + ": "); + show(a); + } + static void show(String info, double[] a) { + System.out.print(info + ": "); + show(a); + } +} diff --git a/onjava/BasicSupplier.java b/onjava/BasicSupplier.java index 6a9e27a4..e1c7e855 100644 --- a/onjava/BasicSupplier.java +++ b/onjava/BasicSupplier.java @@ -2,14 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Automatically create a Supplier, given a class -// with a default (no-arg) constructor. +// Supplier from a class with a no-arg constructor package onjava; import java.util.function.*; public class BasicSupplier implements Supplier { private Class type; - public BasicSupplier(Class type){ this.type = type; } + public BasicSupplier(Class type) { + this.type = type; + } @Override public T get() { try { @@ -20,7 +21,7 @@ public class BasicSupplier implements Supplier { throw new RuntimeException(e); } } - // Produce a Default generator given a type token: + // Produce a default Supplier from a type token: public static Supplier create(Class type) { return new BasicSupplier<>(type); } diff --git a/onjava/CollectionMethodDifferences.java b/onjava/CollectionMethodDifferences.java index d0ccd1f5..7e82604e 100644 --- a/onjava/CollectionMethodDifferences.java +++ b/onjava/CollectionMethodDifferences.java @@ -5,21 +5,21 @@ package onjava; import java.lang.reflect.*; import java.util.*; +import java.util.stream.*; public class CollectionMethodDifferences { static Set methodSet(Class type) { - Set result = new TreeSet<>(); - for(Method m : type.getMethods()) - result.add(m.getName()); - return result; + return Arrays.stream(type.getMethods()) + .map(Method::getName) + .collect(Collectors.toCollection(TreeSet::new)); } static void interfaces(Class type) { System.out.print("Interfaces in " + type.getSimpleName() + ": "); - List result = new ArrayList<>(); - for(Class c : type.getInterfaces()) - result.add(c.getSimpleName()); - System.out.println(result); + System.out.println( + Arrays.stream(type.getInterfaces()) + .map(Class::getSimpleName) + .collect(Collectors.toList())); } static Set object = methodSet(Object.class); static { object.add("clone"); } diff --git a/onjava/ConvertTo.java b/onjava/ConvertTo.java index 3c3f59de..3d4fd850 100644 --- a/onjava/ConvertTo.java +++ b/onjava/ConvertTo.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package onjava; -public class ConvertTo { +public interface ConvertTo { public static boolean[] primitive(Boolean[] in) { boolean[] result = new boolean[in.length]; for(int i = 0; i < in.length; i++) @@ -53,4 +53,53 @@ public class ConvertTo { result[i] = in[i]; return result; } + // Convert from primitive array to wrapped array: + public 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + Double[] result = new Double[in.length]; + for(int i = 0; i < in.length; i++) + result[i] = in[i]; + return result; + } } diff --git a/onjava/Count.java b/onjava/Count.java new file mode 100644 index 00000000..aba21970 --- /dev/null +++ b/onjava/Count.java @@ -0,0 +1,202 @@ +// onjava/Count.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Generate incremental values of different types +package onjava; +import java.util.*; +import java.util.function.*; +import static onjava.ConvertTo.*; + +public interface Count { + public static class Boolean + implements Supplier { + private boolean b = true; + @Override + public java.lang.Boolean get() { + b = !b; + return java.lang.Boolean.valueOf(b); + } + public java.lang.Boolean get(int n) { return get(); } + public java.lang.Boolean[] array(int sz) { + java.lang.Boolean[] result = + new java.lang.Boolean[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class boolean_ { + private boolean b = true; + public boolean get() { + b = !b; + return b; + } + public boolean get(int n) { return get(); } + public boolean[] array(int sz) { + return primitive(new Boolean().array(sz)); + } + } + public static class Byte + implements Supplier { + private byte b; + @Override + public java.lang.Byte get() { return b++; } + public java.lang.Byte get(int n) { return get(); } + public java.lang.Byte[] array(int sz) { + java.lang.Byte[] result = new java.lang.Byte[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class byte_ { + private byte b; + public byte get() { return b++; } + public byte get(int n) { return get(); } + public byte[] array(int sz) { + return primitive(new Byte().array(sz)); + } + } + static final 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]; + } + public java.lang.Character get(int n) { + return get(); + } + public java.lang.Character[] array(int sz) { + java.lang.Character[] result = + new java.lang.Character[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class char_ { + private int i; + public char get() { + i = (i + 1) % chars.length; + return chars[i]; + } + public char get(int n) { return get(); } + public char[] array(int sz) { + return primitive(new Character().array(sz)); + } + } + public static class Short + implements Supplier { + short s; + @Override + public java.lang.Short get() { return s++; } + public java.lang.Short get(int n) { return get(); } + public java.lang.Short[] array(int sz) { + java.lang.Short[] result = new java.lang.Short[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class short_ { + short s; + public short get() { return s++; } + public short get(int n) { return get(); } + public short[] array(int sz) { + return primitive(new Short().array(sz)); + } + } + public static class Integer + implements Supplier { + int i; + @Override + public java.lang.Integer get() { return i++; } + public java.lang.Integer get(int n) { return get(); } + public java.lang.Integer[] array(int sz) { + java.lang.Integer[] result = + new java.lang.Integer[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class int_ implements IntSupplier { + int i; + public int get() { return i++; } + public int get(int n) { return get(); } + @Override + public int getAsInt() { return get(); } + public int[] array(int sz) { + return primitive(new Integer().array(sz)); + } + } + public static class Long + implements Supplier { + private long l; + @Override + public java.lang.Long get() { return l++; } + public java.lang.Long get(int n) { return get(); } + public java.lang.Long[] array(int sz) { + java.lang.Long[] result = new java.lang.Long[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class long_ implements LongSupplier { + private long l; + public long get() { return l++; } + public long get(int n) { return get(); } + @Override + public long getAsLong() { return get(); } + public long[] array(int sz) { + return primitive(new Long().array(sz)); + } + } + public class Float + implements Supplier { + private int i; + @Override + public java.lang.Float get() { + return java.lang.Float.valueOf(i++); + } + public java.lang.Float get(int n) { return get(); } + public java.lang.Float[] array(int sz) { + java.lang.Float[] result = new java.lang.Float[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public class float_ { + private int i; + public float get() { return i++; } + public float get(int n) { return get(); } + public float[] array(int sz) { + return primitive(new Float().array(sz)); + } + } + public class Double + implements Supplier { + private int i; + @Override + public java.lang.Double get() { + return java.lang.Double.valueOf(i++); + } + public java.lang.Double get(int n) { return get(); } + public java.lang.Double[] array(int sz) { + java.lang.Double[] result = + new java.lang.Double[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public class double_ implements DoubleSupplier { + private int i; + public double get() { return i++; } + public double get(int n) { return get(); } + @Override + public double getAsDouble() { return get(0); } + public double[] array(int sz) { + return primitive(new Double().array(sz)); + } + } +} diff --git a/onjava/CountingMapData.java b/onjava/CountingFilledMap.java similarity index 90% rename from onjava/CountingMapData.java rename to onjava/CountingFilledMap.java index ac288b83..d7c85784 100644 --- a/onjava/CountingMapData.java +++ b/onjava/CountingFilledMap.java @@ -1,18 +1,18 @@ -// onjava/CountingMapData.java +// onjava/CountingFilledMap.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Unlimited-length Map containing sample data. +// Unlimited-length Map containing sample data package onjava; import java.util.*; -public class CountingMapData +public class CountingFilledMap extends AbstractMap { private int size; private static String[] chars = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" .split(" "); - public CountingMapData(int size) { + public CountingFilledMap(int size) { if(size < 0) this.size = 0; else this.size = size; } @@ -51,7 +51,7 @@ extends AbstractMap { return entries; } public static void main(String[] args) { - System.out.println(new CountingMapData(60)); + System.out.println(new CountingFilledMap(60)); } } /* Output: diff --git a/onjava/CountingIntegerList.java b/onjava/CountingIntegerList.java index 837c56d4..9036632d 100644 --- a/onjava/CountingIntegerList.java +++ b/onjava/CountingIntegerList.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://mindviewinc.com/Books/OnJava/ for more book information. -// List of any length, containing sample data. +// List of any length, containing sample data package onjava; import java.util.*; diff --git a/onjava/CountingSupplier.java b/onjava/CountingSupplier.java deleted file mode 100644 index 9668129f..00000000 --- a/onjava/CountingSupplier.java +++ /dev/null @@ -1,88 +0,0 @@ -// onjava/CountingSupplier.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Simple generator implementations. -package onjava; -import java.util.function.*; - -public class CountingSupplier { - public static class - Boolean implements Supplier { - private boolean value = false; - @Override - public java.lang.Boolean get() { - value = !value; // Just flips back and forth - return value; - } - } - public static class - Byte implements Supplier { - private byte value = 0; - @Override - public java.lang.Byte get() { return value++; } - } - static char[] chars = ("abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); - public static class - Character implements Supplier { - int index = -1; - @Override - public java.lang.Character get() { - index = (index + 1) % chars.length; - return chars[index]; - } - } - public static class - String implements Supplier { - private int length = 7; - Supplier cg = new Character(); - public String() {} - public String(int length) { this.length = length; } - @Override - public java.lang.String get() { - char[] buf = new char[length]; - for(int i = 0; i < length; i++) - buf[i] = cg.get(); - return new java.lang.String(buf); - } - } - public static class - Short implements Supplier { - private short value = 0; - @Override - public java.lang.Short get() { return value++; } - } - public static class - Integer implements Supplier { - private int value = 0; - @Override - public java.lang.Integer get() { return value++; } - } - public static class - Long implements Supplier { - private long value = 0; - @Override - public java.lang.Long get() { return value++; } - } - public static class - Float implements Supplier { - private float value = 0; - @Override - public java.lang.Float get() { - float result = value; - value += 1.0; - return result; - } - } - public static class - Double implements Supplier { - private double value = 0.0; - @Override - public java.lang.Double get() { - double result = value; - value += 1.0; - return result; - } - } -} diff --git a/onjava/Countries.java b/onjava/Countries.java index 580d38fb..e1d983bd 100644 --- a/onjava/Countries.java +++ b/onjava/Countries.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://mindviewinc.com/Books/OnJava/ for more book information. -// "Flyweight" Maps and Lists of sample data. +// "Flyweight" Maps and Lists of sample data package onjava; import java.util.*; @@ -82,7 +82,8 @@ public class Countries { {"BULGARIA","Sofia"}, {"GEORGIA","Tbilisi"}, {"KAZAKSTAN","Almaty"}, {"KYRGYZSTAN","Alma-Ata"}, {"MOLDOVA","Chisinau"}, {"RUSSIA","Moscow"}, - {"TAJIKISTAN","Dushanbe"}, {"TURKMENISTAN","Ashkabad"}, + {"TAJIKISTAN","Dushanbe"}, + {"TURKMENISTAN","Ashkabad"}, {"UKRAINE","Kyiv"}, {"UZBEKISTAN","Tashkent"}, // Europe {"ALBANIA","Tirana"}, {"ANDORRA","Andorra la Vella"}, diff --git a/onjava/DaemonThreadFactory.java b/onjava/DaemonThreadFactory.java index 85d4c98c..9fb59c52 100644 --- a/onjava/DaemonThreadFactory.java +++ b/onjava/DaemonThreadFactory.java @@ -5,7 +5,8 @@ package onjava; import java.util.concurrent.*; -public class DaemonThreadFactory implements ThreadFactory { +public class +DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); diff --git a/onjava/Deque.java b/onjava/Deque.java index 7ea45237..c83da38e 100644 --- a/onjava/Deque.java +++ b/onjava/Deque.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating a Deque from a LinkedList. +// Creating a Deque from a LinkedList package onjava; import java.util.*; diff --git a/onjava/Enums.java b/onjava/Enums.java index 12199f86..a9d1c85b 100644 --- a/onjava/Enums.java +++ b/onjava/Enums.java @@ -6,8 +6,9 @@ package onjava; import java.util.*; public class Enums { - private static Random rand = new Random(47); - public static > T random(Class ec) { + private static SplittableRandom rand = new SplittableRandom(47); + public static + > T random(Class ec) { return random(ec.getEnumConstants()); } public static T random(T[] values) { diff --git a/onjava/CollectionData.java b/onjava/FilledCollection.java similarity index 56% rename from onjava/CollectionData.java rename to onjava/FilledCollection.java index 81cc9ac6..382954a6 100644 --- a/onjava/CollectionData.java +++ b/onjava/FilledCollection.java @@ -1,20 +1,20 @@ -// onjava/CollectionData.java +// onjava/FilledCollection.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A Collection filled with data using a generator object. +// A Collection filled with data using a generator object package onjava; import java.util.*; import java.util.function.*; -public class CollectionData extends ArrayList { - public CollectionData(Supplier gen, int quantity) { +public class FilledCollection extends ArrayList { + public FilledCollection(Supplier gen, int quantity) { for(int i = 0; i < quantity; i++) add(gen.get()); } // A generic convenience method: - public static CollectionData + public static FilledCollection list(Supplier gen, int quantity) { - return new CollectionData<>(gen, quantity); + return new FilledCollection<>(gen, quantity); } } diff --git a/onjava/MapData.java b/onjava/FilledMap.java similarity index 57% rename from onjava/MapData.java rename to onjava/FilledMap.java index 1b7f4795..7bd7afed 100644 --- a/onjava/MapData.java +++ b/onjava/FilledMap.java @@ -1,64 +1,65 @@ -// onjava/MapData.java +// onjava/FilledMap.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A Map filled with data using a generator object. +// Fill a Map with data using a generator object package onjava; import java.util.*; import java.util.function.*; -public class MapData extends LinkedHashMap { +public class FilledMap extends LinkedHashMap { // A single Pair Supplier: - public MapData(Supplier> gen, int quantity) { + public FilledMap(Supplier> gen, int quantity) { for(int i = 0; i < quantity; i++) { Pair p = gen.get(); put(p.key, p.value); } } // Two separate Suppliers: - public MapData(Supplier genK, Supplier genV, + public FilledMap(Supplier genK, Supplier genV, int quantity) { for(int i = 0; i < quantity; i++) { put(genK.get(), genV.get()); } } // A key Supplier and a single value: - public MapData(Supplier genK, V value, int quantity){ + public + FilledMap(Supplier genK, V value, int quantity) { for(int i = 0; i < quantity; i++) { put(genK.get(), value); } } // An Iterable and a value Supplier: - public MapData(Iterable genK, Supplier genV) { + public FilledMap(Iterable genK, Supplier genV) { for(K key : genK) { put(key, genV.get()); } } // An Iterable and a single value: - public MapData(Iterable genK, V value) { + public FilledMap(Iterable genK, V value) { for(K key : genK) { put(key, value); } } // Generic convenience methods: - public static MapData + public static FilledMap map(Supplier> gen, int quantity) { - return new MapData<>(gen, quantity); + return new FilledMap<>(gen, quantity); } - public static MapData + public static FilledMap map(Supplier genK, Supplier genV, int quantity) { - return new MapData<>(genK, genV, quantity); + return new FilledMap<>(genK, genV, quantity); } - public static MapData + public static FilledMap map(Supplier genK, V value, int quantity) { - return new MapData<>(genK, value, quantity); + return new FilledMap<>(genK, value, quantity); } - public static MapData + public static FilledMap map(Iterable genK, Supplier genV) { - return new MapData<>(genK, genV); + return new FilledMap<>(genK, genV); } - public static MapData + public static FilledMap map(Iterable genK, V value) { - return new MapData<>(genK, value); + return new FilledMap<>(genK, value); } } diff --git a/onjava/Generated.java b/onjava/Generated.java deleted file mode 100644 index 3fd80021..00000000 --- a/onjava/Generated.java +++ /dev/null @@ -1,21 +0,0 @@ -// onjava/Generated.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -package onjava; -import java.util.function.*; - -public class Generated { - // Fill an existing array: - public static T[] array(T[] a, Supplier gen) { - return new CollectionData<>(gen, a.length).toArray(a); - } - // Create a new array: - @SuppressWarnings("unchecked") - public static T[] array(Class type, - Supplier gen, int size) { - T[] a = - (T[])java.lang.reflect.Array.newInstance(type, size); - return new CollectionData<>(gen, size).toArray(a); - } -} diff --git a/onjava/Hex.java b/onjava/Hex.java index 8f4098b7..a22eaf2b 100644 --- a/onjava/Hex.java +++ b/onjava/Hex.java @@ -20,7 +20,8 @@ public class Hex { result.append("\n"); return result.toString(); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length == 0) // Test by displaying this class file: System.out.println(format( diff --git a/onjava/OSExecute.java b/onjava/OSExecute.java index 52495f6a..5ba9195b 100644 --- a/onjava/OSExecute.java +++ b/onjava/OSExecute.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Run an operating system command -// and send the output to the console. +// and send the output to the console package onjava; import java.io.*; @@ -13,29 +13,26 @@ public class OSExecute { try { Process process = new ProcessBuilder(command.split(" ")).start(); - BufferedReader results = new BufferedReader( - new InputStreamReader(process.getInputStream())); - String s; - while((s = results.readLine())!= null) - System.out.println(s); - BufferedReader errors = new BufferedReader( - new InputStreamReader(process.getErrorStream())); - // Report errors and return nonzero value - // to calling process if there are problems: - while((s = errors.readLine())!= null) { - System.err.println(s); - err = true; + try(BufferedReader results = new BufferedReader( + new InputStreamReader(process.getInputStream())); + BufferedReader errors = new BufferedReader( + new InputStreamReader( + process.getErrorStream()))) { + String s; + while((s = results.readLine())!= null) + System.out.println(s); + // Report errors and return nonzero value + // to calling process if there are problems: + while((s = errors.readLine())!= null) { + System.err.println(s); + err = true; + } } } catch(Exception e) { - // Compensate for Windows 2000, which throws an - // exception for the default command line: - if(!command.startsWith("CMD /C")) - command("CMD /C " + command); - else - throw new RuntimeException(e); + throw new RuntimeException(e); } if(err) - throw new OSExecuteException("Errors executing " + - command); + throw new OSExecuteException( + "Errors executing " + command); } } diff --git a/onjava/Rand.java b/onjava/Rand.java new file mode 100644 index 00000000..d8f075b4 --- /dev/null +++ b/onjava/Rand.java @@ -0,0 +1,224 @@ +// onjava/Rand.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Generate random values of different types +package onjava; +import java.util.*; +import java.util.function.*; +import static onjava.ConvertTo.*; + +public interface Rand { + static final int MOD = 10_000; + public static class Boolean + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Boolean get() { + return r.nextBoolean(); + } + public java.lang.Boolean get(int n) { + return get(); + } + public java.lang.Boolean[] array(int sz) { + java.lang.Boolean[] result = + new java.lang.Boolean[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class boolean_ { + public boolean[] array(int sz) { + return primitive(new Boolean().array(sz)); + } + } + public static class Byte + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Byte get() { + return (byte)r.nextInt(MOD); + } + public java.lang.Byte get(int n) { return get(); } + public java.lang.Byte[] array(int sz) { + java.lang.Byte[] result = new java.lang.Byte[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class byte_ { + public byte[] array(int sz) { + return primitive(new Byte().array(sz)); + } + } + public static class Character + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Character get() { + return (char)r.nextInt('a', 'z' + 1); + } + public java.lang.Character get(int n) { + return get(); + } + public java.lang.Character[] array(int sz) { + java.lang.Character[] result = + new java.lang.Character[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class char_ { + public char[] array(int sz) { + return primitive(new Character().array(sz)); + } + } + public static class Short + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Short get() { + return (short)r.nextInt(MOD); + } + public java.lang.Short get(int n) { return get(); } + public java.lang.Short[] array(int sz) { + java.lang.Short[] result = new java.lang.Short[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class short_ { + public short[] array(int sz) { + return primitive(new Short().array(sz)); + } + } + public static class Integer + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Integer get() { + return r.nextInt(MOD); + } + public java.lang.Integer get(int n) { return get(); } + public java.lang.Integer[] array(int sz) { + int[] primitive = new int_().array(sz); + java.lang.Integer[] result = + new java.lang.Integer[sz]; + for(int i = 0; i < sz; i++) + result[i] = primitive[i]; + return result; + } + } + public static class int_ implements IntSupplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public int getAsInt() { return r.nextInt(MOD); } + public int get(int n) { return getAsInt(); } + public int[] array(int sz) { + return r.ints(sz, 0, MOD).toArray(); + } + } + public static class Long + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Long get() { + return r.nextLong(MOD); + } + public java.lang.Long get(int n) { return get(); } + public java.lang.Long[] array(int sz) { + long[] primitive = new long_().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 { + SplittableRandom r = new SplittableRandom(47); + @Override + public long getAsLong() { + return r.nextLong(MOD); + } + public long get(int n) { return getAsLong(); } + public long[] array(int sz) { + return r.longs(sz, 0, MOD).toArray(); + } + } + public static class Float + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Float get() { + return (float)trim(r.nextDouble()); + } + public java.lang.Float get(int n) { return get(); } + public java.lang.Float[] array(int sz) { + java.lang.Float[] result = new java.lang.Float[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + public static class float_ { + public float[] array(int sz) { + return primitive(new Float().array(sz)); + } + } + static double trim(double d) { + return ((double)Math.round(d * 1000.0)) / 100.0; + } + public static class Double + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Double get() { + return trim(r.nextDouble()); + } + public java.lang.Double get(int n) { return get(); } + public java.lang.Double[] array(int sz) { + double[] primitive = new Rand.double_().array(sz); + java.lang.Double[] result = + new java.lang.Double[sz]; + for(int i = 0; i < sz; i++) + result[i] = primitive[i]; + return result; + } + } + public static class double_ implements DoubleSupplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public double getAsDouble() { + return trim(r.nextDouble()); + } + public double get(int n) { return getAsDouble(); } + public double[] array(int sz) { + double[] result = r.doubles(sz).toArray(); + Arrays.setAll(result, + n -> result[n] = trim(result[n])); + return result; + } + } + public static class String + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + private int strlen = 7; // Default string length + public String() {} + public String(int str_length) { + strlen = str_length; + } + @Override + public java.lang.String get() { + return r.ints(strlen, 'a', 'z' + 1) + .collect(StringBuilder::new, + StringBuilder::appendCodePoint, + StringBuilder::append).toString(); + } + public java.lang.String get(int n) { return get(); } + public java.lang.String[] array(int sz) { + java.lang.String[] result = + new java.lang.String[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } +} diff --git a/onjava/RandomSupplier.java b/onjava/RandomSupplier.java deleted file mode 100644 index b872a2e7..00000000 --- a/onjava/RandomSupplier.java +++ /dev/null @@ -1,85 +0,0 @@ -// onjava/RandomSupplier.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Suppliers that produce random values. -package onjava; -import java.util.*; -import java.util.function.*; - -public class RandomSupplier { - private static Random r = new Random(47); - public static class - Boolean implements Supplier { - @Override - public java.lang.Boolean get() { - return r.nextBoolean(); - } - } - public static class - Byte implements Supplier { - @Override - public java.lang.Byte get() { - return (byte)r.nextInt(); - } - } - public static class - Character implements Supplier { - @Override - public java.lang.Character get() { - return CountingSupplier.chars[ - r.nextInt(CountingSupplier.chars.length)]; - } - } - public static class - String extends CountingSupplier.String { - // Plug in the random Character generator: - { cg = new Character(); } // Instance initializer - public String() {} - public String(int length) { super(length); } - } - public static class - Short implements Supplier { - @Override - public java.lang.Short get() { - return (short)r.nextInt(); - } - } - public static class - Integer implements Supplier { - private int mod = 10000; - public Integer() {} - public Integer(int modulo) { mod = modulo; } - @Override - public java.lang.Integer get() { - return r.nextInt(mod); - } - } - public static class - Long implements Supplier { - private int mod = 10000; - public Long() {} - public Long(int modulo) { mod = modulo; } - @Override - public java.lang.Long get() { - return (long) r.nextInt(mod); - } - } - public static class - Float implements Supplier { - @Override - public java.lang.Float get() { - // Trim all but the first two decimal places: - int trimmed = Math.round(r.nextFloat() * 100); - return ((float)trimmed) / 100; - } - } - public static class - Double implements Supplier { - @Override - public java.lang.Double get() { - long trimmed = Math.round(r.nextDouble() * 100); - return ((double)trimmed) / 100; - } - } -} diff --git a/onjava/Range.java b/onjava/Range.java index 17d37f41..70565c69 100644 --- a/onjava/Range.java +++ b/onjava/Range.java @@ -23,7 +23,8 @@ public class Range { return result; } // Produce a sequence [start..end) incrementing by step - public static int[] range(int start, int end, int step) { + public static + int[] range(int start, int end, int step) { int sz = (end - start)/step; int[] result = new int[sz]; for(int i = 0; i < sz; i++) diff --git a/onjava/RmDir.java b/onjava/RmDir.java index 83c5aaba..1d4e7d65 100644 --- a/onjava/RmDir.java +++ b/onjava/RmDir.java @@ -9,7 +9,7 @@ import java.io.IOException; public class RmDir { public static void rmdir(Path dir) throws IOException { - Files.walkFileTree(dir, new SimpleFileVisitor(){ + Files.walkFileTree(dir,new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) diff --git a/onjava/Sets.java b/onjava/Sets.java index 862aac80..bdd11e2f 100644 --- a/onjava/Sets.java +++ b/onjava/Sets.java @@ -25,7 +25,8 @@ public class Sets { return result; } // Reflexive--everything not in the intersection: - public static Set complement(Set a, Set b) { + public static + Set complement(Set a, Set b) { return difference(union(a, b), intersection(a, b)); } } diff --git a/onjava/Sleep.java b/onjava/Sleep.java index 95a6b953..d30658ae 100644 --- a/onjava/Sleep.java +++ b/onjava/Sleep.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://mindviewinc.com/Books/OnJava/ for more book information. -// Sleep for n seconds. +// Sleep for n seconds package onjava; import java.util.concurrent.*; diff --git a/onjava/Stack.java b/onjava/Stack.java index f009be90..49ae8450 100644 --- a/onjava/Stack.java +++ b/onjava/Stack.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://mindviewinc.com/Books/OnJava/ for more book information. -// Making a stack from a LinkedList. +// Making a stack from a LinkedList package onjava; import java.util.LinkedList; @@ -11,7 +11,11 @@ public class Stack { public void push(T v) { storage.addFirst(v); } public T peek() { return storage.getFirst(); } public T pop() { return storage.removeFirst(); } - public boolean empty() { return storage.isEmpty(); } + public boolean empty() { + return storage.isEmpty(); + } @Override - public String toString() { return storage.toString(); } + public String toString() { + return storage.toString(); + } } diff --git a/onjava/Suppliers.java b/onjava/Suppliers.java new file mode 100644 index 00000000..c04f4527 --- /dev/null +++ b/onjava/Suppliers.java @@ -0,0 +1,37 @@ +// onjava/Suppliers.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// A utility to use with Suppliers +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: + public static > + C create(Supplier factory, Supplier gen, int n) { + return Stream.generate(gen) + .limit(n) + .collect(factory, C::add, C::addAll); + } + // Fill an existing collection: + public static > + C fill(C coll, Supplier gen, int n) { + Stream.generate(gen) + .limit(n) + .forEach(coll::add); + return coll; + } + // Use an unbound method reference to + // produce a more general method: + public static H fill(H holder, + BiConsumer adder, Supplier gen, int n) { + Stream.generate(gen) + .limit(n) + .forEach(a -> adder.accept(holder, a)); + return holder; + } +} diff --git a/onjava/SwingConsole.java b/onjava/SwingConsole.java index 4091bba9..a2f8158c 100644 --- a/onjava/SwingConsole.java +++ b/onjava/SwingConsole.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Tool for running Swing demos from the -// console, both applets and JFrames. +// console, both applets and JFrames package onjava; import javax.swing.*; diff --git a/onjava/TaskItem.java b/onjava/TaskItem.java index 7a4f82b4..5c9cfdca 100644 --- a/onjava/TaskItem.java +++ b/onjava/TaskItem.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://mindviewinc.com/Books/OnJava/ for more book information. -// A Future and the Callable that produced it. +// A Future and the Callable that produced it package onjava; import java.util.concurrent.*; diff --git a/onjava/TaskManager.java b/onjava/TaskManager.java index ed1f1624..77c02147 100644 --- a/onjava/TaskManager.java +++ b/onjava/TaskManager.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://mindviewinc.com/Books/OnJava/ for more book information. -// Managing and executing a queue of tasks. +// Managing and executing a queue of tasks package onjava; import java.util.concurrent.*; import java.util.*; diff --git a/onjava/TimeIt.java b/onjava/TimeIt.java new file mode 100644 index 00000000..e48625f3 --- /dev/null +++ b/onjava/TimeIt.java @@ -0,0 +1,17 @@ +// onjava/TimeIt.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +package onjava; +import java.util.concurrent.*; + +public interface TimeIt { + static long timeIt(Runnable test) { + long start = System.nanoTime(); + test.run(); + long delta = System.nanoTime() - start; + long millis = TimeUnit.NANOSECONDS.toMillis(delta); + System.out.println(millis); + return millis; + } +} diff --git a/onjava/TimedAbort.java b/onjava/TimedAbort.java index f8b76cbd..69fbfd7c 100644 --- a/onjava/TimedAbort.java +++ b/onjava/TimedAbort.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://mindviewinc.com/Books/OnJava/ for more book information. -// Terminate a program after n seconds. +// Terminate a program after n seconds package onjava; import java.util.*; diff --git a/onjava/Tuple.java b/onjava/Tuple.java index 4bde61b3..ac6bef81 100644 --- a/onjava/Tuple.java +++ b/onjava/Tuple.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://mindviewinc.com/Books/OnJava/ for more book information. -// Tuple library using type argument inference. +// Tuple library using type argument inference package onjava; public class Tuple { diff --git a/onjava/Tuple3.java b/onjava/Tuple3.java index d874e262..f324a56d 100644 --- a/onjava/Tuple3.java +++ b/onjava/Tuple3.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package onjava; -public class Tuple3 extends Tuple2 { +public class Tuple3 extends Tuple2 { public final C _3; public Tuple3(A a, B b, C c) { super(a, b); diff --git a/onjava/TypeCounter.java b/onjava/TypeCounter.java index ec5a2960..f94a8bd4 100644 --- a/onjava/TypeCounter.java +++ b/onjava/TypeCounter.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://mindviewinc.com/Books/OnJava/ for more book information. -// Counts instances of a type family. +// Counts instances of a type family package onjava; import java.util.*; diff --git a/onjava/atunit/AtUnit.java b/onjava/atunit/AtUnit.java index 3927ea80..569132fb 100644 --- a/onjava/atunit/AtUnit.java +++ b/onjava/atunit/AtUnit.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://mindviewinc.com/Books/OnJava/ for more book information. -// An annotation-based unit-test framework. +// An annotation-based unit-test framework package onjava.atunit; import java.lang.reflect.*; import java.io.*; @@ -16,7 +16,8 @@ public class AtUnit implements ProcessFiles.Strategy { static List failedTests= new ArrayList<>(); static long testsRun = 0; static long failures = 0; - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { ClassLoader.getSystemClassLoader() .setDefaultAssertionStatus(true); // Enable asserts new ProcessFiles(new AtUnit(), "class").start(args); @@ -24,7 +25,8 @@ public class AtUnit implements ProcessFiles.Strategy { System.out.println("OK (" + testsRun + " tests)"); else { System.out.println("(" + testsRun + " tests)"); - System.out.println("\n>>> " + failures + " FAILURE" + + System.out.println( + "\n>>> " + failures + " FAILURE" + (failures > 1 ? "S" : "") + " <<<"); for(String failed : failedTests) System.out.println(" " + failed); diff --git a/onjava/atunit/ClassNameFinder.java b/onjava/atunit/ClassNameFinder.java index c1c9d120..d4c0d7d5 100644 --- a/onjava/atunit/ClassNameFinder.java +++ b/onjava/atunit/ClassNameFinder.java @@ -76,7 +76,8 @@ public class ClassNameFinder { } } // Demonstration: - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { PathMatcher matcher = FileSystems.getDefault() .getPathMatcher("glob:**/*.class"); // Walk the entire tree: diff --git a/onjava/atunit/Test.java b/onjava/atunit/Test.java index 9e64435f..4946c4c5 100644 --- a/onjava/atunit/Test.java +++ b/onjava/atunit/Test.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://mindviewinc.com/Books/OnJava/ for more book information. -// The @Test tag. +// The @Test tag package onjava.atunit; import java.lang.annotation.*; diff --git a/onjava/atunit/TestObjectCleanup.java b/onjava/atunit/TestObjectCleanup.java index f0758c26..35c6b019 100644 --- a/onjava/atunit/TestObjectCleanup.java +++ b/onjava/atunit/TestObjectCleanup.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://mindviewinc.com/Books/OnJava/ for more book information. -// The @Unit @TestObjectCleanup tag. +// The @Unit @TestObjectCleanup tag package onjava.atunit; import java.lang.annotation.*; diff --git a/onjava/atunit/TestObjectCreate.java b/onjava/atunit/TestObjectCreate.java index 6c7fb6c7..8b7271b2 100644 --- a/onjava/atunit/TestObjectCreate.java +++ b/onjava/atunit/TestObjectCreate.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://mindviewinc.com/Books/OnJava/ for more book information. -// The @Unit @TestObjectCreate tag. +// The @Unit @TestObjectCreate tag package onjava.atunit; import java.lang.annotation.*; diff --git a/onjava/atunit/TestProperty.java b/onjava/atunit/TestProperty.java index e1c77e88..d13fd5a1 100644 --- a/onjava/atunit/TestProperty.java +++ b/onjava/atunit/TestProperty.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://mindviewinc.com/Books/OnJava/ for more book information. -// The @Unit @TestProperty tag. +// The @Unit @TestProperty tag package onjava.atunit; import java.lang.annotation.*; diff --git a/onjava/build.xml b/onjava/build.xml index 9afb2aaf..d224e4ae 100644 --- a/onjava/build.xml +++ b/onjava/build.xml @@ -8,8 +8,8 @@ + - @@ -18,8 +18,8 @@ + - diff --git a/operators/AllOps.java b/operators/AllOps.java index bbd3c0d8..b0afec16 100644 --- a/operators/AllOps.java +++ b/operators/AllOps.java @@ -2,8 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Tests all the operators on all the primitive data types -// to show which ones are accepted by the Java compiler. +// Tests all operators on all primitive data types +// to show which ones are accepted by the Java compiler public class AllOps { // To accept the results of a boolean test: diff --git a/operators/Assignment.java b/operators/Assignment.java index 7e2a61f3..9e57fbb6 100644 --- a/operators/Assignment.java +++ b/operators/Assignment.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://mindviewinc.com/Books/OnJava/ for more book information. -// Assignment with objects is a bit tricky. +// Assignment with objects is a bit tricky class Tank { int level; diff --git a/operators/AutoInc.java b/operators/AutoInc.java index d782b257..ee1ad587 100644 --- a/operators/AutoInc.java +++ b/operators/AutoInc.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the ++ and -- operators. +// Demonstrates the ++ and -- operators public class AutoInc { public static void main(String[] args) { diff --git a/operators/BitManipulation.java b/operators/BitManipulation.java index f4eb7799..5541c9c2 100644 --- a/operators/BitManipulation.java +++ b/operators/BitManipulation.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using the bitwise operators. +// Using the bitwise operators import java.util.*; public class BitManipulation { diff --git a/operators/Bool.java b/operators/Bool.java index 2c48fb2e..e2b885a5 100644 --- a/operators/Bool.java +++ b/operators/Bool.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://mindviewinc.com/Books/OnJava/ for more book information. -// Relational and logical operators. +// Relational and logical operators import java.util.*; public class Bool { diff --git a/operators/EqualsMethod2.java b/operators/EqualsMethod2.java index 0d3233b5..2c4f8196 100644 --- a/operators/EqualsMethod2.java +++ b/operators/EqualsMethod2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Default equals() does not compare contents. +// Default equals() does not compare contents class Value { int i; diff --git a/operators/MathOps.java b/operators/MathOps.java index dd8cb55f..a75fd84a 100644 --- a/operators/MathOps.java +++ b/operators/MathOps.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the mathematical operators. +// The mathematical operators import java.util.*; public class MathOps { diff --git a/operators/Overflow.java b/operators/Overflow.java index b965e773..4e75edcd 100644 --- a/operators/Overflow.java +++ b/operators/Overflow.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://mindviewinc.com/Books/OnJava/ for more book information. -// Surprise! Java lets you overflow. +// Surprise! Java lets you overflow public class Overflow { public static void main(String[] args) { diff --git a/operators/PassObject.java b/operators/PassObject.java index 27b722de..f1e9564f 100644 --- a/operators/PassObject.java +++ b/operators/PassObject.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Passing objects to methods might not be -// what you're used to. +// what you're used to class Letter { char c; diff --git a/operators/RoundingNumbers.java b/operators/RoundingNumbers.java index f12cf970..c98d6281 100644 --- a/operators/RoundingNumbers.java +++ b/operators/RoundingNumbers.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://mindviewinc.com/Books/OnJava/ for more book information. -// Rounding floats and doubles. +// Rounding floats and doubles public class RoundingNumbers { public static void main(String[] args) { diff --git a/operators/ShortCircuit.java b/operators/ShortCircuit.java index f5cc0e8c..3f58f82e 100644 --- a/operators/ShortCircuit.java +++ b/operators/ShortCircuit.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://mindviewinc.com/Books/OnJava/ for more book information. -// Short-circuiting behavior with logical operators. +// Short-circuiting behavior with logical operators public class ShortCircuit { static boolean test1(int val) { diff --git a/operators/URShift.java b/operators/URShift.java index 7e1701d0..e2ae68dd 100644 --- a/operators/URShift.java +++ b/operators/URShift.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://mindviewinc.com/Books/OnJava/ for more book information. -// Test of unsigned right shift. +// Test of unsigned right shift public class URShift { public static void main(String[] args) { diff --git a/output_duet.py b/output_duet.py index 564328f4..d7a8f3b9 100644 --- a/output_duet.py +++ b/output_duet.py @@ -4,8 +4,7 @@ # Visit http://mindviewinc.com/Books/OnJava/ for more book information. """ ToDo: - - Validate errors (.err files, not just .out files) - - Are there any duplicate file names throughout the book? + - Right now it's ignoring the "(first x lines)" examples """ import sys from pathlib import Path @@ -33,10 +32,14 @@ class IgnoreDigits(Adjuster): trace("Ignoring digits") return trim(re.sub("-?\d", "", input_text)) +ignore_digits = IgnoreDigits() + class IgnoreMemoryAddresses(Adjuster): def adjust(self, input_text): return trim(memlocation.sub("", input_text)) +ignore_memory_addresses = IgnoreMemoryAddresses() + class RemoveCharacters(Adjuster): def __init__(self, chars_to_remove): self.chars_to_remove = chars_to_remove @@ -45,30 +48,40 @@ class RemoveCharacters(Adjuster): input_text = input_text.replace(c, "") return input_text -class CompareSortedLines(Adjuster): +class SortLines(Adjuster): def adjust(self, input_text): return "\n".join(sorted(input_text.splitlines())).strip() -class CompareSortedWords(Adjuster): +sort_lines = SortLines() + +class SortWords(Adjuster): def adjust(self, input_text): return "\n".join(sorted(input_text.split())).strip() -class CompareUniqueLines(Adjuster): +sort_words = SortWords() + +class UniqueLines(Adjuster): def adjust(self, input_text): return "\n".join(sorted(list(set(input_text.splitlines())))) -class CompareUniqueWords(Adjuster): +unique_lines = UniqueLines() + +class UniqueWords(Adjuster): # Fairly extreme but will still reveal significant changes def adjust(self, input_text): return "\n".join(sorted(set(input_text.split()))) -class CompareWordsOnly(Adjuster): +unique_words = UniqueWords() + +class WordsOnly(Adjuster): # Fairly extreme but will still reveal significant changes def adjust(self, input_text): return "\n".join( sorted([w for w in input_text.split() if word_only.fullmatch(w)])) +words_only = WordsOnly() + class IgnoreLines(Adjuster): def __init__(self, *lines_to_ignore): self.lines_to_ignore = lines_to_ignore @@ -76,83 +89,86 @@ class IgnoreLines(Adjuster): lines = input_text.splitlines() for ignore in sorted(list(self.lines_to_ignore), reverse=True): ignore = ignore - 1 # Compensate for zero indexing - trace("ignoring line %d: %s" % (ignore, lines[ignore])) + print("ignoring line %d: %s" % (ignore, lines[ignore])) del lines[ignore] return "\n".join(lines) match_adjustments = { - "ToastOMatic.java" : CompareSortedLines(), - "ThreadVariations.java" : CompareSortedLines(), - "ActiveObjectDemo.java" : [CompareSortedLines(), IgnoreDigits()], - "Interrupting.java" : CompareSortedLines(), - "SyncObject.java" : CompareSortedLines(), - "UseCaseTracker.java" : CompareSortedLines(), - "AtUnitComposition.java" : CompareSortedLines(), - "AtUnitExample1.java" : CompareSortedLines(), - "AtUnitExample2.java" : CompareSortedLines(), - "AtUnitExample3.java" : CompareSortedLines(), - "AtUnitExample5.java" : CompareSortedLines(), - "AtUnitExternalTest.java" : CompareSortedLines(), - "HashSetTest.java" : CompareSortedLines(), - "StackLStringTest.java" : CompareSortedLines(), - "WaxOMatic2.java" : CompareSortedLines(), + "ToastOMatic.java" : sort_lines, + "ThreadVariations.java" : sort_lines, + "ActiveObjectDemo.java" : [sort_lines, ignore_digits], + "Interrupting.java" : sort_lines, + "SyncObject.java" : sort_lines, + "UseCaseTracker.java" : sort_lines, + "AtUnitComposition.java" : sort_lines, + "AtUnitExample1.java" : sort_lines, + "AtUnitExample2.java" : sort_lines, + "AtUnitExample3.java" : sort_lines, + "AtUnitExample5.java" : sort_lines, + "AtUnitExternalTest.java" : sort_lines, + "HashSetTest.java" : sort_lines, + "StackLStringTest.java" : sort_lines, + "WaxOMatic2.java" : sort_lines, - "ForEach.java" : CompareSortedWords(), - "PetCount4.java" : [RemoveCharacters("{}"), CompareSortedWords()], + "ForEach.java" : sort_words, + "PetCount4.java" : [RemoveCharacters("{}"), sort_words], - "CachedThreadPool.java" : CompareWordsOnly(), - "FixedThreadPool.java" : CompareWordsOnly(), - "MoreBasicThreads.java" : CompareWordsOnly(), - "ConstantSpecificMethod.java" : CompareWordsOnly(), + "CachedThreadPool.java" : words_only, + "FixedThreadPool.java" : words_only, + "MoreBasicThreads.java" : words_only, + "ConstantSpecificMethod.java" : words_only, - "BankTellerSimulation.java" : [CompareWordsOnly(), CompareUniqueWords()], + "BankTellerSimulation.java" : [words_only, unique_words], + + "MapComparisons.java" : ignore_digits, + "ListComparisons.java" : ignore_digits, + "NotifyVsNotifyAll.java" : ignore_digits, + "SelfManaged.java" : ignore_digits, + "SimpleMicroBenchmark.java" : ignore_digits, + "SimpleThread.java" : ignore_digits, + "SleepingTask.java" : ignore_digits, + "ExchangerDemo.java" : ignore_digits, + "Compete.java" : ignore_digits, + "MappedIO.java" : ignore_digits, + "Directories.java" : ignore_digits, + "Find.java" : ignore_digits, + "PathAnalysis.java" : ignore_digits, + "TreeWatcher.java" : ignore_digits, + "Mixins.java" : ignore_digits, + "ListPerformance.java" : ignore_digits, + "MapPerformance.java" : ignore_digits, + "SetPerformance.java" : ignore_digits, + "SynchronizationComparisons.java" : ignore_digits, + "AtomicityTest.java" : ignore_digits, + "TypesForSets.java" : ignore_digits, + "PrintableLogRecord.java" : ignore_digits, + "LockingMappedFiles.java" : ignore_digits, - "MapComparisons.java" : IgnoreDigits(), - "ListComparisons.java" : IgnoreDigits(), - "NotifyVsNotifyAll.java" : IgnoreDigits(), - "SelfManaged.java" : IgnoreDigits(), - "SimpleMicroBenchmark.java" : IgnoreDigits(), - "SimpleThread.java" : IgnoreDigits(), - "SleepingTask.java" : IgnoreDigits(), - "ExchangerDemo.java" : IgnoreDigits(), - "Compete.java" : IgnoreDigits(), - "MappedIO.java" : IgnoreDigits(), - "Directories.java" : IgnoreDigits(), - "Find.java" : IgnoreDigits(), - "PathAnalysis.java" : IgnoreDigits(), - "TreeWatcher.java" : IgnoreDigits(), - "Mixins.java" : IgnoreDigits(), - "ListPerformance.java" : IgnoreDigits(), - "MapPerformance.java" : IgnoreDigits(), - "SetPerformance.java" : IgnoreDigits(), - "SynchronizationComparisons.java" : IgnoreDigits(), - "AtomicityTest.java" : IgnoreDigits(), - "TypesForSets.java" : IgnoreDigits(), - "PrintableLogRecord.java" : IgnoreDigits(), - "LockingMappedFiles.java" : IgnoreDigits(), "Conversion.java" : IgnoreLines(27, 28), "DynamicProxyMixin.java" : IgnoreLines(2), "PreferencesDemo.java" : IgnoreLines(5), + "AtUnitExample4.java" : IgnoreLines(6, 9), - "SerialNumberChecker.java" : [IgnoreDigits(), CompareUniqueLines()], - "EvenSupplier.java" : [IgnoreDigits(), CompareUniqueLines()], + "SerialNumberChecker.java" : [ignore_digits, unique_lines], + "EvenSupplier.java" : [ignore_digits, unique_lines], - "FillingLists.java" : [ IgnoreMemoryAddresses(), CompareSortedWords() ], + "FillingLists.java" : [ ignore_memory_addresses, sort_words ], - "SimpleDaemons.java" : [ IgnoreMemoryAddresses(), IgnoreDigits() ], + "SimpleDaemons.java" : [ ignore_memory_addresses, ignore_digits ], "CaptureUncaughtException.java" : [ - IgnoreMemoryAddresses(), IgnoreDigits(), CompareUniqueLines() ], + ignore_memory_addresses, ignore_digits, unique_lines ], - "CarBuilder.java" : [ IgnoreDigits(), CompareUniqueLines() ], - "CloseResource.java" : [ CompareUniqueLines() ], + "CarBuilder.java" : [ ignore_digits, unique_lines ], + "CloseResource.java" : [ unique_lines ], - "SpringDetector.java" : [ IgnoreDigits(), CompareSortedWords() ], + "SpringDetector.java" : [ ignore_digits, sort_words ], - "PipedIO.java" : [ CompareUniqueWords() ], + "PipedIO.java" : [ unique_words ], - "ExplicitCriticalSection.java" : IgnoreDigits(), + "CriticalSection.java" : ignore_digits, + "ExplicitCriticalSection.java" : ignore_digits, } diff --git a/patterns/CommandPattern.java b/patterns/CommandPattern.java index a8894364..774d9d84 100644 --- a/patterns/CommandPattern.java +++ b/patterns/CommandPattern.java @@ -5,7 +5,7 @@ import java.util.*; public class CommandPattern { - public static void main(String args[]) { + public static void main(String[] args) { List macro = Arrays.asList( () -> System.out.print("Hello "), () -> System.out.print("World! "), diff --git a/patterns/Facade.java b/patterns/Facade.java index b1e935b8..606324a2 100644 --- a/patterns/Facade.java +++ b/patterns/Facade.java @@ -14,7 +14,7 @@ public class Facade { static A makeA(int x) { return new A(x); } static B makeB(long x) { return new B(x); } static C makeC(double x) { return new C(x); } - public static void main(String args[]) { + public static void main(String[] args) { // The client programmer gets the objects // by calling the static methods: A a = Facade.makeA(1); diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java index d5fecd2b..79a182fc 100644 --- a/patterns/PaperScissorsRock.java +++ b/patterns/PaperScissorsRock.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of multiple dispatching. +// Demonstration of multiple dispatching import java.util.*; import java.util.function.*; import java.util.stream.*; @@ -86,7 +86,7 @@ class ItemFactory { Arrays.asList( Scissors::new, Paper::new, Rock::new); final static int sz = items.size(); - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); public static Item newItem() { return items.get(rand.nextInt(sz)).get(); } @@ -103,7 +103,7 @@ class Compete { } public class PaperScissorsRock { - public static void main(String args[]) { + public static void main(String[] args) { Stream.generate(ItemFactory::newPair) .limit(20) .map(Compete::match) diff --git a/patterns/ProxyDemo.java b/patterns/ProxyDemo.java index 11c7cf26..1323a97f 100644 --- a/patterns/ProxyDemo.java +++ b/patterns/ProxyDemo.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple demonstration of the Proxy pattern. +// Simple demonstration of the Proxy pattern interface ProxyBase { void f(); @@ -37,7 +37,7 @@ class Implementation implements ProxyBase { } public class ProxyDemo { - public static void main(String args[]) { + public static void main(String[] args) { Proxy p = new Proxy(); p.f(); p.g(); diff --git a/patterns/ShapeFactory2.java b/patterns/ShapeFactory2.java index 6df3ea9e..692e487e 100644 --- a/patterns/ShapeFactory2.java +++ b/patterns/ShapeFactory2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Polymorphic factory methods. +// Polymorphic factory methods import java.util.*; import java.util.function.*; import java.util.stream.*; @@ -65,7 +65,7 @@ class Square implements Shape { } public class ShapeFactory2 { - public static void main(String args[]) { + public static void main(String[] args) { List shapes = Stream.of("Circle", "Square", "Square", "Circle", "Circle", "Square") .map(ShapeFactory::createShape) diff --git a/patterns/StateDemo.java b/patterns/StateDemo.java index b9b46165..4a738b9e 100644 --- a/patterns/StateDemo.java +++ b/patterns/StateDemo.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple demonstration of the State pattern. +// Simple demonstration of the State pattern interface StateBase { void f(); @@ -69,7 +69,7 @@ public class StateDemo { b.g(); b.h(); } - public static void main(String args[]) { + public static void main(String[] args) { StateBase b = new State(new Implementation1()); test(b); diff --git a/patterns/TemplateMethod.java b/patterns/TemplateMethod.java index d69c8763..4a98f497 100644 --- a/patterns/TemplateMethod.java +++ b/patterns/TemplateMethod.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple demonstration of Template Method. +// Simple demonstration of Template Method import java.util.stream.*; abstract class ApplicationFramework { @@ -31,7 +31,7 @@ class MyApp extends ApplicationFramework { } public class TemplateMethod { - public static void main(String args[]) { + public static void main(String[] args) { new MyApp(); } } diff --git a/patterns/absfactory/GameEnvironment.java b/patterns/absfactory/GameEnvironment.java index 15e9ff1c..f6fdf378 100644 --- a/patterns/absfactory/GameEnvironment.java +++ b/patterns/absfactory/GameEnvironment.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://mindviewinc.com/Books/OnJava/ for more book information. -// An example of the Abstract Factory pattern. +// An example of the Abstract Factory pattern package patterns.absfactory; import java.util.function.*; @@ -78,7 +78,7 @@ public class GameEnvironment { public void play() { p.interactWith(ob); } - public static void main(String args[]) { + public static void main(String[] args) { GameElementFactory kp = new KittiesAndPuzzles(), kd = new KillAndDismember(); diff --git a/patterns/adapt/Adapter.java b/patterns/adapt/Adapter.java index bfab0281..3ff1bc3c 100644 --- a/patterns/adapt/Adapter.java +++ b/patterns/adapt/Adapter.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://mindviewinc.com/Books/OnJava/ for more book information. -// Variations on the Adapter pattern. +// Variations on the Adapter pattern package patterns.adapt; class WhatIHave { @@ -66,7 +66,7 @@ class WhatIHave3 extends WhatIHave { } public class Adapter { - public static void main(String args[]) { + public static void main(String[] args) { WhatIUse whatIUse = new WhatIUse(); WhatIHave whatIHave = new WhatIHave(); WhatIWant adapt= new ProxyAdapter(whatIHave); diff --git a/patterns/chain/ChainOfResponsibility.java b/patterns/chain/ChainOfResponsibility.java index c17c532a..fe1b1666 100644 --- a/patterns/chain/ChainOfResponsibility.java +++ b/patterns/chain/ChainOfResponsibility.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using the Functional interface. +// Using the Functional interface package patterns.chain; import java.util.*; import java.util.function.*; @@ -68,7 +68,7 @@ class FindMinima { } public class ChainOfResponsibility { - public static void main(String args[]) { + public static void main(String[] args) { FindMinima solver = new FindMinima(); List line = Arrays.asList( 1.0, 2.0, 1.0, 2.0, -1.0, diff --git a/patterns/doubledispatch/Aluminum.java b/patterns/doubledispatch/Aluminum.java index 2ac8e556..75d9e724 100644 --- a/patterns/doubledispatch/Aluminum.java +++ b/patterns/doubledispatch/Aluminum.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://mindviewinc.com/Books/OnJava/ for more book information. -// Aluminum for double dispatching. +// Aluminum for double dispatching package patterns.doubledispatch; import patterns.trash.*; import java.util.*; diff --git a/patterns/doubledispatch/Cardboard.java b/patterns/doubledispatch/Cardboard.java index 3868cb77..90008eda 100644 --- a/patterns/doubledispatch/Cardboard.java +++ b/patterns/doubledispatch/Cardboard.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://mindviewinc.com/Books/OnJava/ for more book information. -// Cardboard for double dispatching. +// Cardboard for double dispatching package patterns.doubledispatch; import patterns.trash.*; import java.util.*; diff --git a/patterns/doubledispatch/DoubleDispatch.java b/patterns/doubledispatch/DoubleDispatch.java index b31a4ae2..dd88cf11 100644 --- a/patterns/doubledispatch/DoubleDispatch.java +++ b/patterns/doubledispatch/DoubleDispatch.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using multiple dispatching to handle more -// than one unknown type during a method call. +// than one unknown type during a method call package patterns.doubledispatch; import patterns.trash.*; import java.util.*; diff --git a/patterns/doubledispatch/Glass.java b/patterns/doubledispatch/Glass.java index 4d10c94e..780aeb79 100644 --- a/patterns/doubledispatch/Glass.java +++ b/patterns/doubledispatch/Glass.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://mindviewinc.com/Books/OnJava/ for more book information. -// Glass for double dispatching. +// Glass for double dispatching package patterns.doubledispatch; import patterns.trash.*; import java.util.*; diff --git a/patterns/doubledispatch/Paper.java b/patterns/doubledispatch/Paper.java index 9a19bf03..befca756 100644 --- a/patterns/doubledispatch/Paper.java +++ b/patterns/doubledispatch/Paper.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://mindviewinc.com/Books/OnJava/ for more book information. -// Paper for double dispatching. +// Paper for double dispatching package patterns.doubledispatch; import patterns.trash.*; import java.util.*; diff --git a/patterns/doubledispatch/TypedBin.java b/patterns/doubledispatch/TypedBin.java index 4f6274c2..887e0663 100644 --- a/patterns/doubledispatch/TypedBin.java +++ b/patterns/doubledispatch/TypedBin.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://mindviewinc.com/Books/OnJava/ for more book information. -// A List that can grab the right type. +// A List that can grab the right type package patterns.doubledispatch; import patterns.trash.*; import java.util.*; diff --git a/patterns/doubledispatch/TypedBinMember.java b/patterns/doubledispatch/TypedBinMember.java index 893a2835..a34d6806 100644 --- a/patterns/doubledispatch/TypedBinMember.java +++ b/patterns/doubledispatch/TypedBinMember.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // An interface for adding the double dispatching // method to the trash hierarchy without -// modifying the original hierarchy. +// modifying the original hierarchy package patterns.doubledispatch; import java.util.*; diff --git a/patterns/factory/ShapeFactory1.java b/patterns/factory/ShapeFactory1.java index 7b5dbabf..81e6844c 100644 --- a/patterns/factory/ShapeFactory1.java +++ b/patterns/factory/ShapeFactory1.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://mindviewinc.com/Books/OnJava/ for more book information. -// A simple static factory method. +// A simple static factory method package patterns.factory; import java.util.*; import java.util.stream.*; @@ -52,7 +52,7 @@ class Square extends Shape { } public class ShapeFactory1 { - public static void main(String args[]) { + public static void main(String[] args) { List shapes = Stream.of( "Circle", "Square", "Square", "Circle", diff --git a/patterns/observer/ObservedFlower.java b/patterns/observer/ObservedFlower.java index 13879be5..bc89ac39 100644 --- a/patterns/observer/ObservedFlower.java +++ b/patterns/observer/ObservedFlower.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of "Observer" pattern. +// Demonstration of "Observer" pattern package patterns.observer; import java.util.*; @@ -75,7 +75,7 @@ class Hummingbird { } public class ObservedFlower { - public static void main(String args[]) { + public static void main(String[] args) { Flower f = new Flower(); Bee ba = new Bee("A"), diff --git a/patterns/recyclea/RecycleA.java b/patterns/recyclea/RecycleA.java index 12deee23..fb07cb41 100644 --- a/patterns/recyclea/RecycleA.java +++ b/patterns/recyclea/RecycleA.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://mindviewinc.com/Books/OnJava/ for more book information. -// Recycling with RTTI. +// Recycling with RTTI package patterns.recyclea; import java.util.*; import java.util.function.*; @@ -65,7 +65,7 @@ class TrashFactory { Arrays.asList( Aluminum::new, Paper::new, Glass::new); final static int sz = ttypes.size(); - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); public static Trash newTrash() { return ttypes .get(rand.nextInt(sz)) diff --git a/patterns/recyclec/RecycleC.java b/patterns/recyclec/RecycleC.java index f55ff27b..b3969fee 100644 --- a/patterns/recyclec/RecycleC.java +++ b/patterns/recyclec/RecycleC.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://mindviewinc.com/Books/OnJava/ for more book information. -// Adding more objects to the recycling problem. +// Adding more objects to the recycling problem package patterns.recyclec; import patterns.trash.*; import java.util.*; diff --git a/patterns/state/StateMachineDemo.java b/patterns/state/StateMachineDemo.java index 4b0cb87a..fc113368 100644 --- a/patterns/state/StateMachineDemo.java +++ b/patterns/state/StateMachineDemo.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates StateMachine pattern -// and Template method. +// The StateMachine pattern and Template method package patterns.state; interface State { @@ -73,7 +72,7 @@ class Washer extends StateMachine { } public class StateMachineDemo { - public static void main(String args[]) { + public static void main(String[] args) { new Washer(); } } diff --git a/patterns/strategy/StrategyPattern.java b/patterns/strategy/StrategyPattern.java index 305d0415..74264f62 100644 --- a/patterns/strategy/StrategyPattern.java +++ b/patterns/strategy/StrategyPattern.java @@ -46,7 +46,7 @@ class MinimaSolver { } public class StrategyPattern { - public static void main(String args[]) { + public static void main(String[] args) { MinimaSolver solver = new MinimaSolver(new LeastSquares()); List line = Arrays.asList( diff --git a/patterns/strategy/StrategyPattern2.java b/patterns/strategy/StrategyPattern2.java index 04d128d7..fca09e50 100644 --- a/patterns/strategy/StrategyPattern2.java +++ b/patterns/strategy/StrategyPattern2.java @@ -26,7 +26,7 @@ class FindMinima2 { } public class StrategyPattern2 { - public static void main(String args[]) { + public static void main(String[] args) { FindMinima2 solver = new FindMinima2(); List line = Arrays.asList( 1.0, 2.0, 1.0, 2.0, -1.0, diff --git a/patterns/trash/Fillable.java b/patterns/trash/Fillable.java index 14fe32ff..f012fe0a 100644 --- a/patterns/trash/Fillable.java +++ b/patterns/trash/Fillable.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://mindviewinc.com/Books/OnJava/ for more book information. -// Any object that can be filled with Trash. +// Any object that can be filled with Trash package patterns.trash; public interface Fillable { diff --git a/patterns/trash/FillableList.java b/patterns/trash/FillableList.java index 748a499a..44822abc 100644 --- a/patterns/trash/FillableList.java +++ b/patterns/trash/FillableList.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://mindviewinc.com/Books/OnJava/ for more book information. -// Adapter that makes a List Fillable. +// Adapter that makes a List Fillable package patterns.trash; import java.util.*; diff --git a/patterns/trash/ParseTrash.java b/patterns/trash/ParseTrash.java index 88f38896..69cff807 100644 --- a/patterns/trash/ParseTrash.java +++ b/patterns/trash/ParseTrash.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Open a file and parse its contents into -// Trash objects, placing each into a List. +// Trash objects, placing each into a List package patterns.trash; import java.util.*; import java.util.stream.*; diff --git a/patterns/trash/Trash.java b/patterns/trash/Trash.java index b8e188a9..4ecaaf1f 100644 --- a/patterns/trash/Trash.java +++ b/patterns/trash/Trash.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://mindviewinc.com/Books/OnJava/ for more book information. -// Base class for Trash recycling examples. +// Base class for Trash recycling examples package patterns.trash; import java.util.*; import java.lang.reflect.*; diff --git a/patterns/trashvisitor/Aluminum.java b/patterns/trashvisitor/Aluminum.java index 5d55b3fb..f2444f22 100644 --- a/patterns/trashvisitor/Aluminum.java +++ b/patterns/trashvisitor/Aluminum.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://mindviewinc.com/Books/OnJava/ for more book information. -// Aluminum for the visitor pattern. +// Aluminum for the visitor pattern package patterns.trashvisitor; import patterns.trash.*; diff --git a/patterns/trashvisitor/Cardboard.java b/patterns/trashvisitor/Cardboard.java index c6c46c3d..815e3b95 100644 --- a/patterns/trashvisitor/Cardboard.java +++ b/patterns/trashvisitor/Cardboard.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://mindviewinc.com/Books/OnJava/ for more book information. -// Cardboard for the visitor pattern. +// Cardboard for the visitor pattern package patterns.trashvisitor; import patterns.trash.*; diff --git a/patterns/trashvisitor/Glass.java b/patterns/trashvisitor/Glass.java index 8ec2904c..85b77a41 100644 --- a/patterns/trashvisitor/Glass.java +++ b/patterns/trashvisitor/Glass.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://mindviewinc.com/Books/OnJava/ for more book information. -// Glass for the visitor pattern. +// Glass for the visitor pattern package patterns.trashvisitor; import patterns.trash.*; diff --git a/patterns/trashvisitor/Paper.java b/patterns/trashvisitor/Paper.java index 1d80c6ee..89147823 100644 --- a/patterns/trashvisitor/Paper.java +++ b/patterns/trashvisitor/Paper.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://mindviewinc.com/Books/OnJava/ for more book information. -// Paper for the visitor pattern. +// Paper for the visitor pattern package patterns.trashvisitor; import patterns.trash.*; diff --git a/patterns/trashvisitor/Visitable.java b/patterns/trashvisitor/Visitable.java index afa54fbc..b32d9b38 100644 --- a/patterns/trashvisitor/Visitable.java +++ b/patterns/trashvisitor/Visitable.java @@ -2,9 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// An interface to add visitor functionality to -// the Trash hierarchy without modifying the -// base class. +// An interface to add visitor functionality to the +// Trash hierarchy without modifying the base class package patterns.trashvisitor; interface Visitable { diff --git a/patterns/trashvisitor/Visitor.java b/patterns/trashvisitor/Visitor.java index bb4bf07b..9344a8c1 100644 --- a/patterns/trashvisitor/Visitor.java +++ b/patterns/trashvisitor/Visitor.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://mindviewinc.com/Books/OnJava/ for more book information. -// The base interface for visitors. +// The base interface for visitors package patterns.trashvisitor; interface Visitor { diff --git a/patterns/visitor/BeeAndFlowers.java b/patterns/visitor/BeeAndFlowers.java index 1d2667f2..a8a9acaf 100644 --- a/patterns/visitor/BeeAndFlowers.java +++ b/patterns/visitor/BeeAndFlowers.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of "visitor" pattern. +// Demonstration of "visitor" pattern package patterns.visitor; import java.util.*; import java.util.function.*; @@ -74,14 +74,14 @@ class FlowerFactory { Arrays.asList(Gladiolus::new, Renuculus::new, Chrysanthemum::new); final static int sz = flowers.size(); - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); public static Flower newFlower() { return flowers.get(rand.nextInt(sz)).get(); } } public class BeeAndFlowers { - public static void main(String args[]) { + public static void main(String[] args) { List flowers = Stream.generate(FlowerFactory::newFlower) .limit(10) diff --git a/patterns/visualobserver/BoxObserver.java b/patterns/visualobserver/BoxObserver.java index 32da3e98..4c2e32a9 100644 --- a/patterns/visualobserver/BoxObserver.java +++ b/patterns/visualobserver/BoxObserver.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Demonstration of Observer pattern using -// Java's built-in observer classes. +// Java's built-in observer classes // {TimeOut:4000} During testing package patterns.visualobserver; import javax.swing.*; diff --git a/polymorphism/FieldAccess.java b/polymorphism/FieldAccess.java index 07979b0f..9bbaa27c 100644 --- a/polymorphism/FieldAccess.java +++ b/polymorphism/FieldAccess.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://mindviewinc.com/Books/OnJava/ for more book information. -// Direct field access is determined at compile time. +// Direct field access is determined at compile time class Super { public int field = 0; diff --git a/polymorphism/Frog.java b/polymorphism/Frog.java index 76f1d90f..e29d037a 100644 --- a/polymorphism/Frog.java +++ b/polymorphism/Frog.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://mindviewinc.com/Books/OnJava/ for more book information. -// Cleanup and inheritance. +// Cleanup and inheritance package polymorphism; class Characteristic { diff --git a/polymorphism/PolyConstructors.java b/polymorphism/PolyConstructors.java index 4f1efa34..cfc432d4 100644 --- a/polymorphism/PolyConstructors.java +++ b/polymorphism/PolyConstructors.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Constructors and polymorphism -// don't produce what you might expect. +// don't produce what you might expect class Glyph { void draw() { System.out.println("Glyph.draw()"); } diff --git a/polymorphism/PrivateOverride.java b/polymorphism/PrivateOverride.java index 7677afb0..167b3fc1 100644 --- a/polymorphism/PrivateOverride.java +++ b/polymorphism/PrivateOverride.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://mindviewinc.com/Books/OnJava/ for more book information. -// Trying to override a private method. +// Trying to override a private method package polymorphism; public class PrivateOverride { diff --git a/polymorphism/PrivateOverride2.java b/polymorphism/PrivateOverride2.java new file mode 100644 index 00000000..a3d31fe0 --- /dev/null +++ b/polymorphism/PrivateOverride2.java @@ -0,0 +1,20 @@ +// polymorphism/PrivateOverride2.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// Detecting a mistaken override using @Override +// {CompileTimeError} (Won't compile) +package polymorphism; + +public class PrivateOverride2 { + private void f() { System.out.println("private f()"); } + public static void main(String[] args) { + PrivateOverride2 po = new Derived2(); + po.f(); + } +} + +class Derived2 extends PrivateOverride2 { + @Override + public void f() { System.out.println("public f()"); } +} diff --git a/polymorphism/RTTI.java b/polymorphism/RTTI.java index 0ce65e1b..9532abe3 100644 --- a/polymorphism/RTTI.java +++ b/polymorphism/RTTI.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://mindviewinc.com/Books/OnJava/ for more book information. -// Downcasting & Runtime type information (RTTI). +// Downcasting & Runtime type information (RTTI) // {ThrowsException} class Useful { diff --git a/polymorphism/ReferenceCounting.java b/polymorphism/ReferenceCounting.java index d40d23c7..093e0198 100644 --- a/polymorphism/ReferenceCounting.java +++ b/polymorphism/ReferenceCounting.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://mindviewinc.com/Books/OnJava/ for more book information. -// Cleaning up shared member objects. +// Cleaning up shared member objects class Shared { private int refcount = 0; @@ -17,7 +17,9 @@ class Shared { System.out.println("Disposing " + this); } @Override - public String toString() { return "Shared " + id; } + public String toString() { + return "Shared " + id; + } } class Composing { @@ -34,15 +36,21 @@ class Composing { shared.dispose(); } @Override - public String toString() { return "Composing " + id; } + public String toString() { + return "Composing " + id; + } } public class ReferenceCounting { public static void main(String[] args) { Shared shared = new Shared(); - Composing[] composing = { new Composing(shared), - new Composing(shared), new Composing(shared), - new Composing(shared), new Composing(shared) }; + Composing[] composing = { + new Composing(shared), + new Composing(shared), + new Composing(shared), + new Composing(shared), + new Composing(shared) + }; for(Composing c : composing) c.dispose(); } diff --git a/polymorphism/Sandwich.java b/polymorphism/Sandwich.java index ddd86f8a..987fbafe 100644 --- a/polymorphism/Sandwich.java +++ b/polymorphism/Sandwich.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://mindviewinc.com/Books/OnJava/ for more book information. -// Order of constructor calls. +// Order of constructor calls package polymorphism; class Meal { @@ -26,14 +26,18 @@ class Lunch extends Meal { } class PortableLunch extends Lunch { - PortableLunch() { System.out.println("PortableLunch()");} + PortableLunch() { + System.out.println("PortableLunch()"); + } } public class Sandwich extends PortableLunch { private Bread b = new Bread(); private Cheese c = new Cheese(); private Lettuce l = new Lettuce(); - public Sandwich() { System.out.println("Sandwich()"); } + public Sandwich() { + System.out.println("Sandwich()"); + } public static void main(String[] args) { new Sandwich(); } diff --git a/polymorphism/Shapes.java b/polymorphism/Shapes.java index cf854eed..2fb4dbd5 100644 --- a/polymorphism/Shapes.java +++ b/polymorphism/Shapes.java @@ -2,20 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Polymorphism in Java. +// Polymorphism in Java import polymorphism.shape.*; public class Shapes { - private static RandomShapeGenerator gen = - new RandomShapeGenerator(); public static void main(String[] args) { - Shape[] s = new Shape[9]; - // Fill up the array with shapes: - for(int i = 0; i < s.length; i++) - s[i] = gen.get(); + RandomShapes gen = new RandomShapes(); // Make polymorphic method calls: - for(Shape shp : s) - shp.draw(); + for(Shape shape : gen.array(9)) + shape.draw(); } } /* Output: diff --git a/polymorphism/StaticPolymorphism.java b/polymorphism/StaticPolymorphism.java index 7870fd2e..1822d0ec 100644 --- a/polymorphism/StaticPolymorphism.java +++ b/polymorphism/StaticPolymorphism.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://mindviewinc.com/Books/OnJava/ for more book information. -// Static methods are not polymorphic. +// Static methods are not polymorphic class StaticSuper { public static String staticGet() { diff --git a/polymorphism/Transmogrify.java b/polymorphism/Transmogrify.java index 877c3eb2..1fecf202 100644 --- a/polymorphism/Transmogrify.java +++ b/polymorphism/Transmogrify.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Dynamically changing the behavior of an object -// via composition (the "State" design pattern). +// via composition (the "State" design pattern) class Actor { public void act() {} @@ -11,12 +11,16 @@ class Actor { class HappyActor extends Actor { @Override - public void act() { System.out.println("HappyActor"); } + public void act() { + System.out.println("HappyActor"); + } } class SadActor extends Actor { @Override - public void act() { System.out.println("SadActor"); } + public void act() { + System.out.println("SadActor"); + } } class Stage { diff --git a/polymorphism/build.xml b/polymorphism/build.xml index 6e1f294d..5a425ef3 100644 --- a/polymorphism/build.xml +++ b/polymorphism/build.xml @@ -2,7 +2,7 @@ - + diff --git a/polymorphism/music/Music.java b/polymorphism/music/Music.java index a0afb860..fd6574ba 100644 --- a/polymorphism/music/Music.java +++ b/polymorphism/music/Music.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://mindviewinc.com/Books/OnJava/ for more book information. -// Inheritance & upcasting. +// Inheritance & upcasting package polymorphism.music; public class Music { diff --git a/polymorphism/music/Music2.java b/polymorphism/music/Music2.java index 57d09e10..2f718888 100644 --- a/polymorphism/music/Music2.java +++ b/polymorphism/music/Music2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Overloading instead of upcasting. +// Overloading instead of upcasting package polymorphism.music; class Stringed extends Instrument { diff --git a/polymorphism/music/Note.java b/polymorphism/music/Note.java index eafc55bd..72903e39 100644 --- a/polymorphism/music/Note.java +++ b/polymorphism/music/Note.java @@ -2,9 +2,9 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Notes to play on musical instruments. +// Notes to play on musical instruments package polymorphism.music; public enum Note { - MIDDLE_C, C_SHARP, B_FLAT; // Etc. + MIDDLE_C, C_SHARP, B_FLAT; // Etc. } diff --git a/polymorphism/music3/Music3.java b/polymorphism/music3/Music3.java index 8e1d33aa..eb6e0290 100644 --- a/polymorphism/music3/Music3.java +++ b/polymorphism/music3/Music3.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://mindviewinc.com/Books/OnJava/ for more book information. -// An extensible program. +// An extensible program package polymorphism.music3; import polymorphism.music.Note; diff --git a/polymorphism/shape/RandomShapeGenerator.java b/polymorphism/shape/RandomShapes.java similarity index 59% rename from polymorphism/shape/RandomShapeGenerator.java rename to polymorphism/shape/RandomShapes.java index fe1a8d71..47d94039 100644 --- a/polymorphism/shape/RandomShapeGenerator.java +++ b/polymorphism/shape/RandomShapes.java @@ -1,12 +1,12 @@ -// polymorphism/shape/RandomShapeGenerator.java +// polymorphism/shape/RandomShapes.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A "factory" that randomly creates shapes. +// A "factory" that randomly creates shapes package polymorphism.shape; import java.util.*; -public class RandomShapeGenerator { +public class RandomShapes { private Random rand = new Random(47); public Shape get() { switch(rand.nextInt(3)) { @@ -16,4 +16,11 @@ public class RandomShapeGenerator { case 2: return new Triangle(); } } + public Shape[] array(int sz) { + Shape[] shapes = new Shape[sz]; + // Fill up the array with shapes: + for(int i = 0; i < shapes.length; i++) + shapes[i] = get(); + return shapes; + } } diff --git a/preferences/PreferencesDemo.java b/preferences/PreferencesDemo.java index 5da0de85..0b05105a 100644 --- a/preferences/PreferencesDemo.java +++ b/preferences/PreferencesDemo.java @@ -5,7 +5,8 @@ import java.util.prefs.*; public class PreferencesDemo { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Preferences prefs = Preferences .userNodeForPackage(PreferencesDemo.class); prefs.put("Location", "Oz"); @@ -16,7 +17,8 @@ public class PreferencesDemo { usageCount++; prefs.putInt("UsageCount", usageCount); for(String key : prefs.keys()) - System.out.println(key + ": "+ prefs.get(key, null)); + System.out.println(key + ": " + + prefs.get(key, null)); // You must always provide a default value: System.out.println( "How many companions does Dorothy have? " + diff --git a/references/AddingClone.java b/references/AddingClone.java index e8b1d2ed..7fb3ba17 100644 --- a/references/AddingClone.java +++ b/references/AddingClone.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // You must go through a few gyrations -// to add cloning to your own class. +// to add cloning to your own class import java.util.*; class Int2 implements Cloneable { @@ -15,14 +15,12 @@ class Int2 implements Cloneable { return Integer.toString(i); } @Override - public Object clone() { - Object o = null; + public Int2 clone() { try { - o = super.clone(); + return (Int2)super.clone(); } catch(CloneNotSupportedException e) { - System.err.println("Int2 can't clone"); + throw new RuntimeException(e); } - return o; } } @@ -36,7 +34,7 @@ public class AddingClone { @SuppressWarnings("unchecked") public static void main(String[] args) { Int2 x = new Int2(10); - Int2 x2 = (Int2)x.clone(); + Int2 x2 = x.clone(); x2.increment(); System.out.println( "x = " + x + ", x2 = " + x2); @@ -51,7 +49,7 @@ public class AddingClone { (ArrayList)v.clone(); // Now clone each element: for(int i = 0; i < v.size(); i++) - v2.set(i, (Int2)v2.get(i).clone()); + v2.set(i, v2.get(i).clone()); // Increment all v2's elements: for(Int2 i2 : v2) i2.increment(); diff --git a/references/Alias1.java b/references/Alias1.java index 0824a222..a2211dc1 100644 --- a/references/Alias1.java +++ b/references/Alias1.java @@ -2,18 +2,18 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Aliasing two references to one object. +// Aliasing two references to one object public class Alias1 { private int i; public Alias1(int ii) { i = ii; } public static void main(String[] args) { Alias1 x = new Alias1(7); - Alias1 y = x; // Assign the reference + Alias1 y = x; // Assign the reference (1) System.out.println("x: " + x.i); System.out.println("y: " + y.i); System.out.println("Incrementing x"); - x.i++; + x.i++; // (2) System.out.println("x: " + x.i); System.out.println("y: " + y.i); } diff --git a/references/Alias2.java b/references/Alias2.java index 22b17e30..5a0494a2 100644 --- a/references/Alias2.java +++ b/references/Alias2.java @@ -2,12 +2,14 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Method calls implicitly alias their arguments. +// Method calls implicitly alias their arguments public class Alias2 { private int i; - public Alias2(int ii) { i = ii; } - public static void f(Alias2 reference) { reference.i++; } + public Alias2(int i) { this.i = i; } + public static void f(Alias2 reference) { + reference.i++; + } public static void main(String[] args) { Alias2 x = new Alias2(7); System.out.println("x: " + x.i); diff --git a/references/CheckCloneable.java b/references/CheckCloneable.java index c5697cbf..4571dcfe 100644 --- a/references/CheckCloneable.java +++ b/references/CheckCloneable.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://mindviewinc.com/Books/OnJava/ for more book information. -// Check to see if a reference can be cloned. +// Check to see if a reference can be cloned // Can't clone this -- doesn't override clone(): class Ordinary {} @@ -65,15 +65,14 @@ public class CheckCloneable { Ordinary x = null; if(ord instanceof Cloneable) { try { - x= (Ordinary)((IsCloneable)ord).clone(); + x = (Ordinary)((IsCloneable)ord).clone(); System.out.println("Cloned " + id); } catch(CloneNotSupportedException e) { System.out.println( "Could not clone " + id); } } else { - System.out.println( - "Doesn't implement Cloneable"); + System.out.println("Doesn't implement Cloneable"); } return x; } @@ -88,10 +87,10 @@ public class CheckCloneable { new ReallyNoMore(), }; Ordinary x = new Ordinary(); - // This won't compile; + // This won't compile because // clone() is protected in Object: //- x = (Ordinary)x.clone(); - // Checks first to see if a class + // Checks first to see if the class // implements Cloneable: for(Ordinary ord1 : ord) { tryToClone(ord1); diff --git a/references/Cloning.java b/references/CloneArrayList.java similarity index 84% rename from references/Cloning.java rename to references/CloneArrayList.java index 10dc7336..44209e8a 100644 --- a/references/Cloning.java +++ b/references/CloneArrayList.java @@ -1,9 +1,9 @@ -// references/Cloning.java +// references/CloneArrayList.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // The clone() operation works for only a few -// items in the standard Java library. +// items in the standard Java library import java.util.*; class Int { @@ -16,11 +16,11 @@ class Int { } } -public class Cloning { +public class CloneArrayList { public static void main(String[] args) { ArrayList v = new ArrayList<>(); - for(int i = 0; i < 10; i++ ) - v.add(new Int(i)); + for(int i = 0; i < 10; i++) + v.add(new Int(i)); System.out.println("v: " + v); @SuppressWarnings("unchecked") ArrayList v2 = (ArrayList)v.clone(); diff --git a/references/Compete.java b/references/Compete.java index 2e265ae4..e673b767 100644 --- a/references/Compete.java +++ b/references/Compete.java @@ -6,35 +6,33 @@ import java.io.*; class Thing1 implements Serializable {} class Thing2 implements Serializable { - Thing1 o1 = new Thing1(); + Thing1 t1 = new Thing1(); } class Thing3 implements Cloneable { @Override - public Object clone() { - Object o = null; + public Thing3 clone() { try { - o = super.clone(); + return (Thing3)super.clone(); } catch(CloneNotSupportedException e) { - System.err.println("Thing3 can't clone"); + throw new RuntimeException(e); } - return o; } } class Thing4 implements Cloneable { - private Thing3 o3 = new Thing3(); + private Thing3 t3 = new Thing3(); @Override - public Object clone() { - Thing4 o = null; + public Thing4 clone() { + Thing4 t4 = null; try { - o = (Thing4)super.clone(); + t4 = (Thing4)super.clone(); } catch(CloneNotSupportedException e) { - System.err.println("Thing4 can't clone"); + throw new RuntimeException(e); } // Clone the field, too: - o.o3 = (Thing3)o3.clone(); - return o; + t4.t3 = t3.clone(); + return t4; } } @@ -43,36 +41,39 @@ public class Compete { public static void main(String[] args) throws Exception { Thing2[] a = new Thing2[SIZE]; - for(int i = 0; i < a.length; i++) + for(int i = 0; i < SIZE; i++) a[i] = new Thing2(); Thing4[] b = new Thing4[SIZE]; - for(int i = 0; i < b.length; i++) + for(int i = 0; i < SIZE; i++) b[i] = new Thing4(); long t1 = System.currentTimeMillis(); - ByteArrayOutputStream buf = - new ByteArrayOutputStream(); - ObjectOutputStream o = - new ObjectOutputStream(buf); - for(Thing2 a1 : a) { - o.writeObject(a1); + try(ByteArrayOutputStream buf = + new ByteArrayOutputStream(); + ObjectOutputStream oos = + new ObjectOutputStream(buf)) { + for(Thing2 a1 : a) { + oos.writeObject(a1); + } + // Now get copies: + try(ObjectInputStream in = + new ObjectInputStream( + new ByteArrayInputStream( + buf.toByteArray()))) { + Thing2[] c = new Thing2[SIZE]; + for(int i = 0; i < SIZE; i++) + c[i] = (Thing2)in.readObject(); + } } - // Now get copies: - ObjectInputStream in = - new ObjectInputStream( - new ByteArrayInputStream( - buf.toByteArray())); - Thing2[] c = new Thing2[SIZE]; - for(int i = 0; i < c.length; i++) - c[i] = (Thing2)in.readObject(); long t2 = System.currentTimeMillis(); System.out.println( "Duplication via serialization: " + (t2 - t1) + " Milliseconds"); + // Now try cloning: t1 = System.currentTimeMillis(); Thing4[] d = new Thing4[SIZE]; - for(int i = 0; i < d.length; i++) - d[i] = (Thing4)b[i].clone(); + for(int i = 0; i < SIZE; i++) + d[i] = b[i].clone(); t2 = System.currentTimeMillis(); System.out.println( "Duplication via cloning: " + @@ -80,6 +81,6 @@ public class Compete { } } /* Output: -Duplication via serialization: 274 Milliseconds -Duplication via cloning: 21 Milliseconds +Duplication via serialization: 202 Milliseconds +Duplication via cloning: 17 Milliseconds */ diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java index 33a08483..3d910620 100644 --- a/references/CopyConstructor.java +++ b/references/CopyConstructor.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // A constructor to copy an object of the same -// type, as an attempt to create a local copy. +// type, as an attempt to create a local copy import java.lang.reflect.*; class FruitQualities { @@ -40,7 +40,7 @@ class Fruit { private FruitQualities fq; private int seeds; private Seed[] s; - public Fruit(FruitQualities q, int seedCount){ + public Fruit(FruitQualities q, int seedCount) { fq = q; seeds = seedCount; s = new Seed[seeds]; @@ -59,9 +59,9 @@ class Fruit { s[i] = new Seed(f.s[i]); // Other copy-construction activities... } - // To allow derived constructors (or other + // This allows derived constructors (or other // methods) to put in different qualities: - protected void addQualities(FruitQualities q){ + protected void addQualities(FruitQualities q) { fq = q; } protected FruitQualities getQualities() { @@ -112,12 +112,12 @@ class GreenZebra extends Tomato { public class CopyConstructor { public static void ripen(Tomato t) { // Use the "copy constructor": - t = new Tomato(t); + t = new Tomato(t); // (1) System.out.println("In ripen, t is a " + t.getClass().getName()); } public static void slice(Fruit f) { - f = new Fruit(f); // Hmmm... will this work? + f = new Fruit(f); // Hmmm... will this work? (2) System.out.println("In slice, f is a " + f.getClass().getName()); } diff --git a/references/DeepCopy.java b/references/DeepCopy.java index 24b9ebee..0976d6dc 100644 --- a/references/DeepCopy.java +++ b/references/DeepCopy.java @@ -2,8 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Cloning a composed object. -// (Install libraries from www.junit.org) +// Cloning a composed object +// (Install libraries from junit.org) import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -13,17 +13,15 @@ class DepthReading implements Cloneable { this.depth = depth; } @Override - public Object clone() { - Object o = null; + public DepthReading clone() { try { - o = super.clone(); + return (DepthReading)super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e); } - return o; } public double getDepth() { return depth; } - public void setDepth(double depth){ + public void setDepth(double depth) { this.depth = depth; } @Override @@ -35,19 +33,17 @@ class DepthReading implements Cloneable { class TemperatureReading implements Cloneable { private long time; private double temperature; - public TemperatureReading(double temperature){ + public TemperatureReading(double temperature) { time = System.currentTimeMillis(); this.temperature = temperature; } @Override - public Object clone() { - Object o = null; + public TemperatureReading clone() { try { - o = super.clone(); + return (TemperatureReading)super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e); } - return o; } public double getTemperature() { return temperature; @@ -70,26 +66,29 @@ class OceanReading implements Cloneable { depth = new DepthReading(ddata); } @Override - public Object clone() { - OceanReading o = null; + public OceanReading clone() { + OceanReading or = null; try { - o = (OceanReading)super.clone(); + or = (OceanReading)super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e); } // Must clone references: - o.depth = (DepthReading)o.depth.clone(); - o.temperature = - (TemperatureReading)o.temperature.clone(); - return o; // Upcasts back to Object + or.depth = (DepthReading)or.depth.clone(); + or.temperature = + (TemperatureReading)or.temperature.clone(); + return or; } public TemperatureReading getTemperatureReading() { return temperature; } - public void setTemperatureReading(TemperatureReading tr){ + public void + setTemperatureReading(TemperatureReading tr) { temperature = tr; } - public DepthReading getDepthReading() { return depth; } + public DepthReading getDepthReading() { + return depth; + } public void setDepthReading(DepthReading dr) { this.depth = dr; } @@ -106,8 +105,7 @@ public class DeepCopy { OceanReading reading = new OceanReading(33.9, 100.5); // Now clone it: - OceanReading clone = - (OceanReading)reading.clone(); + OceanReading clone = reading.clone(); TemperatureReading tr = clone.getTemperatureReading(); tr.setTemperature(tr.getTemperature() + 1); diff --git a/references/HorrorFlick.java b/references/HorrorFlick.java index 671616ad..b4ef52e1 100644 --- a/references/HorrorFlick.java +++ b/references/HorrorFlick.java @@ -2,20 +2,18 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// You can insert Cloneability -// at any level of inheritance. +// You can insert Cloneability at any level of inheritance class Person {} class Hero extends Person {} -class Scientist extends Person -implements Cloneable { - public Object clone() { +class Scientist extends Person implements Cloneable { + @Override + public Scientist clone() { try { - return super.clone(); + return (Scientist)super.clone(); } catch(CloneNotSupportedException e) { - // Should never happen; it's Cloneable: throw new RuntimeException(e); } } @@ -31,7 +29,7 @@ public class HorrorFlick { MadScientist m = new MadScientist(); //- p = (Person)p.clone(); // Compile error //- h = (Hero)h.clone(); // Compile error - s = (Scientist)s.clone(); + s = s.clone(); m = (MadScientist)m.clone(); } } diff --git a/references/Immutable1.java b/references/Immutable1.java index 35b88249..09680dbf 100644 --- a/references/Immutable1.java +++ b/references/Immutable1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Immutable objects are immune to aliasing. +// Immutable objects are immune to aliasing public class Immutable1 { private int data; diff --git a/references/ImmutableInteger.java b/references/ImmutableInteger.java index 73c3a1d1..cf5f544e 100644 --- a/references/ImmutableInteger.java +++ b/references/ImmutableInteger.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://mindviewinc.com/Books/OnJava/ for more book information. -// The Integer class cannot be changed. +// The Integer class cannot be changed import java.util.*; public class ImmutableInteger { diff --git a/references/ImmutableStrings.java b/references/ImmutableStrings.java index 7bb953ad..75127afd 100644 --- a/references/ImmutableStrings.java +++ b/references/ImmutableStrings.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrating StringBuffer. +// Demonstrating StringBuilder public class ImmutableStrings { public static void main(String[] args) { @@ -10,9 +10,9 @@ public class ImmutableStrings { String s = "abc" + foo + "def" + Integer.toString(47); System.out.println(s); - // The "equivalent" using StringBuffer: - StringBuffer sb = - new StringBuffer("abc"); // Creates String + // The "equivalent" using StringBuilder: + StringBuilder sb = + new StringBuilder("abc"); // Creates String sb.append(foo); sb.append("def"); // Creates String sb.append(Integer.toString(47)); diff --git a/references/LocalCopy.java b/references/LocalCopy.java deleted file mode 100644 index cb0464dd..00000000 --- a/references/LocalCopy.java +++ /dev/null @@ -1,57 +0,0 @@ -// references/LocalCopy.java -// (c)2016 MindView LLC: see Copyright.txt -// We make no guarantees that this code is fit for any purpose. -// Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Creating local copies with clone(). - -class MyObject implements Cloneable { - private int n; - public MyObject(int n) { this.n = n; } - @Override - public Object clone() { - Object o = null; - try { - o = super.clone(); - } catch(CloneNotSupportedException e) { - System.err.println("MyObject can't clone"); - } - return o; - } - public int getValue() { return n; } - public void setValue(int n) { this.n = n; } - public void increment() { n++; } - @Override - public String toString() { return Integer.toString(n); } -} - -public class LocalCopy { - public static MyObject g(MyObject v) { - // Passing a reference, modifies outside object: - v.increment(); - return v; - } - public static MyObject f(MyObject v) { - v = (MyObject)v.clone(); // Local copy - v.increment(); - return v; - } - public static void main(String[] args) { - MyObject a = new MyObject(11); - MyObject b = g(a); - // Reference equivalence, not object equivalence: - System.out.println("a == b: " + (a == b) + - "\na = " + a + "\nb = " + b); - MyObject c = new MyObject(47); - MyObject d = f(c); - System.out.println("c == d: " + (c == d) + - "\nc = " + c + "\nd = " + d); - } -} -/* Output: -a == b: true -a = 12 -b = 12 -c == d: false -c = 47 -d = 48 -*/ diff --git a/references/MutableInteger.java b/references/MutableInteger.java index 14afe89b..e28e0cf5 100644 --- a/references/MutableInteger.java +++ b/references/MutableInteger.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://mindviewinc.com/Books/OnJava/ for more book information. -// A changeable wrapper class. +// A changeable wrapper class import java.util.*; class IntValue { diff --git a/references/PassReferences.java b/references/PassReferences.java index 57cb8181..49348e2e 100644 --- a/references/PassReferences.java +++ b/references/PassReferences.java @@ -2,7 +2,6 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Passing references around. public class PassReferences { public static void f(PassReferences h) { diff --git a/references/SimplerMutableInteger.java b/references/SimplerMutableInteger.java new file mode 100644 index 00000000..68449965 --- /dev/null +++ b/references/SimplerMutableInteger.java @@ -0,0 +1,30 @@ +// references/SimplerMutableInteger.java +// (c)2016 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://mindviewinc.com/Books/OnJava/ for more book information. +// A trivial wrapper class +import java.util.*; + +class IntValue2 { + public int n; + public IntValue2(int n) { this.n = n; } +} + +public class SimplerMutableInteger { + public static void main(String[] args) { + List v = new ArrayList<>(); + for(int i = 0; i < 10; i++) + v.add(new IntValue2(i)); + for(IntValue2 i : v) + System.out.print(i.n + " "); + System.out.println(); + for(int i = 0; i < v.size(); i++) + v.get(i).n = v.get(i).n + 1; + for(IntValue2 i : v) + System.out.print(i.n + " "); + } +} +/* Output: +0 1 2 3 4 5 6 7 8 9 +1 2 3 4 5 6 7 8 9 10 +*/ diff --git a/references/Snake.java b/references/Snake.java index 680bb34a..b92c825c 100644 --- a/references/Snake.java +++ b/references/Snake.java @@ -2,8 +2,8 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Tests cloning to see if destination -// of references are also cloned. +// Tests cloning to see if reference +// destinations are also cloned public class Snake implements Cloneable { private Snake next; @@ -27,23 +27,20 @@ public class Snake implements Cloneable { return s; } @Override - public Object clone() { - Object o = null; + public Snake clone() { try { - o = super.clone(); + return (Snake)super.clone(); } catch(CloneNotSupportedException e) { - System.err.println("Snake can't clone"); + throw new RuntimeException(e); } - return o; } public static void main(String[] args) { Snake s = new Snake(5, 'a'); System.out.println("s = " + s); - Snake s2 = (Snake)s.clone(); + Snake s2 = s.clone(); System.out.println("s2 = " + s2); s.increment(); - System.out.println( - "after s.increment, s2 = " + s2); + System.out.println("after s.increment, s2 = " + s2); } } /* Output: diff --git a/references/build.xml b/references/build.xml index e0733d4a..dde5d9ea 100644 --- a/references/build.xml +++ b/references/build.xml @@ -11,7 +11,7 @@ - + @@ -20,9 +20,9 @@ - + @@ -32,7 +32,7 @@ - + @@ -41,9 +41,9 @@ - + diff --git a/remote/PerfectTimeImpl.java b/remote/PerfectTimeImpl.java index 0863f99d..8342b0c1 100644 --- a/remote/PerfectTimeImpl.java +++ b/remote/PerfectTimeImpl.java @@ -2,8 +2,7 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// The implementation of the PerfectTime -// remote object. +// Implementing the PerfectTime remote object import java.rmi.RemoteException; public class PerfectTimeImpl implements PerfectTime { diff --git a/remote/PerfectTimeServer.java b/remote/PerfectTimeServer.java index 9e2d6802..ec07c775 100644 --- a/remote/PerfectTimeServer.java +++ b/remote/PerfectTimeServer.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://mindviewinc.com/Books/OnJava/ for more book information. -// Server for the PerfectTime remote object. +// Server for the PerfectTime remote object // {ValidateByHand} import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; @@ -10,8 +10,8 @@ import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class PerfectTimeServer { - public static - void main(String[] args) throws RemoteException { + public static void + main(String[] args) throws RemoteException { PerfectTimeImpl pt = new PerfectTimeImpl(); PerfectTime stub = (PerfectTime) UnicastRemoteObject.exportObject(pt, 0); diff --git a/reuse/Bath.java b/reuse/Bath.java index 9d9204a2..3266f8de 100644 --- a/reuse/Bath.java +++ b/reuse/Bath.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://mindviewinc.com/Books/OnJava/ for more book information. -// Constructor initialization with composition. +// Constructor initialization with composition class Soap { private String s; diff --git a/reuse/Beetle.java b/reuse/Beetle.java index 4dbc423a..15dc2ceb 100644 --- a/reuse/Beetle.java +++ b/reuse/Beetle.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://mindviewinc.com/Books/OnJava/ for more book information. -// The full process of initialization. +// The full process of initialization class Insect { private int i = 9; diff --git a/reuse/BlankFinal.java b/reuse/BlankFinal.java index d2ddc8ef..24e5a576 100644 --- a/reuse/BlankFinal.java +++ b/reuse/BlankFinal.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://mindviewinc.com/Books/OnJava/ for more book information. -// "Blank" final fields. +// "Blank" final fields class Poppet { private int i; diff --git a/reuse/CADSystem.java b/reuse/CADSystem.java index a776f8a3..2cd10f74 100644 --- a/reuse/CADSystem.java +++ b/reuse/CADSystem.java @@ -2,12 +2,16 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Ensuring proper cleanup. +// Ensuring proper cleanup package reuse; class Shape { - Shape(int i) { System.out.println("Shape constructor"); } - void dispose() { System.out.println("Shape dispose"); } + Shape(int i) { + System.out.println("Shape constructor"); + } + void dispose() { + System.out.println("Shape dispose"); + } } class Circle extends Shape { diff --git a/reuse/Car.java b/reuse/Car.java index 716d08f0..20e0bbe2 100644 --- a/reuse/Car.java +++ b/reuse/Car.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://mindviewinc.com/Books/OnJava/ for more book information. -// Composition with public objects. +// Composition with public objects class Engine { public void start() {} diff --git a/reuse/Cartoon.java b/reuse/Cartoon.java index ff2e864a..77a92406 100644 --- a/reuse/Cartoon.java +++ b/reuse/Cartoon.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://mindviewinc.com/Books/OnJava/ for more book information. -// Constructor calls during inheritance. +// Constructor calls during inheritance class Art { Art() { diff --git a/reuse/Chess.java b/reuse/Chess.java index a4bfaa60..ec3cdb75 100644 --- a/reuse/Chess.java +++ b/reuse/Chess.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://mindviewinc.com/Books/OnJava/ for more book information. -// Inheritance, constructors and arguments. +// Inheritance, constructors and arguments class Game { Game(int i) { diff --git a/reuse/Detergent.java b/reuse/Detergent.java index 99e07f73..367315bd 100644 --- a/reuse/Detergent.java +++ b/reuse/Detergent.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://mindviewinc.com/Books/OnJava/ for more book information. -// Inheritance syntax & properties. +// Inheritance syntax & properties class Cleanser { private String s = "Cleanser"; diff --git a/reuse/FinalArguments.java b/reuse/FinalArguments.java index 6721f59f..b648de4d 100644 --- a/reuse/FinalArguments.java +++ b/reuse/FinalArguments.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using "final" with method arguments. +// Using "final" with method arguments class Gizmo { public void spin() {} diff --git a/reuse/FinalData.java b/reuse/FinalData.java index 2cbf0f77..40a7895c 100644 --- a/reuse/FinalData.java +++ b/reuse/FinalData.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://mindviewinc.com/Books/OnJava/ for more book information. -// The effect of final on fields. +// The effect of final on fields import java.util.*; class Value { @@ -29,7 +29,8 @@ public class FinalData { private final int[] a = { 1, 2, 3, 4, 5, 6 }; @Override public String toString() { - return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5; + return id + ": " + "i4 = " + i4 + + ", INT_5 = " + INT_5; } public static void main(String[] args) { FinalData fd1 = new FinalData("fd1"); diff --git a/reuse/FinalOverridingIllusion.java b/reuse/FinalOverridingIllusion.java index dbd91996..15ef7e9c 100644 --- a/reuse/FinalOverridingIllusion.java +++ b/reuse/FinalOverridingIllusion.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // It only looks like you can override -// a private or private final method. +// a private or private final method class WithFinals { // Identical to "private" alone: diff --git a/reuse/Hide.java b/reuse/Hide.java index 389bcc02..878c0f28 100644 --- a/reuse/Hide.java +++ b/reuse/Hide.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Overloading a base-class method name in a derived -// class does not hide the base-class versions. +// class does not hide the base-class versions class Homer { char doh(char c) { diff --git a/reuse/Jurassic.java b/reuse/Jurassic.java index 3a576149..1b965026 100644 --- a/reuse/Jurassic.java +++ b/reuse/Jurassic.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://mindviewinc.com/Books/OnJava/ for more book information. -// Making an entire class final. +// Making an entire class final class SmallBrain {} diff --git a/reuse/Orc.java b/reuse/Orc.java index b3f6cc79..14376a48 100644 --- a/reuse/Orc.java +++ b/reuse/Orc.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://mindviewinc.com/Books/OnJava/ for more book information. -// The protected keyword. +// The protected keyword class Villain { private String name; diff --git a/reuse/PlaceSetting.java b/reuse/PlaceSetting.java index 41dad884..9f443976 100644 --- a/reuse/PlaceSetting.java +++ b/reuse/PlaceSetting.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://mindviewinc.com/Books/OnJava/ for more book information. -// Combining composition & inheritance. +// Combining composition & inheritance class Plate { Plate(int i) { diff --git a/reuse/SprinklerSystem.java b/reuse/SprinklerSystem.java index 6c901bf8..d967f95e 100644 --- a/reuse/SprinklerSystem.java +++ b/reuse/SprinklerSystem.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://mindviewinc.com/Books/OnJava/ for more book information. -// Composition for code reuse. +// Composition for code reuse class WaterSource { private String s; @@ -27,7 +27,7 @@ public class SprinklerSystem { "valve3 = " + valve3 + " " + "valve4 = " + valve4 + "\n" + "i = " + i + " " + "f = " + f + " " + - "source = " + source; + "source = " + source; // (1) } public static void main(String[] args) { SprinklerSystem sprinklers = new SprinklerSystem(); diff --git a/reuse/Wind.java b/reuse/Wind.java index 839ba8a4..49ff6e40 100644 --- a/reuse/Wind.java +++ b/reuse/Wind.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://mindviewinc.com/Books/OnJava/ for more book information. -// Inheritance & upcasting. +// Inheritance & upcasting class Instrument { public void play() {} diff --git a/serialization/APerson.java b/serialization/APerson.java index 757f606f..930b5a4a 100644 --- a/serialization/APerson.java +++ b/serialization/APerson.java @@ -26,23 +26,27 @@ public class APerson { person.appendChild(lastName); return person; } - // Constructor to restore a APerson from an XML Element: + // Constructor restores a APerson from an XML Element: public APerson(Element person) { - first= person.getFirstChildElement("first").getValue(); - last = person.getFirstChildElement("last").getValue(); + first = + person.getFirstChildElement("first").getValue(); + last = + person.getFirstChildElement("last").getValue(); } @Override public String toString() { return first + " " + last; } // Make it human-readable: public static void format(OutputStream os, Document doc) throws Exception { - Serializer serializer= new Serializer(os,"ISO-8859-1"); + Serializer serializer = + new Serializer(os,"ISO-8859-1"); serializer.setIndent(4); serializer.setMaxLength(60); serializer.write(doc); serializer.flush(); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { List people = Arrays.asList( new APerson("Dr. Bunsen", "Honeydew"), new APerson("Gonzo", "The Great"), @@ -53,8 +57,8 @@ public class APerson { root.appendChild(p.getXML()); Document doc = new Document(root); format(System.out, doc); - format(new BufferedOutputStream(new FileOutputStream( - "People.xml")), doc); + format(new BufferedOutputStream( + new FileOutputStream("People.xml")), doc); } } /* Output: diff --git a/serialization/AStoreCADState.java b/serialization/AStoreCADState.java index 5a23b0b5..afcc799d 100644 --- a/serialization/AStoreCADState.java +++ b/serialization/AStoreCADState.java @@ -2,14 +2,14 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Saving the state of a pretend CAD system. +// Saving the state of a fictitious CAD system import java.io.*; import java.util.*; abstract class Shape implements Serializable { public static final int RED = 1, BLUE = 2, GREEN = 3; private int xPos, yPos, dimension; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); private static int counter = 0; public abstract void setColor(int newColor); public abstract int getColor(); @@ -71,7 +71,8 @@ class Line extends Shape { } public class AStoreCADState { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { List> shapeTypes = new ArrayList<>(); // Add references to the class objects: @@ -86,11 +87,13 @@ public class AStoreCADState { for(int i = 0; i < 10; i++) ((Shape)shapes.get(i)).setColor(Shape.GREEN); // Save the state vector: - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("CADState.dat")); - out.writeObject(shapeTypes); - Line.serializeStaticState(out); - out.writeObject(shapes); + try(ObjectOutputStream out = + new ObjectOutputStream( + new FileOutputStream("CADState.dat"))) { + out.writeObject(shapeTypes); + Line.serializeStaticState(out); + out.writeObject(shapes); + } // Display the shapes: System.out.println(shapes); } diff --git a/serialization/Alien.java b/serialization/Alien.java index cd2988cb..ce07a405 100644 --- a/serialization/Alien.java +++ b/serialization/Alien.java @@ -2,6 +2,6 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A serializable class. +// A serializable class import java.io.*; public class Alien implements Serializable {} diff --git a/serialization/Blip3.java b/serialization/Blip3.java index 59e63169..7e13b58b 100644 --- a/serialization/Blip3.java +++ b/serialization/Blip3.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://mindviewinc.com/Books/OnJava/ for more book information. -// Reconstructing an externalizable object. +// Reconstructing an externalizable object import java.io.*; public class Blip3 implements Externalizable { @@ -36,8 +36,9 @@ public class Blip3 implements Externalizable { s = (String)in.readObject(); i = in.readInt(); } - public static void main(String[] args) - throws IOException, ClassNotFoundException { + public static void + main(String[] args) throws IOException, + ClassNotFoundException { System.out.println("Constructing objects:"); Blip3 b3 = new Blip3("A String ", 47); System.out.println(b3); diff --git a/serialization/Blips.java b/serialization/Blips.java index 4862c088..4e81ca34 100644 --- a/serialization/Blips.java +++ b/serialization/Blips.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://mindviewinc.com/Books/OnJava/ for more book information. -// Simple use of Externalizable & a pitfall. +// Simple use of Externalizable & a pitfall import java.io.*; class Blip1 implements Externalizable { @@ -38,8 +38,9 @@ class Blip2 implements Externalizable { } public class Blips { - public static void main(String[] args) - throws IOException, ClassNotFoundException { + public static void + main(String[] args) throws IOException, + ClassNotFoundException { System.out.println("Constructing objects:"); Blip1 b1 = new Blip1(); Blip2 b2 = new Blip2(); diff --git a/serialization/FreezeAlien.java b/serialization/FreezeAlien.java index 379a743a..cb2ae019 100644 --- a/serialization/FreezeAlien.java +++ b/serialization/FreezeAlien.java @@ -2,11 +2,12 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Create a serialized output file. +// Create a serialized output file import java.io.*; public class FreezeAlien { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { ObjectOutput out = new ObjectOutputStream( new FileOutputStream("X.file")); Alien quellek = new Alien(); diff --git a/serialization/Logon.java b/serialization/Logon.java index 6bf62350..5987b773 100644 --- a/serialization/Logon.java +++ b/serialization/Logon.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the "transient" keyword. +// Demonstrates the "transient" keyword import java.util.concurrent.*; import java.io.*; import java.util.*; @@ -20,11 +20,12 @@ public class Logon implements Serializable { return "logon info: \n username: " + username + "\n date: " + date + "\n password: " + password; } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Logon a = new Logon("Hulk", "myLittlePony"); System.out.println("logon a = " + a); try(ObjectOutputStream o = new ObjectOutputStream( - new FileOutputStream("Logon.dat"))) { + new FileOutputStream("Logon.dat"))) { o.writeObject(a); } TimeUnit.SECONDS.sleep(1); // Delay diff --git a/serialization/MyWorld.java b/serialization/MyWorld.java index db4e47be..d42f4ff5 100644 --- a/serialization/MyWorld.java +++ b/serialization/MyWorld.java @@ -22,36 +22,46 @@ class Animal implements Serializable { } public class MyWorld { - public static void main(String[] args) - throws IOException, ClassNotFoundException { + public static void + main(String[] args) throws IOException, + ClassNotFoundException { House house = new House(); List animals = new ArrayList<>(); animals.add(new Animal("Bosco the dog", house)); animals.add(new Animal("Ralph the hamster", house)); animals.add(new Animal("Molly the cat", house)); System.out.println("animals: " + animals); - ByteArrayOutputStream buf1 = - new ByteArrayOutputStream(); - ObjectOutputStream o1 = new ObjectOutputStream(buf1); - o1.writeObject(animals); - o1.writeObject(animals); // Write a 2nd set - // Write to a different stream: - ByteArrayOutputStream buf2 = - new ByteArrayOutputStream(); - ObjectOutputStream o2 = new ObjectOutputStream(buf2); - o2.writeObject(animals); - // Now get them back: - ObjectInputStream in1 = new ObjectInputStream( - new ByteArrayInputStream(buf1.toByteArray())); - ObjectInputStream in2 = new ObjectInputStream( - new ByteArrayInputStream(buf2.toByteArray())); - List - animals1 = (List)in1.readObject(), - animals2 = (List)in1.readObject(), - animals3 = (List)in2.readObject(); - System.out.println("animals1: " + animals1); - System.out.println("animals2: " + animals2); - System.out.println("animals3: " + animals3); + try(ByteArrayOutputStream buf1 = + new ByteArrayOutputStream(); + ObjectOutputStream o1 = + new ObjectOutputStream(buf1)) { + o1.writeObject(animals); + o1.writeObject(animals); // Write a 2nd set + // Write to a different stream: + try(ByteArrayOutputStream buf2 = + new ByteArrayOutputStream(); + ObjectOutputStream o2 = + new ObjectOutputStream(buf2)) { + o2.writeObject(animals); + // Now get them back: + try(ObjectInputStream in1 = + new ObjectInputStream( + new ByteArrayInputStream( + buf1.toByteArray())); + ObjectInputStream in2 = + new ObjectInputStream( + new ByteArrayInputStream( + buf2.toByteArray()))) { + List + animals1 = (List)in1.readObject(), + animals2 = (List)in1.readObject(), + animals3 = (List)in2.readObject(); + System.out.println("animals1: " + animals1); + System.out.println("animals2: " + animals2); + System.out.println("animals3: " + animals3); + } + } + } } } /* Output: diff --git a/serialization/People.java b/serialization/People.java index 1aee36ce..5a7a7fa1 100644 --- a/serialization/People.java +++ b/serialization/People.java @@ -11,13 +11,15 @@ import java.util.*; public class People extends ArrayList { public People(String fileName) throws Exception { - Document doc = new Builder().build(new File(fileName)); + Document doc = + new Builder().build(new File(fileName)); Elements elements = doc.getRootElement().getChildElements(); for(int i = 0; i < elements.size(); i++) add(new APerson(elements.get(i))); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { People p = new People("People.xml"); System.out.println(p); } diff --git a/serialization/RecoverCADState.java b/serialization/RecoverCADState.java index ad416cd2..e23d0bca 100644 --- a/serialization/RecoverCADState.java +++ b/serialization/RecoverCADState.java @@ -2,22 +2,25 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Restoring the state of the pretend CAD system. +// Restoring the state of the fictitious CAD system // {RunFirst: AStoreCADState} import java.io.*; import java.util.*; public class RecoverCADState { @SuppressWarnings("unchecked") - public static void main(String[] args) throws Exception { - ObjectInputStream in = new ObjectInputStream( - new FileInputStream("CADState.dat")); - // Read in the same order they were written: - List> shapeTypes = - (List>)in.readObject(); - Line.deserializeStaticState(in); - List shapes = (List)in.readObject(); - System.out.println(shapes); + public static void + main(String[] args) throws Exception { + try(ObjectInputStream in = + new ObjectInputStream( + new FileInputStream("CADState.dat"))) { + // Read in the same order they were written: + List> shapeTypes = + (List>)in.readObject(); + Line.deserializeStaticState(in); + List shapes = (List)in.readObject(); + System.out.println(shapes); + } } } /* Output: diff --git a/serialization/SerialCtl.java b/serialization/SerialCtl.java index 234dc5d1..19867628 100644 --- a/serialization/SerialCtl.java +++ b/serialization/SerialCtl.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Controlling serialization by adding your own -// writeObject() and readObject() methods. +// writeObject() and readObject() methods import java.io.*; public class SerialCtl implements Serializable { @@ -25,11 +25,13 @@ public class SerialCtl implements Serializable { stream.defaultReadObject(); b = (String)stream.readObject(); } - public static void main(String[] args) - throws IOException, ClassNotFoundException { + public static void + main(String[] args) throws IOException, + ClassNotFoundException { SerialCtl sc = new SerialCtl("Test1", "Test2"); System.out.println("Before:\n" + sc); - ByteArrayOutputStream buf= new ByteArrayOutputStream(); + ByteArrayOutputStream buf = + new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(buf); o.writeObject(sc); // Now get it back: diff --git a/serialization/Worm.java b/serialization/Worm.java index 5a316d7b..0b3d949f 100644 --- a/serialization/Worm.java +++ b/serialization/Worm.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates object serialization. +// Demonstrates object serialization import java.io.*; import java.util.*; @@ -10,11 +10,13 @@ class Data implements Serializable { private int n; public Data(int n) { this.n = n; } @Override - public String toString() { return Integer.toString(n); } + public String toString() { + return Integer.toString(n); + } } public class Worm implements Serializable { - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); private Data[] d = { new Data(rand.nextInt(10)), new Data(rand.nextInt(10)), @@ -44,8 +46,9 @@ public class Worm implements Serializable { result.append(next); return result.toString(); } - public static void main(String[] args) - throws ClassNotFoundException, IOException { + public static void + main(String[] args) throws ClassNotFoundException, + IOException { Worm w = new Worm(6, 'a'); System.out.println("w = " + w); try(ObjectOutputStream out = new ObjectOutputStream( @@ -67,7 +70,8 @@ public class Worm implements Serializable { out2.writeObject(w); out2.flush(); try(ObjectInputStream in2 = new ObjectInputStream( - new ByteArrayInputStream(bout.toByteArray()))) { + new ByteArrayInputStream( + bout.toByteArray()))) { String s = (String)in2.readObject(); Worm w3 = (Worm)in2.readObject(); System.out.println(s + "w3 = " + w3); diff --git a/serialization/xfiles/ThawAlien.java b/serialization/xfiles/ThawAlien.java index d11d6ce3..0032abde 100644 --- a/serialization/xfiles/ThawAlien.java +++ b/serialization/xfiles/ThawAlien.java @@ -7,7 +7,8 @@ package serialization.xfiles; import java.io.*; public class ThawAlien { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File("..", "X.file"))); Object mystery = in.readObject(); diff --git a/standardio/ChangeSystemOut.java b/standardio/ChangeSystemOut.java index 66e789a2..d3943605 100644 --- a/standardio/ChangeSystemOut.java +++ b/standardio/ChangeSystemOut.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://mindviewinc.com/Books/OnJava/ for more book information. -// Turn System.out into a PrintWriter. +// Turn System.out into a PrintWriter import java.io.*; public class ChangeSystemOut { diff --git a/standardio/Echo.java b/standardio/Echo.java index 5e3b4e07..c59ac07c 100644 --- a/standardio/Echo.java +++ b/standardio/Echo.java @@ -2,17 +2,18 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// How to read from standard input. +// How to read from standard input // {TimeOutDuringTesting} import java.io.*; public class Echo { - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); String s; - while((s = stdin.readLine()) != null && s.length()!= 0) + while((s=stdin.readLine()) != null && + s.length() != 0) System.out.println(s); // An empty line or Ctrl-Z terminates the program } diff --git a/standardio/OSExecuteDemo.java b/standardio/OSExecuteDemo.java index 273d605f..4801605e 100644 --- a/standardio/OSExecuteDemo.java +++ b/standardio/OSExecuteDemo.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates standard I/O redirection. +// Demonstrates standard I/O redirection import onjava.*; public class OSExecuteDemo { diff --git a/standardio/Redirecting.java b/standardio/Redirecting.java index ca936dcb..5f647bc5 100644 --- a/standardio/Redirecting.java +++ b/standardio/Redirecting.java @@ -2,12 +2,12 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates standard I/O redirection. +// Demonstrates standard I/O redirection import java.io.*; public class Redirecting { - public static void main(String[] args) - throws IOException { + public static void + main(String[] args) throws IOException { PrintStream console = System.out; try(BufferedInputStream in = new BufferedInputStream( new FileInputStream("Redirecting.java")); @@ -18,7 +18,7 @@ public class Redirecting { System.setOut(out); System.setErr(out); BufferedReader br = new BufferedReader( - new InputStreamReader(System.in)); + new InputStreamReader(System.in)); String s; while((s = br.readLine()) != null) System.out.println(s); diff --git a/standardio/build.xml b/standardio/build.xml index bcd6e154..5a06e455 100644 --- a/standardio/build.xml +++ b/standardio/build.xml @@ -16,9 +16,9 @@ - + - + \ No newline at end of file diff --git a/staticchecking/DogsAndRobots.cpp b/staticchecking/DogsAndRobots.cpp index c60808db..eeb7f12e 100644 --- a/staticchecking/DogsAndRobots.cpp +++ b/staticchecking/DogsAndRobots.cpp @@ -27,3 +27,7 @@ int main() { speak(d); speak(r); } +/* Output: +Arf! +Click! +*/ diff --git a/staticchecking/DogsAndRobots.py b/staticchecking/DogsAndRobots.py index cbdd8628..68663e34 100644 --- a/staticchecking/DogsAndRobots.py +++ b/staticchecking/DogsAndRobots.py @@ -7,11 +7,11 @@ def speak(anything): anything.talk() class Dog: - def talk(self): System.out.println("Arf!") + def talk(self): print("Arf!") def reproduce(self): pass class Robot: - def talk(self): System.out.println("Click!") + def talk(self): print("Click!") def oilChange(self): pass a = Dog() @@ -19,3 +19,8 @@ b = Robot() speak(a) speak(b) + +output = """ +Arf! +Click! +""" diff --git a/staticchecking/NoBasePetSpeak.py b/staticchecking/NoBasePetSpeak.py index 1278b0eb..6ada6189 100644 --- a/staticchecking/NoBasePetSpeak.py +++ b/staticchecking/NoBasePetSpeak.py @@ -2,23 +2,23 @@ # (c)2016 MindView LLC: see Copyright.txt # We make no guarantees that this code is fit for any purpose. # Visit http://mindviewinc.com/Books/OnJava/ for more book information. -# Speaking pets without base classes: +# Speaking pets without base classes class Cat: def speak(self): - System.out.println("meow!") + print("meow!") class Dog: def speak(self): - System.out.println("woof!") + print("woof!") class Bob: def bow(self): - System.out.println("thank you, thank you!") + print("thank you, thank you!") def speak(self): - System.out.println("Welcome to the neighborhood!") + print("Welcome to the neighborhood!") def drive(self): - System.out.println("beep, beep!") + print("beep, beep!") def command(pet): pet.speak() @@ -27,3 +27,9 @@ pets = [ Cat(), Dog(), Bob() ] for pet in pets: command(pet) + +output = """ +meow! +woof! +Welcome to the neighborhood! +""" diff --git a/staticchecking/PetSpeak.py b/staticchecking/PetSpeak.py index dcc6e76f..36c8f2d3 100644 --- a/staticchecking/PetSpeak.py +++ b/staticchecking/PetSpeak.py @@ -9,15 +9,20 @@ class Pet: class Cat(Pet): def speak(self): - System.out.println("meow!") + print("meow!") class Dog(Pet): def speak(self): - System.out.println("woof!") + print("woof!") def command(pet): pet.speak() -pets = [ Cat(), Dog() ] -for pet in pets: +pets = [ Cat(), Dog() ] # (1) +for pet in pets: # (2) command(pet) + +output = """ +meow! +woof! +""" diff --git a/staticchecking/dogsandrobots.go b/staticchecking/dogsandrobots.go index beae7f59..fdfe72e8 100644 --- a/staticchecking/dogsandrobots.go +++ b/staticchecking/dogsandrobots.go @@ -21,3 +21,7 @@ func main() { speak(Dog{}) speak(Robot{}) } +/* Output: +woof! +Click! +*/ diff --git a/staticchecking/drc/DogAndRobotCollections.java b/staticchecking/drc/DogAndRobotCollections.java index 84834f2f..e8cfaccc 100644 --- a/staticchecking/drc/DogAndRobotCollections.java +++ b/staticchecking/drc/DogAndRobotCollections.java @@ -25,13 +25,11 @@ public class DogAndRobotCollections { List robotList = new ArrayList<>(); for(int i = 0; i < 10; i++) dogList.add(new Dog()); - // dogList.add(new Robot()); // Compile-time error + //- dogList.add(new Robot()); // Compile-time error for(int i = 0; i < 10; i++) robotList.add(new Robot()); - // robotList.add(new Dog()); // Compile-time error - // No cast necessary + //- robotList.add(new Dog()); // Compile-time error dogList.forEach(Dog::talk); - // No cast necessary robotList.forEach(Robot::talk); } } diff --git a/staticchecking/petspeak.go b/staticchecking/petspeak.go index 297806ec..e226e8a9 100644 --- a/staticchecking/petspeak.go +++ b/staticchecking/petspeak.go @@ -12,9 +12,15 @@ type Dog struct {} func (this Dog) speak() { fmt.Printf("woof!\n")} type Bob struct {} -func (this Bob) bow() { fmt.Printf("thank you, thank you!\n") } -func (this Bob) speak() { fmt.Printf("Welcome to the neighborhood!\n") } -func (this Bob) drive() { fmt.Printf("beep, beep!\n") } +func (this Bob) bow() { + fmt.Printf("thank you, thank you!\n") +} +func (this Bob) speak() { + fmt.Printf("Welcome to the neighborhood!\n") +} +func (this Bob) drive() { + fmt.Printf("beep, beep!\n") +} type Speaker interface { speak() @@ -22,7 +28,8 @@ type Speaker interface { func command(s Speaker) { s.speak() } -// If "Speaker" is never used anywhere else, it can be anonymous: +// If "Speaker" is never used +// anywhere else, it can be anonymous: func command2(s interface { speak() }) { s.speak() } func main() { @@ -33,3 +40,12 @@ func main() { command2(Dog{}) command2(Bob{}) } + +/* Output: +meow! +woof! +Welcome to the neighborhood! +meow! +woof! +Welcome to the neighborhood! +*/ diff --git a/streams/FileToWordsBuilder.java b/streams/FileToWordsBuilder.java index ec7591b3..89619eb4 100644 --- a/streams/FileToWordsBuilder.java +++ b/streams/FileToWordsBuilder.java @@ -18,7 +18,8 @@ public class FileToWordsBuilder { }); } Stream stream() { return builder.build(); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { new FileToWordsBuilder("Cheese.dat").stream() .limit(7) .map(w -> w + " ") diff --git a/streams/FileToWordsRegexp.java b/streams/FileToWordsRegexp.java index 45dbcfae..453596f7 100644 --- a/streams/FileToWordsRegexp.java +++ b/streams/FileToWordsRegexp.java @@ -18,7 +18,8 @@ public class FileToWordsRegexp { public Stream stream() { return Pattern.compile("[ .,?]+").splitAsStream(all); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { FileToWordsRegexp fw = new FileToWordsRegexp("Cheese.dat"); fw.stream() diff --git a/streams/FileToWordsTest.java b/streams/FileToWordsTest.java index c43d3fed..761c1d32 100644 --- a/streams/FileToWordsTest.java +++ b/streams/FileToWordsTest.java @@ -5,7 +5,8 @@ import java.util.stream.*; public class FileToWordsTest { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { FileToWords.stream("Cheese.dat") .limit(7) .forEach(s -> System.out.format("%s ", s)); diff --git a/streams/FlatMap.java b/streams/FlatMap.java index 915dc8f7..982e591f 100644 --- a/streams/FlatMap.java +++ b/streams/FlatMap.java @@ -7,7 +7,8 @@ import java.util.stream.*; public class FlatMap { public static void main(String[] args) { Stream.of(1, 2, 3) - .flatMap(i -> Stream.of("Gonzo", "Fozzie", "Beaker")) + .flatMap( + i -> Stream.of("Gonzo", "Fozzie", "Beaker")) .forEach(System.out::println); } } diff --git a/streams/Informational.java b/streams/Informational.java index 43fb11f5..ff3691a2 100644 --- a/streams/Informational.java +++ b/streams/Informational.java @@ -6,7 +6,8 @@ import java.util.stream.*; import java.util.function.*; public class Informational { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { System.out.println( FileToWords.stream("Cheese.dat").count()); System.out.println( diff --git a/streams/OptionalFlatMap.java b/streams/OptionalFlatMap.java index 808a3fa6..ba0d586b 100644 --- a/streams/OptionalFlatMap.java +++ b/streams/OptionalFlatMap.java @@ -34,7 +34,8 @@ class OptionalFlatMap { } }); - test("Replace", s -> Optional.of(s.replace("2", "9"))); + test("Replace", + s -> Optional.of(s.replace("2", "9"))); test("Take last digit", s -> Optional.of(s.length() > 0 ? diff --git a/streams/Peeking.java b/streams/Peeking.java index 737004ee..67cc56ea 100644 --- a/streams/Peeking.java +++ b/streams/Peeking.java @@ -4,7 +4,8 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. class Peeking { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { FileToWords.stream("Cheese.dat") .skip(21) .limit(4) diff --git a/streams/RandomWords.java b/streams/RandomWords.java index d21db401..b72cff78 100644 --- a/streams/RandomWords.java +++ b/streams/RandomWords.java @@ -25,9 +25,11 @@ public class RandomWords implements Supplier { } @Override public String toString() { - return words.stream().collect(Collectors.joining(" ")); + return words.stream() + .collect(Collectors.joining(" ")); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { System.out.println( Stream.generate(new RandomWords("Cheese.dat")) .limit(10) diff --git a/streams/SortedComparator.java b/streams/SortedComparator.java index d5edacaa..2fba575d 100644 --- a/streams/SortedComparator.java +++ b/streams/SortedComparator.java @@ -5,7 +5,8 @@ import java.util.*; public class SortedComparator { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { FileToWords.stream("Cheese.dat") .skip(10) .limit(10) diff --git a/streams/SpecialCollector.java b/streams/SpecialCollector.java index 8ecb5c23..474b09dc 100644 --- a/streams/SpecialCollector.java +++ b/streams/SpecialCollector.java @@ -6,7 +6,8 @@ import java.util.*; import java.util.stream.*; public class SpecialCollector { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { ArrayList words = FileToWords.stream("Cheese.dat") .collect(ArrayList::new, diff --git a/streams/TreeSetOfWords.java b/streams/TreeSetOfWords.java index 48b73141..f2e17e2a 100644 --- a/streams/TreeSetOfWords.java +++ b/streams/TreeSetOfWords.java @@ -7,7 +7,8 @@ import java.nio.file.*; import java.util.stream.*; public class TreeSetOfWords { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Set words2 = Files.lines(Paths.get("TreeSetOfWords.java")) .flatMap(s -> Arrays.stream(s.split("\\W+"))) diff --git a/strings/InfiniteRecursion.java b/strings/InfiniteRecursion.java index 1bd4f930..76908172 100644 --- a/strings/InfiniteRecursion.java +++ b/strings/InfiniteRecursion.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://mindviewinc.com/Books/OnJava/ for more book information. -// Accidental recursion. +// Accidental recursion // {ThrowsException} // {ValidateByHand} import java.util.*; diff --git a/strings/JGrep.java b/strings/JGrep.java index 49458e22..93a6cc41 100644 --- a/strings/JGrep.java +++ b/strings/JGrep.java @@ -2,14 +2,15 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A very simple version of the "grep" program. +// A very simple version of the "grep" program // {Args: WhitherStringBuilder.java 'return|for|String'} import java.util.regex.*; import java.nio.file.*; import java.util.stream.*; public class JGrep { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length < 2) { System.out.println("Usage: java JGrep file regex"); System.exit(0); diff --git a/strings/ReceiptBuilder.java b/strings/ReceiptBuilder.java index 8c9d3120..bee6b5e6 100644 --- a/strings/ReceiptBuilder.java +++ b/strings/ReceiptBuilder.java @@ -6,7 +6,8 @@ import java.util.*; public class ReceiptBuilder { private double total = 0; - private Formatter f = new Formatter(new StringBuilder()); + private Formatter f = + new Formatter(new StringBuilder()); public ReceiptBuilder() { f.format("%-15s %5s %10s\n", "Item", "Qty", "Price"); f.format("%-15s %5s %10s\n", "----", "---", "-----"); diff --git a/strings/Resetting.java b/strings/Resetting.java index e6fc0a3e..7a1b1343 100644 --- a/strings/Resetting.java +++ b/strings/Resetting.java @@ -5,7 +5,8 @@ import java.util.regex.*; public class Resetting { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Matcher m = Pattern.compile("[frb][aiu][gx]") .matcher("fix the rug with bags"); while(m.find()) diff --git a/strings/StartEnd.java b/strings/StartEnd.java index 23e39587..faecde11 100644 --- a/strings/StartEnd.java +++ b/strings/StartEnd.java @@ -8,7 +8,7 @@ public class StartEnd { public static String input = "As long as there is injustice, whenever a\n" + "Targathian baby cries out, wherever a distress\n" + - "signal sounds among the stars ... We'll be there.\n" + + "signal sounds among the stars ... We'll be there.\n"+ "This fine ship, and this fine crew ...\n" + "Never give up! Never surrender!"; private static class Display { diff --git a/strings/TestRegularExpression.java b/strings/TestRegularExpression.java index 161accca..3120424a 100644 --- a/strings/TestRegularExpression.java +++ b/strings/TestRegularExpression.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://mindviewinc.com/Books/OnJava/ for more book information. -// Easily try out regular expressions. +// Easily try out regular expressions // {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" } import java.util.regex.*; diff --git a/strings/TheReplacements.java b/strings/TheReplacements.java index 56fcba5f..f35dc811 100644 --- a/strings/TheReplacements.java +++ b/strings/TheReplacements.java @@ -13,7 +13,8 @@ import java.util.stream.*; extracted block. !*/ public class TheReplacements { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { String s = Files.lines( Paths.get("TheReplacements.java")) .collect(Collectors.joining("\n")); diff --git a/strings/ThreatAnalyzer.java b/strings/ThreatAnalyzer.java index 569ec028..c3224945 100644 --- a/strings/ThreatAnalyzer.java +++ b/strings/ThreatAnalyzer.java @@ -22,7 +22,8 @@ public class ThreatAnalyzer { MatchResult match = scanner.match(); String ip = match.group(1); String date = match.group(2); - System.out.format("Threat on %s from %s\n", date,ip); + System.out.format( + "Threat on %s from %s\n", date,ip); } } } diff --git a/swt/ColorBoxes.java b/swt/ColorBoxes.java index 26c5e0d5..543875b2 100644 --- a/swt/ColorBoxes.java +++ b/swt/ColorBoxes.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://mindviewinc.com/Books/OnJava/ for more book information. -// SWT translation of Swing ColorBoxes.java. +// SWT translation of Swing ColorBoxes.java import swt.util.*; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; @@ -23,7 +23,7 @@ class CBox extends Canvas implements Runnable { color.dispose(); } } - private static Random rand = new Random(); + private static SplittableRandom rand = new SplittableRandom(); private static RGB newColor() { return new RGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)); diff --git a/swt/DisplayEnvironment.java b/swt/DisplayEnvironment.java index 55b21979..b2169113 100644 --- a/swt/DisplayEnvironment.java +++ b/swt/DisplayEnvironment.java @@ -8,7 +8,8 @@ import org.eclipse.swt.widgets.*; import org.eclipse.swt.layout.*; import java.util.*; -public class DisplayEnvironment implements SWTApplication { +public class +DisplayEnvironment implements SWTApplication { @Override public void createContents(Composite parent) { parent.setLayout(new FillLayout()); @@ -18,7 +19,7 @@ public class DisplayEnvironment implements SWTApplication { entry.getValue() + "\n"); } } - public static void main(String [] args) { + public static void main(String[] args) { SWTConsole.run(new DisplayEnvironment(), 800, 600); } } diff --git a/swt/DisplayProperties.java b/swt/DisplayProperties.java index 4e37808b..39548b95 100644 --- a/swt/DisplayProperties.java +++ b/swt/DisplayProperties.java @@ -8,7 +8,7 @@ import org.eclipse.swt.layout.*; import java.io.*; public class DisplayProperties { - public static void main(String [] args) { + public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Display Properties"); diff --git a/swt/HelloSWT.java b/swt/HelloSWT.java index 6fb43a27..a8f2f14a 100644 --- a/swt/HelloSWT.java +++ b/swt/HelloSWT.java @@ -7,7 +7,7 @@ import org.eclipse.swt.widgets.*; public class HelloSWT { - public static void main(String [] args) { + public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Hi there, SWT!"); // Title bar diff --git a/swt/Menus.java b/swt/Menus.java index 98a56a84..18c54b9e 100644 --- a/swt/Menus.java +++ b/swt/Menus.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://mindviewinc.com/Books/OnJava/ for more book information. -// Fun with menus. +// Fun with menus import swt.util.*; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; @@ -49,7 +49,8 @@ public class Menus implements SWTApplication { }; void addItem(Menu bar, Iterator it, MenuItem mItem) { - MenuItem item = new MenuItem(mItem.getMenu(),SWT.PUSH); + MenuItem item = + new MenuItem(mItem.getMenu(),SWT.PUSH); item.addListener(SWT.Selection, listener); item.setText(it.next()); } diff --git a/swt/ShellsAreMainWindows.java b/swt/ShellsAreMainWindows.java index f252e68d..3d64b9f2 100644 --- a/swt/ShellsAreMainWindows.java +++ b/swt/ShellsAreMainWindows.java @@ -6,7 +6,7 @@ import org.eclipse.swt.widgets.*; public class ShellsAreMainWindows { static Shell[] shells = new Shell[10]; - public static void main(String [] args) { + public static void main(String[] args) { Display display = new Display(); for(int i = 0; i < shells.length; i++) { shells[i] = new Shell(display); diff --git a/swt/SineWave.java b/swt/SineWave.java index 5f18a984..3d644656 100644 --- a/swt/SineWave.java +++ b/swt/SineWave.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://mindviewinc.com/Books/OnJava/ for more book information. -// SWT translation of Swing SineWave.java. +// SWT translation of Swing SineWave.java import swt.util.*; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; diff --git a/swt/TabbedPane.java b/swt/TabbedPane.java index 7c6a0166..f0a41108 100644 --- a/swt/TabbedPane.java +++ b/swt/TabbedPane.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://mindviewinc.com/Books/OnJava/ for more book information. -// Placing SWT components in tabbed panes. +// Placing SWT components in tabbed panes import swt.util.*; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; @@ -104,7 +104,8 @@ public class TabbedPane implements SWTApplication { tab.setText("Scribble"); tab.setToolTipText("Simple graphics: drawing"); final Canvas canvas = new Canvas(folder, SWT.NONE); - ScribbleMouseListener sml= new ScribbleMouseListener(); + ScribbleMouseListener sml = + new ScribbleMouseListener(); canvas.addMouseListener(sml); canvas.addMouseMoveListener(sml); tab.setControl(canvas); @@ -120,7 +121,9 @@ public class TabbedPane implements SWTApplication { gc.dispose(); updatePoint(e); } - public void mouseDown(MouseEvent e) { updatePoint(e); } + public void mouseDown(MouseEvent e) { + updatePoint(e); + } private void updatePoint(MouseEvent e) { p.x = e.x; p.y = e.y; diff --git a/concurrency/ActiveObjectDemo.java b/tasks/ActiveObjectDemo.java similarity index 95% rename from concurrency/ActiveObjectDemo.java rename to tasks/ActiveObjectDemo.java index 999d7e72..f39bb0dc 100644 --- a/concurrency/ActiveObjectDemo.java +++ b/tasks/ActiveObjectDemo.java @@ -1,17 +1,17 @@ -// concurrency/ActiveObjectDemo.java +// tasks/ActiveObjectDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Can only pass constants, immutables, "disconnected // objects," or other active objects as arguments -// to asynch methods. +// to asynch methods import java.util.concurrent.*; import java.util.*; public class ActiveObjectDemo { private ExecutorService ex = Executors.newSingleThreadExecutor(); - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); // Insert a random delay to produce the effect // of a calculation time: private void pause(int factor) { diff --git a/concurrency/AtomicEvenSupplier.java b/tasks/AtomicEvenSupplier.java similarity index 85% rename from concurrency/AtomicEvenSupplier.java rename to tasks/AtomicEvenSupplier.java index 8edd5191..fff3899f 100644 --- a/concurrency/AtomicEvenSupplier.java +++ b/tasks/AtomicEvenSupplier.java @@ -1,8 +1,8 @@ -// concurrency/AtomicEvenSupplier.java +// tasks/AtomicEvenSupplier.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Atomic classes are occasionally useful in regular code. +// Atomic classes are occasionally useful in regular code // {TimeOutDuringTesting} // {IgnoreOutput} // No output validation import java.util.concurrent.atomic.*; diff --git a/concurrency/AtomicIntegerTest.java b/tasks/AtomicIntegerTest.java similarity index 96% rename from concurrency/AtomicIntegerTest.java rename to tasks/AtomicIntegerTest.java index 2d40c88f..1394399e 100644 --- a/concurrency/AtomicIntegerTest.java +++ b/tasks/AtomicIntegerTest.java @@ -1,4 +1,4 @@ -// concurrency/AtomicIntegerTest.java +// tasks/AtomicIntegerTest.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/Atomicity.java b/tasks/Atomicity.java similarity index 96% rename from concurrency/Atomicity.java rename to tasks/Atomicity.java index 24aace63..5d1ec193 100644 --- a/concurrency/Atomicity.java +++ b/tasks/Atomicity.java @@ -1,4 +1,4 @@ -// concurrency/Atomicity.java +// tasks/Atomicity.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/AtomicityTest.java b/tasks/AtomicityTest.java similarity index 86% rename from concurrency/AtomicityTest.java rename to tasks/AtomicityTest.java index d78fc41c..2f85d8cc 100644 --- a/concurrency/AtomicityTest.java +++ b/tasks/AtomicityTest.java @@ -1,4 +1,4 @@ -// concurrency/AtomicityTest.java +// tasks/AtomicityTest.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -15,9 +15,9 @@ public class AtomicityTest implements Runnable { evenIncrement(); } public static void main(String[] args) { - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); AtomicityTest at = new AtomicityTest(); - exec.execute(at); + es.execute(at); while(true) { int val = at.getValue(); if(val % 2 != 0) { diff --git a/concurrency/AttemptLocking.java b/tasks/AttemptLocking.java similarity index 90% rename from concurrency/AttemptLocking.java rename to tasks/AttemptLocking.java index f380f6a4..8c0bbb58 100644 --- a/concurrency/AttemptLocking.java +++ b/tasks/AttemptLocking.java @@ -1,9 +1,9 @@ -// concurrency/AttemptLocking.java +// tasks/AttemptLocking.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Locks in the concurrent library allow you -// to give up on trying to acquire a lock. +// to give up on trying to acquire a lock import java.util.concurrent.*; import java.util.concurrent.locks.*; @@ -26,8 +26,8 @@ public class AttemptLocking { throw new RuntimeException(e); } try { - System.out.println("tryLock(2, TimeUnit.SECONDS): " + - captured); + System.out.println( + "tryLock(2, TimeUnit.SECONDS): " + captured); } finally { if(captured) lock.unlock(); diff --git a/concurrency/BankTellerSimulation.java b/tasks/BankTellerSimulation.java similarity index 90% rename from concurrency/BankTellerSimulation.java rename to tasks/BankTellerSimulation.java index fc810fee..add65a65 100644 --- a/concurrency/BankTellerSimulation.java +++ b/tasks/BankTellerSimulation.java @@ -1,8 +1,8 @@ -// concurrency/BankTellerSimulation.java +// tasks/BankTellerSimulation.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using queues and multithreading. +// Using queues and multithreading // {Args: 5} import java.util.concurrent.*; import java.util.*; @@ -36,7 +36,7 @@ class CustomerLine extends ArrayBlockingQueue { // Randomly add customers to a queue: class CustomerSupplier implements Runnable { private CustomerLine customers; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); public CustomerSupplier(CustomerLine cq) { customers = cq; } @@ -84,11 +84,14 @@ class Teller implements Runnable, Comparable { servingCustomerLine = false; } public synchronized void serveCustomerLine() { - assert !servingCustomerLine:"already serving: " + this; + assert !servingCustomerLine: + "already serving: " + this; servingCustomerLine = true; notifyAll(); } - public String toString() { return "Teller " + id + " "; } + public String toString() { + return "Teller " + id + " "; + } public String shortString() { return "T" + id; } // Used by priority queue: public synchronized int compareTo(Teller other) { @@ -125,7 +128,8 @@ class TellerManager implements Runnable { // If tellers are on break or doing // another job, bring one back: if(tellersDoingOtherThings.size() > 0) { - Teller teller = tellersDoingOtherThings.remove(); + Teller teller = + tellersDoingOtherThings.remove(); teller.serveCustomerLine(); workingTellers.offer(teller); return; @@ -174,22 +178,23 @@ class TellerManager implements Runnable { public class BankTellerSimulation { static final int MAX_LINE_SIZE = 50; static final int ADJUSTMENT_PERIOD = 1000; - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); // If line is too long, customers will leave: CustomerLine customers = new CustomerLine(MAX_LINE_SIZE); - exec.execute(new CustomerSupplier(customers)); + es.execute(new CustomerSupplier(customers)); // Manager will add and remove tellers as necessary: - exec.execute(new TellerManager( - exec, customers, ADJUSTMENT_PERIOD)); + es.execute(new TellerManager( + es, customers, ADJUSTMENT_PERIOD)); if(args.length > 0) // Optional argument TimeUnit.SECONDS.sleep(new Integer(args[0])); else { System.out.println("Press 'Enter' to quit"); System.in.read(); } - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: diff --git a/concurrency/BasicThreads.java b/tasks/BasicThreads.java similarity index 86% rename from concurrency/BasicThreads.java rename to tasks/BasicThreads.java index 63ee3a2a..49b84191 100644 --- a/concurrency/BasicThreads.java +++ b/tasks/BasicThreads.java @@ -1,8 +1,8 @@ -// concurrency/BasicThreads.java +// tasks/BasicThreads.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// The most basic use of the Thread class. +// The most basic use of the Thread class public class BasicThreads { public static void main(String[] args) { diff --git a/concurrency/CachedThreadPool.java b/tasks/CachedThreadPool.java similarity index 82% rename from concurrency/CachedThreadPool.java rename to tasks/CachedThreadPool.java index 7bff5d80..715a8048 100644 --- a/concurrency/CachedThreadPool.java +++ b/tasks/CachedThreadPool.java @@ -1,4 +1,4 @@ -// concurrency/CachedThreadPool.java +// tasks/CachedThreadPool.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -6,10 +6,10 @@ import java.util.concurrent.*; public class CachedThreadPool { public static void main(String[] args) { - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService e = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) - exec.execute(new LiftOff()); - exec.shutdown(); + e.execute(new LiftOff()); + e.shutdown(); } } /* Output: diff --git a/concurrency/CallableDemo.java b/tasks/CallableDemo.java similarity index 87% rename from concurrency/CallableDemo.java rename to tasks/CallableDemo.java index b123da6f..6321980f 100644 --- a/concurrency/CallableDemo.java +++ b/tasks/CallableDemo.java @@ -1,4 +1,4 @@ -// concurrency/CallableDemo.java +// tasks/CallableDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -18,10 +18,10 @@ class TaskWithResult implements Callable { public class CallableDemo { public static void main(String[] args) { - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); ArrayList> results = new ArrayList<>(); for(int i = 0; i < 10; i++) - results.add(exec.submit(new TaskWithResult(i))); + results.add(es.submit(new TaskWithResult(i))); for(Future fs : results) try { // get() blocks until completion: @@ -32,7 +32,7 @@ public class CallableDemo { } catch(ExecutionException e) { System.out.println(e); } finally { - exec.shutdown(); + es.shutdown(); } } } diff --git a/concurrency/CaptureUncaughtException.java b/tasks/CaptureUncaughtException.java similarity index 97% rename from concurrency/CaptureUncaughtException.java rename to tasks/CaptureUncaughtException.java index cedd75aa..45fb52ce 100644 --- a/concurrency/CaptureUncaughtException.java +++ b/tasks/CaptureUncaughtException.java @@ -1,4 +1,4 @@ -// concurrency/CaptureUncaughtException.java +// tasks/CaptureUncaughtException.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/CarBuilder.java b/tasks/CarBuilder.java similarity index 92% rename from concurrency/CarBuilder.java rename to tasks/CarBuilder.java index b6cd9fb9..1efce05e 100644 --- a/concurrency/CarBuilder.java +++ b/tasks/CarBuilder.java @@ -1,8 +1,8 @@ -// concurrency/CarBuilder.java +// tasks/CarBuilder.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A complex example of tasks working together. +// A complex example of tasks working together import java.util.concurrent.*; import java.util.*; @@ -55,7 +55,8 @@ class Assembler implements Runnable { private Car car; private CyclicBarrier barrier = new CyclicBarrier(4); private RobotPool robotPool; - public Assembler(CarQueue cq, CarQueue fq, RobotPool rp){ + public + Assembler(CarQueue cq, CarQueue fq, RobotPool rp) { chassisQueue = cq; finishingQueue = fq; robotPool = rp; @@ -77,7 +78,8 @@ class Assembler implements Runnable { finishingQueue.put(car); } } catch(InterruptedException e) { - System.out.println("Exiting Assembler via interrupt"); + System.out.println( + "Exiting Assembler via interrupt"); } catch(BrokenBarrierException e) { // This one we want to know about throw new RuntimeException(e); @@ -96,7 +98,8 @@ class Reporter implements Runnable { System.out.println(carQueue.take()); } } catch(InterruptedException e) { - System.out.println("Exiting Reporter via interrupt"); + System.out.println( + "Exiting Reporter via interrupt"); } System.out.println("Reporter off"); } @@ -144,7 +147,9 @@ abstract class Robot implements Runnable { while(engage == false) // Power down wait(); } - public String toString() { return getClass().getName(); } + public String toString() { + return getClass().getName(); + } } class EngineRobot extends Robot { @@ -195,21 +200,22 @@ class RobotPool { } public class CarBuilder { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { CarQueue chassisQueue = new CarQueue(), finishingQueue = new CarQueue(); - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); RobotPool robotPool = new RobotPool(); - exec.execute(new EngineRobot(robotPool)); - exec.execute(new DriveTrainRobot(robotPool)); - exec.execute(new WheelRobot(robotPool)); - exec.execute(new Assembler( + es.execute(new EngineRobot(robotPool)); + es.execute(new DriveTrainRobot(robotPool)); + es.execute(new WheelRobot(robotPool)); + es.execute(new Assembler( chassisQueue, finishingQueue, robotPool)); - exec.execute(new Reporter(finishingQueue)); + es.execute(new Reporter(finishingQueue)); // Start everything running by producing chassis: - exec.execute(new ChassisBuilder(chassisQueue)); + es.execute(new ChassisBuilder(chassisQueue)); TimeUnit.SECONDS.sleep(7); - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: diff --git a/concurrency/Chopstick.java b/tasks/Chopstick.java similarity index 86% rename from concurrency/Chopstick.java rename to tasks/Chopstick.java index 6bf2e7be..c27b343a 100644 --- a/concurrency/Chopstick.java +++ b/tasks/Chopstick.java @@ -1,8 +1,8 @@ -// concurrency/Chopstick.java +// tasks/Chopstick.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Chopsticks for dining philosophers. +// Chopsticks for dining philosophers public class Chopstick { private boolean taken = false; diff --git a/concurrency/CloseResource.java b/tasks/CloseResource.java similarity index 74% rename from concurrency/CloseResource.java rename to tasks/CloseResource.java index ff557522..9a75118d 100644 --- a/concurrency/CloseResource.java +++ b/tasks/CloseResource.java @@ -1,25 +1,27 @@ -// concurrency/CloseResource.java +// tasks/CloseResource.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Interrupting a blocked task by -// closing the underlying resource. +// closing the underlying resource // {TimeOutDuringTesting} import java.net.*; import java.util.concurrent.*; import java.io.*; public class CloseResource { - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); ServerSocket server = new ServerSocket(8080); try(InputStream socketInput = - new Socket("localhost", 8080).getInputStream()) { - exec.execute(new IOBlocked(socketInput)); - exec.execute(new IOBlocked(System.in)); + new Socket("localhost", 8080) + .getInputStream()) { + es.execute(new IOBlocked(socketInput)); + es.execute(new IOBlocked(System.in)); TimeUnit.MILLISECONDS.sleep(100); System.out.println("Shutting down all threads"); - exec.shutdownNow(); + es.shutdownNow(); TimeUnit.SECONDS.sleep(1); System.out.println( "Closing " + socketInput.getClass().getName()); diff --git a/concurrency/CountDownLatchDemo.java b/tasks/CountDownLatchDemo.java similarity index 87% rename from concurrency/CountDownLatchDemo.java rename to tasks/CountDownLatchDemo.java index 8b27aa47..15feb8d9 100644 --- a/concurrency/CountDownLatchDemo.java +++ b/tasks/CountDownLatchDemo.java @@ -1,4 +1,4 @@ -// concurrency/CountDownLatchDemo.java +// tasks/CountDownLatchDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -9,7 +9,7 @@ import java.util.*; class TaskPortion implements Runnable { private static int counter = 0; private final int id = counter++; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); private final CountDownLatch latch; TaskPortion(CountDownLatch latch) { this.latch = latch; @@ -59,16 +59,17 @@ class WaitingTask implements Runnable { public class CountDownLatchDemo { static final int SIZE = 100; - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); // All must share a single CountDownLatch object: CountDownLatch latch = new CountDownLatch(SIZE); for(int i = 0; i < 10; i++) - exec.execute(new WaitingTask(latch)); + es.execute(new WaitingTask(latch)); for(int i = 0; i < SIZE; i++) - exec.execute(new TaskPortion(latch)); + es.execute(new TaskPortion(latch)); System.out.println("Launched all tasks"); - exec.shutdown(); // Quit when all tasks complete + es.shutdown(); // Quit when all tasks complete } } /* Output: (First and last 10 Lines) diff --git a/concurrency/CriticalSection.java b/tasks/CriticalSection.java similarity index 93% rename from concurrency/CriticalSection.java rename to tasks/CriticalSection.java index 4f00fa72..faaba95d 100644 --- a/concurrency/CriticalSection.java +++ b/tasks/CriticalSection.java @@ -1,13 +1,13 @@ -// concurrency/CriticalSection.java +// tasks/CriticalSection.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {TimeOutDuringTesting} -// (Behavior may have changed in Java 8). +// (Behavior may have changed in Java 8) // Synchronizing blocks instead of entire methods. Also // demonstrates protection of a non-thread-safe class // with a thread-safe one. -package concurrency; +package tasks; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.*; @@ -119,17 +119,17 @@ public class CriticalSection { // Test the two different approaches: static void testApproaches(PairManager pman1, PairManager pman2) { - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); PairManipulator pm1 = new PairManipulator(pman1), pm2 = new PairManipulator(pman2); PairChecker pcheck1 = new PairChecker(pman1), pcheck2 = new PairChecker(pman2); - exec.execute(pm1); - exec.execute(pm2); - exec.execute(pcheck1); - exec.execute(pcheck2); + es.execute(pm1); + es.execute(pm2); + es.execute(pcheck1); + es.execute(pcheck2); try { TimeUnit.MILLISECONDS.sleep(500); } catch(InterruptedException e) { diff --git a/concurrency/DaemonFromFactory.java b/tasks/DaemonFromFactory.java similarity index 90% rename from concurrency/DaemonFromFactory.java rename to tasks/DaemonFromFactory.java index b2fd217b..210a8160 100644 --- a/concurrency/DaemonFromFactory.java +++ b/tasks/DaemonFromFactory.java @@ -1,8 +1,8 @@ -// concurrency/DaemonFromFactory.java +// tasks/DaemonFromFactory.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using a Thread Factory to create daemons. +// Using a Thread Factory to create daemons import java.util.concurrent.*; import onjava.*; @@ -19,7 +19,8 @@ public class DaemonFromFactory implements Runnable { System.out.println("Interrupted"); } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool( new DaemonThreadFactory()); for(int i = 0; i < 10; i++) diff --git a/concurrency/Daemons.java b/tasks/Daemons.java similarity index 92% rename from concurrency/Daemons.java rename to tasks/Daemons.java index 94c15978..2085d1f6 100644 --- a/concurrency/Daemons.java +++ b/tasks/Daemons.java @@ -1,8 +1,8 @@ -// concurrency/Daemons.java +// tasks/Daemons.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Daemon threads spawn other daemon threads. +// Daemon threads spawn other daemon threads import java.util.concurrent.*; class Daemon implements Runnable { @@ -31,7 +31,8 @@ class DaemonSpawn implements Runnable { } public class Daemons { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Thread d = new Thread(new Daemon()); d.setDaemon(true); d.start(); diff --git a/concurrency/DaemonsDoRunFinally.java b/tasks/DaemonsDoRunFinally.java similarity index 89% rename from concurrency/DaemonsDoRunFinally.java rename to tasks/DaemonsDoRunFinally.java index 0ff25db4..1abc95f1 100644 --- a/concurrency/DaemonsDoRunFinally.java +++ b/tasks/DaemonsDoRunFinally.java @@ -1,4 +1,4 @@ -// concurrency/DaemonsDoRunFinally.java +// tasks/DaemonsDoRunFinally.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -21,7 +21,8 @@ class ADaemon implements Runnable { } public class DaemonsDoRunFinally { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Thread t = new Thread(new ADaemon()); t.setDaemon(true); t.start(); diff --git a/concurrency/DeadlockingDiningPhilosophers.java b/tasks/DeadlockingDiningPhilosophers.java similarity index 83% rename from concurrency/DeadlockingDiningPhilosophers.java rename to tasks/DeadlockingDiningPhilosophers.java index 639c679e..f3882311 100644 --- a/concurrency/DeadlockingDiningPhilosophers.java +++ b/tasks/DeadlockingDiningPhilosophers.java @@ -1,25 +1,26 @@ -// concurrency/DeadlockingDiningPhilosophers.java +// tasks/DeadlockingDiningPhilosophers.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates how deadlock can be hidden in a program. +// Demonstrates how deadlock can be hidden in a program // {Args: 0 5 timeout} import java.util.concurrent.*; public class DeadlockingDiningPhilosophers { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { int ponder = 5; if(args.length > 0) ponder = Integer.parseInt(args[0]); int size = 5; if(args.length > 1) size = Integer.parseInt(args[1]); - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); Chopstick[] sticks = new Chopstick[size]; for(int i = 0; i < size; i++) sticks[i] = new Chopstick(); for(int i = 0; i < size; i++) - exec.execute(new Philosopher( + es.execute(new Philosopher( sticks[i], sticks[(i+1) % size], i, ponder)); if(args.length == 3 && args[2].equals("timeout")) TimeUnit.SECONDS.sleep(5); @@ -27,7 +28,7 @@ public class DeadlockingDiningPhilosophers { System.out.println("Press 'Enter' to quit"); System.in.read(); } - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: (First and last 10 Lines) diff --git a/concurrency/DelayQueueDemo.java b/tasks/DelayQueueDemo.java similarity index 90% rename from concurrency/DelayQueueDemo.java rename to tasks/DelayQueueDemo.java index 57069123..c1397451 100644 --- a/concurrency/DelayQueueDemo.java +++ b/tasks/DelayQueueDemo.java @@ -1,4 +1,4 @@ -// concurrency/DelayQueueDemo.java +// tasks/DelayQueueDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -68,7 +68,7 @@ class DelayedTaskConsumer implements Runnable { public void run() { try { while(!Thread.interrupted()) - q.take().run(); // Run task with the current thread + q.take().run(); // Run task with current thread } catch(InterruptedException e) { // Acceptable way to exit } @@ -78,16 +78,16 @@ class DelayedTaskConsumer implements Runnable { public class DelayQueueDemo { public static void main(String[] args) { - Random rand = new Random(47); - ExecutorService exec = Executors.newCachedThreadPool(); + SplittableRandom rand = new SplittableRandom(47); + ExecutorService es = Executors.newCachedThreadPool(); DelayQueue queue = new DelayQueue<>(); // Fill with tasks that have random delays: for(int i = 0; i < 20; i++) queue.put(new DelayedTask(rand.nextInt(5000))); // Set the stopping point - queue.add(new DelayedTask.EndSentinel(5000, exec)); - exec.execute(new DelayedTaskConsumer(queue)); + queue.add(new DelayedTask.EndSentinel(5000, es)); + es.execute(new DelayedTaskConsumer(queue)); } } /* Output: diff --git a/concurrency/EvenChecker.java b/tasks/EvenChecker.java similarity index 85% rename from concurrency/EvenChecker.java rename to tasks/EvenChecker.java index 1fd932bf..98d62fbc 100644 --- a/concurrency/EvenChecker.java +++ b/tasks/EvenChecker.java @@ -1,4 +1,4 @@ -// concurrency/EvenChecker.java +// tasks/EvenChecker.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -24,10 +24,10 @@ public class EvenChecker implements Runnable { // Test any type of IntSupplier: public static void test(IntSupplier gp, int count) { System.out.println("Press Control-C to exit"); - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < count; i++) - exec.execute(new EvenChecker(gp, i)); - exec.shutdown(); + es.execute(new EvenChecker(gp, i)); + es.shutdown(); } // Default value for count: public static void test(IntSupplier gp) { diff --git a/concurrency/EvenSupplier.java b/tasks/EvenSupplier.java similarity index 91% rename from concurrency/EvenSupplier.java rename to tasks/EvenSupplier.java index 275aaa65..10daf942 100644 --- a/concurrency/EvenSupplier.java +++ b/tasks/EvenSupplier.java @@ -1,8 +1,8 @@ -// concurrency/EvenSupplier.java +// tasks/EvenSupplier.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// When threads collide. +// When threads collide // {TimeOutDuringTesting} (on single-core machines) public class EvenSupplier extends IntSupplier { diff --git a/concurrency/ExceptionThread.java b/tasks/ExceptionThread.java similarity index 75% rename from concurrency/ExceptionThread.java rename to tasks/ExceptionThread.java index df906bf5..acd42090 100644 --- a/concurrency/ExceptionThread.java +++ b/tasks/ExceptionThread.java @@ -1,4 +1,4 @@ -// concurrency/ExceptionThread.java +// tasks/ExceptionThread.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -12,7 +12,7 @@ public class ExceptionThread implements Runnable { throw new RuntimeException(); } public static void main(String[] args) { - ExecutorService exec = Executors.newCachedThreadPool(); - exec.execute(new ExceptionThread()); + ExecutorService es = Executors.newCachedThreadPool(); + es.execute(new ExceptionThread()); } } diff --git a/concurrency/ExchangerDemo.java b/tasks/ExchangerDemo.java similarity index 87% rename from concurrency/ExchangerDemo.java rename to tasks/ExchangerDemo.java index 9e0396ca..358dfe1e 100644 --- a/concurrency/ExchangerDemo.java +++ b/tasks/ExchangerDemo.java @@ -1,4 +1,4 @@ -// concurrency/ExchangerDemo.java +// tasks/ExchangerDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -36,7 +36,8 @@ class ExchangerConsumer implements Runnable { private Exchanger> exchanger; private List holder; private volatile T value; - ExchangerConsumer(Exchanger> ex, List holder){ + ExchangerConsumer( + Exchanger> ex, List holder) { exchanger = ex; this.holder = holder; } @@ -60,22 +61,23 @@ class ExchangerConsumer implements Runnable { public class ExchangerDemo { static int size = 10; static int delay = 5; // Seconds - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length > 0) size = new Integer(args[0]); if(args.length > 1) delay = new Integer(args[1]); - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); Exchanger> xc = new Exchanger<>(); List producerList = new CopyOnWriteArrayList<>(), consumerList = new CopyOnWriteArrayList<>(); - exec.execute(new ExchangerProducer<>(xc, + es.execute(new ExchangerProducer<>(xc, BasicSupplier.create(Fat.class), producerList)); - exec.execute( + es.execute( new ExchangerConsumer<>(xc,consumerList)); TimeUnit.SECONDS.sleep(delay); - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: diff --git a/concurrency/ExplicitCriticalSection.java b/tasks/ExplicitCriticalSection.java similarity index 94% rename from concurrency/ExplicitCriticalSection.java rename to tasks/ExplicitCriticalSection.java index 79c06d1d..f60a8782 100644 --- a/concurrency/ExplicitCriticalSection.java +++ b/tasks/ExplicitCriticalSection.java @@ -1,11 +1,10 @@ -// concurrency/ExplicitCriticalSection.java +// tasks/ExplicitCriticalSection.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {ThrowsException} on a multiprocessor machine -// Using explicit Lock objects to create -// critical sections. -package concurrency; +// Using explicit Lock objects to create critical sections +package tasks; import java.util.concurrent.locks.*; // Synchronize the entire method: diff --git a/concurrency/FastSimulation.java b/tasks/FastSimulation.java similarity index 87% rename from concurrency/FastSimulation.java rename to tasks/FastSimulation.java index 68a56e13..e3c74b75 100644 --- a/concurrency/FastSimulation.java +++ b/tasks/FastSimulation.java @@ -1,4 +1,4 @@ -// concurrency/FastSimulation.java +// tasks/FastSimulation.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -12,7 +12,7 @@ public class FastSimulation { static final int N_EVOLVERS = 50; static final AtomicInteger[][] GRID = new AtomicInteger[N_ELEMENTS][N_GENES]; - static Random rand = new Random(47); + static SplittableRandom rand = new SplittableRandom(47); static class Evolver implements Runnable { @Override public void run() { @@ -41,15 +41,17 @@ public class FastSimulation { } } } - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < N_ELEMENTS; i++) for(int j = 0; j < N_GENES; j++) - GRID[i][j] = new AtomicInteger(rand.nextInt(1000)); + GRID[i][j] = + new AtomicInteger(rand.nextInt(1000)); for(int i = 0; i < N_EVOLVERS; i++) - exec.execute(new Evolver()); + es.execute(new Evolver()); TimeUnit.SECONDS.sleep(5); - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: (First and last 10 Lines) diff --git a/concurrency/Fat.java b/tasks/Fat.java similarity index 90% rename from concurrency/Fat.java rename to tasks/Fat.java index a301557a..245a40db 100644 --- a/concurrency/Fat.java +++ b/tasks/Fat.java @@ -1,8 +1,8 @@ -// concurrency/Fat.java +// tasks/Fat.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Objects that are expensive to create. +// Objects that are expensive to create public class Fat { private volatile double d; // Prevent optimization diff --git a/concurrency/FixedDiningPhilosophers.java b/tasks/FixedDiningPhilosophers.java similarity index 83% rename from concurrency/FixedDiningPhilosophers.java rename to tasks/FixedDiningPhilosophers.java index 1ce4d143..9ada5a78 100644 --- a/concurrency/FixedDiningPhilosophers.java +++ b/tasks/FixedDiningPhilosophers.java @@ -1,29 +1,30 @@ -// concurrency/FixedDiningPhilosophers.java +// tasks/FixedDiningPhilosophers.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Dining philosophers without deadlock. +// Dining philosophers without deadlock // {Args: 5 5 timeout} import java.util.concurrent.*; public class FixedDiningPhilosophers { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { int ponder = 5; if(args.length > 0) ponder = Integer.parseInt(args[0]); int size = 5; if(args.length > 1) size = Integer.parseInt(args[1]); - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); Chopstick[] sticks = new Chopstick[size]; for(int i = 0; i < size; i++) sticks[i] = new Chopstick(); for(int i = 0; i < size; i++) if(i < (size-1)) - exec.execute(new Philosopher( + es.execute(new Philosopher( sticks[i], sticks[i+1], i, ponder)); else - exec.execute(new Philosopher( + es.execute(new Philosopher( sticks[0], sticks[i], i, ponder)); if(args.length == 3 && args[2].equals("timeout")) TimeUnit.SECONDS.sleep(5); @@ -31,7 +32,7 @@ public class FixedDiningPhilosophers { System.out.println("Press 'Enter' to quit"); System.in.read(); } - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: (First and last 10 Lines) diff --git a/concurrency/FixedThreadPool.java b/tasks/FixedThreadPool.java similarity index 83% rename from concurrency/FixedThreadPool.java rename to tasks/FixedThreadPool.java index b76e826f..358ac802 100644 --- a/concurrency/FixedThreadPool.java +++ b/tasks/FixedThreadPool.java @@ -1,4 +1,4 @@ -// concurrency/FixedThreadPool.java +// tasks/FixedThreadPool.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -7,10 +7,10 @@ import java.util.concurrent.*; public class FixedThreadPool { public static void main(String[] args) { // Constructor argument is number of threads: - ExecutorService exec = Executors.newFixedThreadPool(5); + ExecutorService e = Executors.newFixedThreadPool(5); for(int i = 0; i < 5; i++) - exec.execute(new LiftOff()); - exec.shutdown(); + e.execute(new LiftOff()); + e.shutdown(); } } /* Output: diff --git a/concurrency/GreenhouseScheduler.java b/tasks/GreenhouseScheduler.java similarity index 90% rename from concurrency/GreenhouseScheduler.java rename to tasks/GreenhouseScheduler.java index 4803d82b..35f1755a 100644 --- a/concurrency/GreenhouseScheduler.java +++ b/tasks/GreenhouseScheduler.java @@ -1,9 +1,9 @@ -// concurrency/GreenhouseScheduler.java +// tasks/GreenhouseScheduler.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Rewriting innerclasses/GreenhouseController.java -// to use a ScheduledThreadPoolExecutor. +// to use a ScheduledThreadPoolExecutor // {Args: 5000} import java.util.concurrent.*; import java.util.*; @@ -101,9 +101,9 @@ public class GreenhouseScheduler { // New feature: data collection static class DataPoint { final Calendar time; - final float temperature; - final float humidity; - public DataPoint(Calendar d, float temp, float hum) { + final double temperature; + final double humidity; + public DataPoint(Calendar d, double temp, double hum) { time = d; temperature = temp; humidity = hum; @@ -121,11 +121,11 @@ public class GreenhouseScheduler { lastTime.set(Calendar.MINUTE, 30); lastTime.set(Calendar.SECOND, 00); } - private float lastTemp = 65.0f; + private double lastTemp = 65.0f; private int tempDirection = +1; - private float lastHumidity = 50.0f; + private double lastHumidity = 50.0f; private int humidityDirection = +1; - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); List data = Collections.synchronizedList( new ArrayList<>()); class CollectData implements Runnable { @@ -140,13 +140,15 @@ public class GreenhouseScheduler { if(rand.nextInt(5) == 4) tempDirection = -tempDirection; // Store previous value: - lastTemp += tempDirection*(1.0f+rand.nextFloat()); + lastTemp += + tempDirection * (1.0f + rand.nextDouble()); if(rand.nextInt(5) == 4) humidityDirection = -humidityDirection; - lastHumidity += humidityDirection*rand.nextFloat(); + lastHumidity += + humidityDirection * rand.nextDouble(); // Calendar must be cloned, otherwise all - // DataPoints hold references to the same lastTime. - // For a basic object like Calendar, clone() is OK. + // DataPoints hold references to same lastTime. + // For basic object like Calendar, clone() is OK. data.add(new DataPoint((Calendar)lastTime.clone(), lastTemp, lastHumidity)); } diff --git a/concurrency/HorseRace.java b/tasks/HorseRace.java similarity index 95% rename from concurrency/HorseRace.java rename to tasks/HorseRace.java index 1535a604..fa41aa68 100644 --- a/concurrency/HorseRace.java +++ b/tasks/HorseRace.java @@ -1,8 +1,8 @@ -// concurrency/HorseRace.java +// tasks/HorseRace.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using CyclicBarriers. +// Using CyclicBarriers import java.util.concurrent.*; import java.util.*; @@ -10,7 +10,7 @@ class Horse implements Runnable { private static int counter = 0; private final int id = counter++; private int strides = 0; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); private static CyclicBarrier barrier; public Horse(CyclicBarrier b) { barrier = b; } public synchronized int getStrides() { return strides; } @@ -19,7 +19,7 @@ class Horse implements Runnable { try { while(!Thread.interrupted()) { synchronized(this) { - strides += rand.nextInt(3); // Produces 0, 1 or 2 + strides += rand.nextInt(3); // Yeilds 0, 1 or 2 } barrier.await(); } diff --git a/concurrency/IntSupplier.java b/tasks/IntSupplier.java similarity index 92% rename from concurrency/IntSupplier.java rename to tasks/IntSupplier.java index 7ff240c4..4397462c 100644 --- a/concurrency/IntSupplier.java +++ b/tasks/IntSupplier.java @@ -1,4 +1,4 @@ -// concurrency/IntSupplier.java +// tasks/IntSupplier.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/Interrupting.java b/tasks/Interrupting.java similarity index 87% rename from concurrency/Interrupting.java rename to tasks/Interrupting.java index 09f9a97c..92dff245 100644 --- a/concurrency/Interrupting.java +++ b/tasks/Interrupting.java @@ -1,8 +1,8 @@ -// concurrency/Interrupting.java +// tasks/Interrupting.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Interrupting a blocked thread. +// Interrupting a blocked thread import java.util.concurrent.*; import java.io.*; @@ -28,7 +28,8 @@ class IOBlocked implements Runnable { in.read(); } catch(IOException e) { if(Thread.currentThread().isInterrupted()) { - System.out.println("Interrupted from blocked I/O"); + System.out.println( + "Interrupted from blocked I/O"); } else { throw new RuntimeException(e); } @@ -54,14 +55,16 @@ class SynchronizedBlocked implements Runnable { public void run() { System.out.println("Trying to call f()"); f(); - System.out.println("Exiting SynchronizedBlocked.run()"); + System.out.println( + "Exiting SynchronizedBlocked.run()"); } } public class Interrupting { private static ExecutorService exec = Executors.newCachedThreadPool(); - static void test(Runnable r) throws InterruptedException{ + static void + test(Runnable r) throws InterruptedException { Future f = exec.submit(r); TimeUnit.MILLISECONDS.sleep(100); System.out.println( @@ -70,7 +73,8 @@ public class Interrupting { System.out.println( "Interrupt sent to " + r.getClass().getName()); } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { test(new SleepBlocked()); test(new IOBlocked(System.in)); test(new SynchronizedBlocked()); diff --git a/concurrency/Interrupting2.java b/tasks/Interrupting2.java similarity index 90% rename from concurrency/Interrupting2.java rename to tasks/Interrupting2.java index c321d77e..8f7aa4bb 100644 --- a/concurrency/Interrupting2.java +++ b/tasks/Interrupting2.java @@ -1,8 +1,8 @@ -// concurrency/Interrupting2.java +// tasks/Interrupting2.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Interrupting a task blocked with a ReentrantLock. +// Interrupting a task blocked with a ReentrantLock import java.util.concurrent.*; import java.util.concurrent.locks.*; @@ -36,7 +36,8 @@ class Blocked2 implements Runnable { } public class Interrupting2 { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Thread t = new Thread(new Blocked2()); t.start(); TimeUnit.SECONDS.sleep(1); diff --git a/concurrency/InterruptingIdiom.java b/tasks/InterruptingIdiom.java similarity index 93% rename from concurrency/InterruptingIdiom.java rename to tasks/InterruptingIdiom.java index 3f2e2649..e976eba3 100644 --- a/concurrency/InterruptingIdiom.java +++ b/tasks/InterruptingIdiom.java @@ -1,8 +1,8 @@ -// concurrency/InterruptingIdiom.java +// tasks/InterruptingIdiom.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// General idiom for interrupting a task. +// General idiom for interrupting a task // {Args: 1100} import java.util.concurrent.*; @@ -56,7 +56,8 @@ class Blocked3 implements Runnable { } public class InterruptingIdiom { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { if(args.length != 1) { System.out.println( "usage: java InterruptingIdiom delay-in-mS"); diff --git a/concurrency/Joining.java b/tasks/Joining.java similarity index 92% rename from concurrency/Joining.java rename to tasks/Joining.java index 09406332..685a280a 100644 --- a/concurrency/Joining.java +++ b/tasks/Joining.java @@ -1,8 +1,8 @@ -// concurrency/Joining.java +// tasks/Joining.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Understanding join(). +// Understanding join() class Sleeper extends Thread { private int duration; @@ -16,7 +16,8 @@ class Sleeper extends Thread { try { sleep(duration); } catch(InterruptedException e) { - System.out.println(getName() + " was interrupted. " + + System.out.println(getName() + + " was interrupted. " + "isInterrupted(): " + isInterrupted()); return; } diff --git a/concurrency/LiftOff.java b/tasks/LiftOff.java similarity index 90% rename from concurrency/LiftOff.java rename to tasks/LiftOff.java index 871bc327..5995815d 100644 --- a/concurrency/LiftOff.java +++ b/tasks/LiftOff.java @@ -1,8 +1,8 @@ -// concurrency/LiftOff.java +// tasks/LiftOff.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of the Runnable interface. +// Demonstration of the Runnable interface public class LiftOff implements Runnable { protected int countDown = 10; // Default diff --git a/concurrency/ListComparisons.java b/tasks/ListComparisons.java similarity index 89% rename from concurrency/ListComparisons.java rename to tasks/ListComparisons.java index 1137c281..ba8e1525 100644 --- a/concurrency/ListComparisons.java +++ b/tasks/ListComparisons.java @@ -1,9 +1,9 @@ -// concurrency/ListComparisons.java +// tasks/ListComparisons.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {Args: 1 10 10} (Fast verification check during build) -// Rough comparison of thread-safe List performance. +// Rough comparison of thread-safe List performance import java.util.concurrent.*; import java.util.*; import onjava.*; @@ -16,8 +16,8 @@ abstract class ListTest extends Tester> { long result = 0; void test() { for(long i = 0; i < testCycles; i++) - for(int index = 0; index < collectionSize; index++) - result += testCollection.get(index); + for(int n = 0; n < collectionSize; n++) + result += testCollection.get(n); } void putResults() { readResult += result; @@ -27,8 +27,8 @@ abstract class ListTest extends Tester> { class Writer extends TestTask { void test() { for(long i = 0; i < testCycles; i++) - for(int index = 0; index < collectionSize; index++) - testCollection.set(index, writeData[index]); + for(int n = 0; n < collectionSize; n++) + testCollection.set(n, writeData[n]); } void putResults() { writeTime += duration; diff --git a/concurrency/MainThread.java b/tasks/MainThread.java similarity index 92% rename from concurrency/MainThread.java rename to tasks/MainThread.java index 293ffcd9..3f424569 100644 --- a/concurrency/MainThread.java +++ b/tasks/MainThread.java @@ -1,4 +1,4 @@ -// concurrency/MainThread.java +// tasks/MainThread.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/MapComparisons.java b/tasks/MapComparisons.java similarity index 82% rename from concurrency/MapComparisons.java rename to tasks/MapComparisons.java index de036d38..9a6b6a8e 100644 --- a/concurrency/MapComparisons.java +++ b/tasks/MapComparisons.java @@ -1,9 +1,9 @@ -// concurrency/MapComparisons.java +// tasks/MapComparisons.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {Args: 1 10 10} (Fast verification check during build) -// Rough comparison of thread-safe Map performance. +// Rough comparison of thread-safe Map performance import java.util.concurrent.*; import java.util.*; import onjava.*; @@ -17,8 +17,8 @@ extends Tester> { long result = 0; void test() { for(long i = 0; i < testCycles; i++) - for(int index = 0; index < collectionSize; index++) - result += testCollection.get(index); + for(int n = 0; n < collectionSize; n++) + result += testCollection.get(n); } void putResults() { readResult += result; @@ -28,8 +28,8 @@ extends Tester> { class Writer extends TestTask { void test() { for(long i = 0; i < testCycles; i++) - for(int index = 0; index < collectionSize; index++) - testCollection.put(index, writeData[index]); + for(int n = 0; n < collectionSize; n++) + testCollection.put(n, writeData[n]); } void putResults() { writeTime += duration; @@ -47,9 +47,9 @@ class SynchronizedHashMapTest extends MapTest { Map collectionInitializer() { return Collections.synchronizedMap( new HashMap<>( - MapData.map( - new CountingSupplier.Integer(), - new CountingSupplier.Integer(), + FilledMap.map( + new onjava.Count.Integer(), + new onjava.Count.Integer(), collectionSize))); } SynchronizedHashMapTest(int nReaders, int nWriters) { @@ -60,9 +60,10 @@ class SynchronizedHashMapTest extends MapTest { class ConcurrentHashMapTest extends MapTest { Map collectionInitializer() { return new ConcurrentHashMap<>( - MapData.map( - new CountingSupplier.Integer(), - new CountingSupplier.Integer(), collectionSize)); + FilledMap.map( + new onjava.Count.Integer(), + new onjava.Count.Integer(), + collectionSize)); } ConcurrentHashMapTest(int nReaders, int nWriters) { super("ConcurrentHashMap", nReaders, nWriters); diff --git a/concurrency/MoreBasicThreads.java b/tasks/MoreBasicThreads.java similarity index 92% rename from concurrency/MoreBasicThreads.java rename to tasks/MoreBasicThreads.java index 44ada4b3..0e55d71c 100644 --- a/concurrency/MoreBasicThreads.java +++ b/tasks/MoreBasicThreads.java @@ -1,8 +1,8 @@ -// concurrency/MoreBasicThreads.java +// tasks/MoreBasicThreads.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Adding more threads. +// Adding more threads public class MoreBasicThreads { public static void main(String[] args) { diff --git a/concurrency/MultiLock.java b/tasks/MultiLock.java similarity index 88% rename from concurrency/MultiLock.java rename to tasks/MultiLock.java index 795bf53a..beb71896 100644 --- a/concurrency/MultiLock.java +++ b/tasks/MultiLock.java @@ -1,8 +1,8 @@ -// concurrency/MultiLock.java +// tasks/MultiLock.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// One thread can reacquire the same lock. +// One thread can reacquire the same lock public class MultiLock { public synchronized void f1(int count) { @@ -19,7 +19,8 @@ public class MultiLock { f1(count); } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { final MultiLock multiLock = new MultiLock(); new Thread() { @Override diff --git a/concurrency/MutexEvenSupplier.java b/tasks/MutexEvenSupplier.java similarity index 89% rename from concurrency/MutexEvenSupplier.java rename to tasks/MutexEvenSupplier.java index 31b44dbf..6511e53d 100644 --- a/concurrency/MutexEvenSupplier.java +++ b/tasks/MutexEvenSupplier.java @@ -1,8 +1,8 @@ -// concurrency/MutexEvenSupplier.java +// tasks/MutexEvenSupplier.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Preventing thread collisions with mutexes. +// Preventing thread collisions with mutexes // {TimeOutDuringTesting} // {IgnoreOutput} // No output validation import java.util.concurrent.locks.*; diff --git a/concurrency/NIOInterruption.java b/tasks/NIOInterruption.java similarity index 80% rename from concurrency/NIOInterruption.java rename to tasks/NIOInterruption.java index f4f00c03..90c7ce8f 100644 --- a/concurrency/NIOInterruption.java +++ b/tasks/NIOInterruption.java @@ -1,8 +1,8 @@ -// concurrency/NIOInterruption.java +// tasks/NIOInterruption.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Interrupting a blocked NIO channel. +// Interrupting a blocked NIO channel import java.net.*; import java.nio.*; import java.nio.channels.*; @@ -24,21 +24,23 @@ class NIOBlocked implements Runnable { } catch(IOException e) { throw new RuntimeException(e); } - System.out.println("Exiting NIOBlocked.run() " + this); + System.out.println( + "Exiting NIOBlocked.run() " + this); } } public class NIOInterruption { - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); InetSocketAddress isa = new InetSocketAddress("localhost", 8080); try(ServerSocket server = new ServerSocket(8080); SocketChannel sc1 = SocketChannel.open(isa); SocketChannel sc2 = SocketChannel.open(isa)) { - Future f = exec.submit(new NIOBlocked(sc1)); - exec.execute(new NIOBlocked(sc2)); - exec.shutdown(); + Future f = es.submit(new NIOBlocked(sc1)); + es.execute(new NIOBlocked(sc2)); + es.shutdown(); TimeUnit.SECONDS.sleep(1); // Produce an interrupt via cancel: f.cancel(true); diff --git a/concurrency/NaiveExceptionHandling.java b/tasks/NaiveExceptionHandling.java similarity index 93% rename from concurrency/NaiveExceptionHandling.java rename to tasks/NaiveExceptionHandling.java index 46c86c0f..919a396d 100644 --- a/concurrency/NaiveExceptionHandling.java +++ b/tasks/NaiveExceptionHandling.java @@ -1,4 +1,4 @@ -// concurrency/NaiveExceptionHandling.java +// tasks/NaiveExceptionHandling.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/NotifyVsNotifyAll.java b/tasks/NotifyVsNotifyAll.java similarity index 91% rename from concurrency/NotifyVsNotifyAll.java rename to tasks/NotifyVsNotifyAll.java index b8c8d94a..76ad5491 100644 --- a/concurrency/NotifyVsNotifyAll.java +++ b/tasks/NotifyVsNotifyAll.java @@ -1,4 +1,4 @@ -// concurrency/NotifyVsNotifyAll.java +// tasks/NotifyVsNotifyAll.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -34,11 +34,12 @@ class Task2 implements Runnable { } public class NotifyVsNotifyAll { - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) - exec.execute(new Task()); - exec.execute(new Task2()); + es.execute(new Task()); + es.execute(new Task2()); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { boolean prod = true; @@ -63,7 +64,7 @@ public class NotifyVsNotifyAll { Task2.blocker.prodAll(); TimeUnit.MILLISECONDS.sleep(500); System.out.println("\nShutting down"); - exec.shutdownNow(); // Interrupt all tasks + es.shutdownNow(); // Interrupt all tasks } } /* Output: diff --git a/concurrency/OrnamentalGarden.java b/tasks/OrnamentalGarden.java similarity index 87% rename from concurrency/OrnamentalGarden.java rename to tasks/OrnamentalGarden.java index 2ef5c210..054acdff 100644 --- a/concurrency/OrnamentalGarden.java +++ b/tasks/OrnamentalGarden.java @@ -1,4 +1,4 @@ -// concurrency/OrnamentalGarden.java +// tasks/OrnamentalGarden.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -7,7 +7,7 @@ import java.util.*; class Count { private int count = 0; - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); // Remove the synchronized keyword to see counting fail: public synchronized int increment() { int temp = count; @@ -67,16 +67,18 @@ class Entrance implements Runnable { } public class OrnamentalGarden { - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) - exec.execute(new Entrance(i)); + es.execute(new Entrance(i)); // Run for a while, then stop and collect the data: TimeUnit.SECONDS.sleep(3); Entrance.cancel(); - exec.shutdown(); - if(!exec.awaitTermination(250, TimeUnit.MILLISECONDS)) - System.out.println("Some tasks were not terminated!"); + es.shutdown(); + if(!es.awaitTermination(250, TimeUnit.MILLISECONDS)) + System.out.println( + "Some tasks were not terminated!"); System.out.println( "Total: " + Entrance.getTotalCount()); System.out.println( diff --git a/concurrency/Philosopher.java b/tasks/Philosopher.java similarity index 94% rename from concurrency/Philosopher.java rename to tasks/Philosopher.java index 4f15a0eb..0b698642 100644 --- a/concurrency/Philosopher.java +++ b/tasks/Philosopher.java @@ -1,4 +1,4 @@ -// concurrency/Philosopher.java +// tasks/Philosopher.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -11,7 +11,7 @@ public class Philosopher implements Runnable { private Chopstick right; private final int id; private final int ponderFactor; - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); private void pause() throws InterruptedException { if(ponderFactor == 0) return; TimeUnit.MILLISECONDS.sleep( diff --git a/concurrency/PipedIO.java b/tasks/PipedIO.java similarity index 82% rename from concurrency/PipedIO.java rename to tasks/PipedIO.java index e5ac40de..34d8d67a 100644 --- a/concurrency/PipedIO.java +++ b/tasks/PipedIO.java @@ -1,4 +1,4 @@ -// concurrency/PipedIO.java +// tasks/PipedIO.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -8,7 +8,7 @@ import java.io.*; import java.util.*; class Sender implements Runnable { - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); private PipedWriter out = new PipedWriter(); public PipedWriter getPipedWriter() { return out; } @Override @@ -37,7 +37,8 @@ class Receiver implements Runnable { try { while(true) { // Blocks until characters are there: - System.out.print("Read: " + (char)in.read() + ", "); + System.out.print( + "Read: " + (char)in.read() + ", "); } } catch(IOException e) { System.out.println(e + " Receiver read exception"); @@ -46,14 +47,15 @@ class Receiver implements Runnable { } public class PipedIO { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Sender sender = new Sender(); Receiver receiver = new Receiver(sender); - ExecutorService exec = Executors.newCachedThreadPool(); - exec.execute(sender); - exec.execute(receiver); + ExecutorService es = Executors.newCachedThreadPool(); + es.execute(sender); + es.execute(receiver); TimeUnit.SECONDS.sleep(4); - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: diff --git a/concurrency/Pool.java b/tasks/Pool.java similarity index 95% rename from concurrency/Pool.java rename to tasks/Pool.java index f4c70026..5ca71d15 100644 --- a/concurrency/Pool.java +++ b/tasks/Pool.java @@ -1,9 +1,9 @@ -// concurrency/Pool.java +// tasks/Pool.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using a Semaphore inside a Pool, to restrict -// the number of tasks that can use a resource. +// the number of tasks that can use a resource import java.util.concurrent.*; import java.util.*; diff --git a/concurrency/PriorityBlockingQueueDemo.java b/tasks/PriorityBlockingQueueDemo.java similarity index 86% rename from concurrency/PriorityBlockingQueueDemo.java rename to tasks/PriorityBlockingQueueDemo.java index 499fa791..00c8c764 100644 --- a/concurrency/PriorityBlockingQueueDemo.java +++ b/tasks/PriorityBlockingQueueDemo.java @@ -1,4 +1,4 @@ -// concurrency/PriorityBlockingQueueDemo.java +// tasks/PriorityBlockingQueueDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -7,7 +7,7 @@ import java.util.*; class PrioritizedTask implements Runnable, Comparable { - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); private static int counter = 0; private final int id = counter++; private final int priority; @@ -39,7 +39,8 @@ Runnable, Comparable { public String summary() { return "(" + id + ":" + priority + ")"; } - public static class EndSentinel extends PrioritizedTask { + public static + class EndSentinel extends PrioritizedTask { private ExecutorService exec; public EndSentinel(ExecutorService e) { super(-1); // Lowest priority in this program @@ -61,7 +62,7 @@ Runnable, Comparable { } class PrioritizedTaskProducer implements Runnable { - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); private Queue queue; private ExecutorService exec; public PrioritizedTaskProducer( @@ -91,7 +92,8 @@ class PrioritizedTaskProducer implements Runnable { } catch(InterruptedException e) { // Acceptable way to exit } - System.out.println("Finished PrioritizedTaskProducer"); + System.out.println( + "Finished PrioritizedTaskProducer"); } } @@ -110,17 +112,19 @@ class PrioritizedTaskConsumer implements Runnable { } catch(InterruptedException e) { // Acceptable way to exit } - System.out.println("Finished PrioritizedTaskConsumer"); + System.out.println( + "Finished PrioritizedTaskConsumer"); } } public class PriorityBlockingQueueDemo { - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); - exec.execute(new PrioritizedTaskProducer(queue, exec)); - exec.execute(new PrioritizedTaskConsumer(queue)); + es.execute(new PrioritizedTaskProducer(queue, es)); + es.execute(new PrioritizedTaskConsumer(queue)); } } /* Output: (First and last 12 Lines) diff --git a/concurrency/ReaderWriterList.java b/tasks/ReaderWriterList.java similarity index 91% rename from concurrency/ReaderWriterList.java rename to tasks/ReaderWriterList.java index 72613860..d54584d0 100644 --- a/concurrency/ReaderWriterList.java +++ b/tasks/ReaderWriterList.java @@ -1,4 +1,4 @@ -// concurrency/ReaderWriterList.java +// tasks/ReaderWriterList.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -37,7 +37,8 @@ public class ReaderWriterList { rlock.unlock(); } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { new ReaderWriterListTest(30, 1); } } @@ -45,7 +46,7 @@ public class ReaderWriterList { class ReaderWriterListTest { ExecutorService exec = Executors.newCachedThreadPool(); private final static int SIZE = 100; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); private ReaderWriterList list = new ReaderWriterList<>(SIZE, 0); private class Writer implements Runnable { @@ -59,7 +60,8 @@ class ReaderWriterListTest { } catch(InterruptedException e) { // Acceptable way to exit } - System.out.println("Writer finished, shutting down"); + System.out.println( + "Writer finished, shutting down"); exec.shutdownNow(); } } diff --git a/concurrency/ResponsiveUI.java b/tasks/ResponsiveUI.java similarity index 86% rename from concurrency/ResponsiveUI.java rename to tasks/ResponsiveUI.java index 886cb194..732dc782 100644 --- a/concurrency/ResponsiveUI.java +++ b/tasks/ResponsiveUI.java @@ -1,8 +1,8 @@ -// concurrency/ResponsiveUI.java +// tasks/ResponsiveUI.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// User interface responsiveness. +// User interface responsiveness // {TimeOutDuringTesting} class UnresponsiveUI { @@ -26,7 +26,8 @@ public class ResponsiveUI extends Thread { d += (Math.PI + Math.E) / d; } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { //- new UnresponsiveUI(); // Must kill this process new ResponsiveUI(); System.in.read(); diff --git a/concurrency/Restaurant.java b/tasks/Restaurant.java similarity index 94% rename from concurrency/Restaurant.java rename to tasks/Restaurant.java index 1fd4b111..caf37d28 100644 --- a/concurrency/Restaurant.java +++ b/tasks/Restaurant.java @@ -1,8 +1,8 @@ -// concurrency/Restaurant.java +// tasks/Restaurant.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// The producer-consumer approach to task cooperation. +// The producer-consumer approach to task cooperation import java.util.concurrent.*; class Meal { @@ -27,7 +27,7 @@ class WaitPerson implements Runnable { "Waitperson got " + restaurant.meal); synchronized(restaurant.chef) { restaurant.meal = null; - restaurant.chef.notifyAll(); // Ready for another + restaurant.chef.notifyAll(); // Ready for more } } } catch(InterruptedException e) { diff --git a/concurrency/SelfManaged.java b/tasks/SelfManaged.java similarity index 92% rename from concurrency/SelfManaged.java rename to tasks/SelfManaged.java index a233712b..e6f5e246 100644 --- a/concurrency/SelfManaged.java +++ b/tasks/SelfManaged.java @@ -1,8 +1,8 @@ -// concurrency/SelfManaged.java +// tasks/SelfManaged.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A Runnable containing its own driver Thread. +// A Runnable containing its own driver Thread public class SelfManaged implements Runnable { private int countDown = 5; diff --git a/concurrency/SemaphoreDemo.java b/tasks/SemaphoreDemo.java similarity index 91% rename from concurrency/SemaphoreDemo.java rename to tasks/SemaphoreDemo.java index f960b37e..ad745e73 100644 --- a/concurrency/SemaphoreDemo.java +++ b/tasks/SemaphoreDemo.java @@ -1,4 +1,4 @@ -// concurrency/SemaphoreDemo.java +// tasks/SemaphoreDemo.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -37,18 +37,19 @@ public class SemaphoreDemo { public static void main(String[] args) throws Exception { final Pool pool = new Pool<>(Fat.class, SIZE); - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < SIZE; i++) - exec.execute(new CheckoutTask<>(pool)); + es.execute(new CheckoutTask<>(pool)); System.out.println("All CheckoutTasks created"); List list = new ArrayList<>(); for(int i = 0; i < SIZE; i++) { Fat f = pool.checkOut(); - System.out.print(i + ": main() thread checked out "); + System.out.print( + i + ": main() thread checked out "); f.operation(); list.add(f); } - Future blocked = exec.submit(() -> { + Future blocked = es.submit(() -> { try { // Semaphore prevents additional checkout, // so call is blocked: @@ -64,7 +65,7 @@ public class SemaphoreDemo { pool.checkIn(f); for(Fat f : list) pool.checkIn(f); // Second checkIn ignored - exec.shutdown(); + es.shutdown(); } } /* Output: (First and last 10 Lines) diff --git a/concurrency/SerialNumberChecker.java b/tasks/SerialNumberChecker.java similarity index 93% rename from concurrency/SerialNumberChecker.java rename to tasks/SerialNumberChecker.java index ba816060..5c17371c 100644 --- a/concurrency/SerialNumberChecker.java +++ b/tasks/SerialNumberChecker.java @@ -1,9 +1,9 @@ -// concurrency/SerialNumberChecker.java +// tasks/SerialNumberChecker.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Operations that might seem safe are not, -// when threads are present. +// when threads are present // {Args: 4} import java.util.concurrent.*; @@ -52,7 +52,8 @@ public class SerialNumberChecker { } } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { for(int i = 0; i < SIZE; i++) exec.execute(new SerialChecker()); // Stop after n seconds if there's an argument: diff --git a/concurrency/SerialNumberSupplier.java b/tasks/SerialNumberSupplier.java similarity index 89% rename from concurrency/SerialNumberSupplier.java rename to tasks/SerialNumberSupplier.java index 06502fad..a73ae120 100644 --- a/concurrency/SerialNumberSupplier.java +++ b/tasks/SerialNumberSupplier.java @@ -1,4 +1,4 @@ -// concurrency/SerialNumberSupplier.java +// tasks/SerialNumberSupplier.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/SettingDefaultHandler.java b/tasks/SettingDefaultHandler.java similarity index 76% rename from concurrency/SettingDefaultHandler.java rename to tasks/SettingDefaultHandler.java index a03b5b3b..8215d269 100644 --- a/concurrency/SettingDefaultHandler.java +++ b/tasks/SettingDefaultHandler.java @@ -1,4 +1,4 @@ -// concurrency/SettingDefaultHandler.java +// tasks/SettingDefaultHandler.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. @@ -9,8 +9,8 @@ public class SettingDefaultHandler { public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler( new MyUncaughtExceptionHandler()); - ExecutorService exec = Executors.newCachedThreadPool(); - exec.execute(new ExceptionThread()); + ExecutorService es = Executors.newCachedThreadPool(); + es.execute(new ExceptionThread()); } } /* Output: diff --git a/concurrency/SimpleDaemons.java b/tasks/SimpleDaemons.java similarity index 89% rename from concurrency/SimpleDaemons.java rename to tasks/SimpleDaemons.java index 880e6af0..6906275f 100644 --- a/concurrency/SimpleDaemons.java +++ b/tasks/SimpleDaemons.java @@ -1,8 +1,8 @@ -// concurrency/SimpleDaemons.java +// tasks/SimpleDaemons.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Daemon threads don't prevent the program from ending. +// Daemon threads don't prevent the program from ending import java.util.concurrent.*; public class SimpleDaemons implements Runnable { @@ -18,7 +18,8 @@ public class SimpleDaemons implements Runnable { System.out.println("sleep() interrupted"); } } - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { for(int i = 0; i < 10; i++) { Thread daemon = new Thread(new SimpleDaemons()); daemon.setDaemon(true); // Must call before start() diff --git a/concurrency/SimpleMicroBenchmark.java b/tasks/SimpleMicroBenchmark.java similarity index 90% rename from concurrency/SimpleMicroBenchmark.java rename to tasks/SimpleMicroBenchmark.java index b6781219..c394494f 100644 --- a/concurrency/SimpleMicroBenchmark.java +++ b/tasks/SimpleMicroBenchmark.java @@ -1,8 +1,8 @@ -// concurrency/SimpleMicroBenchmark.java +// tasks/SimpleMicroBenchmark.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// The dangers of microbenchmarking. +// The dangers of microbenchmarking import java.util.concurrent.locks.*; abstract class Incrementable { @@ -38,7 +38,8 @@ public class SimpleMicroBenchmark { public static void main(String[] args) { long synchTime = test(new SynchronizingTest()); long lockTime = test(new LockingTest()); - System.out.printf("synchronized: %1$10d\n", synchTime); + System.out.printf( + "synchronized: %1$10d\n", synchTime); System.out.printf("Lock: %1$10d\n", lockTime); System.out.printf("Lock/synchronized = %1$.3f", (double)lockTime/(double)synchTime); diff --git a/concurrency/SimplePriorities.java b/tasks/SimplePriorities.java similarity index 89% rename from concurrency/SimplePriorities.java rename to tasks/SimplePriorities.java index 256dd1b6..0bc001dc 100644 --- a/concurrency/SimplePriorities.java +++ b/tasks/SimplePriorities.java @@ -1,8 +1,8 @@ -// concurrency/SimplePriorities.java +// tasks/SimplePriorities.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Shows thread priorities. +// Shows thread priorities import java.util.concurrent.*; public class SimplePriorities implements Runnable { @@ -31,13 +31,13 @@ public class SimplePriorities implements Runnable { } } public static void main(String[] args) { - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) - exec.execute( + es.execute( new SimplePriorities(Thread.MIN_PRIORITY)); - exec.execute( + es.execute( new SimplePriorities(Thread.MAX_PRIORITY)); - exec.shutdown(); + es.shutdown(); } } /* Output: (First 10 Lines) diff --git a/concurrency/SimpleThread.java b/tasks/SimpleThread.java similarity index 92% rename from concurrency/SimpleThread.java rename to tasks/SimpleThread.java index 46e76887..9d1d5d3c 100644 --- a/concurrency/SimpleThread.java +++ b/tasks/SimpleThread.java @@ -1,8 +1,8 @@ -// concurrency/SimpleThread.java +// tasks/SimpleThread.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Inheriting directly from the Thread class. +// Inheriting directly from the Thread class public class SimpleThread extends Thread { private int countDown = 5; diff --git a/concurrency/SingleThreadExecutor.java b/tasks/SingleThreadExecutor.java similarity index 95% rename from concurrency/SingleThreadExecutor.java rename to tasks/SingleThreadExecutor.java index ac3fc202..3a4b579b 100644 --- a/concurrency/SingleThreadExecutor.java +++ b/tasks/SingleThreadExecutor.java @@ -1,4 +1,4 @@ -// concurrency/SingleThreadExecutor.java +// tasks/SingleThreadExecutor.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/SleepingTask.java b/tasks/SleepingTask.java similarity index 84% rename from concurrency/SleepingTask.java rename to tasks/SleepingTask.java index 7cdb10a7..d9d98346 100644 --- a/concurrency/SleepingTask.java +++ b/tasks/SleepingTask.java @@ -1,8 +1,8 @@ -// concurrency/SleepingTask.java +// tasks/SleepingTask.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Calling sleep() to pause for a while. +// Calling sleep() to pause for a while import java.util.concurrent.*; public class SleepingTask extends LiftOff { @@ -21,10 +21,10 @@ public class SleepingTask extends LiftOff { } } public static void main(String[] args) { - ExecutorService exec = Executors.newCachedThreadPool(); + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) - exec.execute(new SleepingTask()); - exec.shutdown(); + es.execute(new SleepingTask()); + es.shutdown(); } } /* Output: diff --git a/concurrency/SyncObject.java b/tasks/SyncObject.java similarity index 92% rename from concurrency/SyncObject.java rename to tasks/SyncObject.java index 1d38ab1d..009fdb61 100644 --- a/concurrency/SyncObject.java +++ b/tasks/SyncObject.java @@ -1,8 +1,8 @@ -// concurrency/SyncObject.java +// tasks/SyncObject.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Synchronizing on another object. +// Synchronizing on another object class DualSynch { private Object syncObject = new Object(); diff --git a/concurrency/SynchronizationComparisons.java b/tasks/SynchronizationComparisons.java similarity index 97% rename from concurrency/SynchronizationComparisons.java rename to tasks/SynchronizationComparisons.java index 76e799bc..841dcc05 100644 --- a/concurrency/SynchronizationComparisons.java +++ b/tasks/SynchronizationComparisons.java @@ -1,9 +1,9 @@ -// concurrency/SynchronizationComparisons.java +// tasks/SynchronizationComparisons.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Comparing the performance of explicit Locks -// and Atomics versus the synchronized keyword. +// and Atomics versus the synchronized keyword import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; @@ -24,7 +24,7 @@ abstract class Accumulator { protected final static int SIZE = 100000; protected static int[] preLoaded = new int[SIZE]; static { // Load the array of random numbers: - Random rand = new Random(47); + SplittableRandom rand = new SplittableRandom(47); for(int i = 0; i < SIZE; i++) preLoaded[i] = rand.nextInt(); } diff --git a/concurrency/TestBlockingQueues.java b/tasks/TestBlockingQueues.java similarity index 98% rename from concurrency/TestBlockingQueues.java rename to tasks/TestBlockingQueues.java index d1cac404..d47d63c2 100644 --- a/concurrency/TestBlockingQueues.java +++ b/tasks/TestBlockingQueues.java @@ -1,4 +1,4 @@ -// concurrency/TestBlockingQueues.java +// tasks/TestBlockingQueues.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. diff --git a/concurrency/Tester.java b/tasks/Tester.java similarity index 92% rename from concurrency/Tester.java rename to tasks/Tester.java index 567b791d..935c50e2 100644 --- a/concurrency/Tester.java +++ b/tasks/Tester.java @@ -1,8 +1,8 @@ -// concurrency/Tester.java +// tasks/Tester.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Framework to test performance of concurrency collections. +// Performance test framework for concurrency collections import java.util.concurrent.*; import onjava.*; @@ -28,8 +28,7 @@ public abstract class Tester { nReaders + "r " + nWriters + "w"; this.nReaders = nReaders; this.nWriters = nWriters; - writeData = Generated.array(Integer.class, - new RandomSupplier.Integer(), collectionSize); + writeData = new Rand.Integer().array(collectionSize); for(int i = 0; i < testReps; i++) { runTest(); readTime = 0; diff --git a/concurrency/ThreadLocalVariableHolder.java b/tasks/ThreadLocalVariableHolder.java similarity index 78% rename from concurrency/ThreadLocalVariableHolder.java rename to tasks/ThreadLocalVariableHolder.java index d91b1f6f..6634f2bb 100644 --- a/concurrency/ThreadLocalVariableHolder.java +++ b/tasks/ThreadLocalVariableHolder.java @@ -1,8 +1,8 @@ -// concurrency/ThreadLocalVariableHolder.java +// tasks/ThreadLocalVariableHolder.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Automatically giving each thread its own storage. +// Automatically giving each thread its own storage import java.util.concurrent.*; import java.util.*; @@ -27,7 +27,7 @@ class Accessor implements Runnable { public class ThreadLocalVariableHolder { private static ThreadLocal value = new ThreadLocal() { - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); @Override protected synchronized Integer initialValue() { return rand.nextInt(10000); @@ -37,12 +37,13 @@ public class ThreadLocalVariableHolder { value.set(value.get() + 1); } public static int get() { return value.get(); } - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) - exec.execute(new Accessor(i)); + es.execute(new Accessor(i)); TimeUnit.SECONDS.sleep(3); // Run for a while - exec.shutdownNow(); // All Accessors will quit + es.shutdownNow(); // All Accessors will quit } } /* Output: (First and last 10 Lines) diff --git a/concurrency/ThreadVariations.java b/tasks/ThreadVariations.java similarity index 98% rename from concurrency/ThreadVariations.java rename to tasks/ThreadVariations.java index ae83ca1d..3c852207 100644 --- a/concurrency/ThreadVariations.java +++ b/tasks/ThreadVariations.java @@ -1,8 +1,8 @@ -// concurrency/ThreadVariations.java +// tasks/ThreadVariations.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Creating threads with inner classes. +// Creating threads with inner classes import java.util.concurrent.*; // Using a named inner class: diff --git a/concurrency/ToastOMatic.java b/tasks/ToastOMatic.java similarity index 90% rename from concurrency/ToastOMatic.java rename to tasks/ToastOMatic.java index 43fd69d5..45dfb097 100644 --- a/concurrency/ToastOMatic.java +++ b/tasks/ToastOMatic.java @@ -1,8 +1,8 @@ -// concurrency/ToastOMatic.java +// tasks/ToastOMatic.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// A toaster that uses queues. +// A toaster that uses queues import java.util.concurrent.*; import java.util.*; @@ -26,7 +26,7 @@ class ToastQueue extends LinkedBlockingQueue {} class Toaster implements Runnable { private ToastQueue toastQueue; private int count = 0; - private Random rand = new Random(47); + private SplittableRandom rand = new SplittableRandom(47); public Toaster(ToastQueue tq) { toastQueue = tq; } @Override public void run() { @@ -74,7 +74,8 @@ class Butterer implements Runnable { // Apply jam to buttered toast: class Jammer implements Runnable { private ToastQueue butteredQueue, finishedQueue; - public Jammer(ToastQueue buttered, ToastQueue finished) { + public + Jammer(ToastQueue buttered, ToastQueue finished) { butteredQueue = buttered; finishedQueue = finished; } @@ -125,17 +126,18 @@ class Eater implements Runnable { } public class ToastOMatic { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { ToastQueue dryQueue = new ToastQueue(), butteredQueue = new ToastQueue(), finishedQueue = new ToastQueue(); - ExecutorService exec = Executors.newCachedThreadPool(); - exec.execute(new Toaster(dryQueue)); - exec.execute(new Butterer(dryQueue, butteredQueue)); - exec.execute(new Jammer(butteredQueue, finishedQueue)); - exec.execute(new Eater(finishedQueue)); + ExecutorService es = Executors.newCachedThreadPool(); + es.execute(new Toaster(dryQueue)); + es.execute(new Butterer(dryQueue, butteredQueue)); + es.execute(new Jammer(butteredQueue, finishedQueue)); + es.execute(new Eater(finishedQueue)); TimeUnit.SECONDS.sleep(5); - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: diff --git a/concurrency/build.xml b/tasks/build.xml similarity index 84% rename from concurrency/build.xml rename to tasks/build.xml index 9416ffbc..d321f073 100644 --- a/concurrency/build.xml +++ b/tasks/build.xml @@ -1,7 +1,7 @@ - + @@ -20,7 +20,7 @@ - + @@ -28,7 +28,7 @@ - + @@ -68,9 +68,9 @@ - - - + + + @@ -87,7 +87,7 @@ - + @@ -95,7 +95,7 @@ - + @@ -135,9 +135,9 @@ - - - + + + diff --git a/concurrency/restaurant2/RestaurantWithQueues.java b/tasks/restaurant2/RestaurantWithQueues.java similarity index 91% rename from concurrency/restaurant2/RestaurantWithQueues.java rename to tasks/restaurant2/RestaurantWithQueues.java index 7b02202b..c58972ba 100644 --- a/concurrency/restaurant2/RestaurantWithQueues.java +++ b/tasks/restaurant2/RestaurantWithQueues.java @@ -1,9 +1,9 @@ -// concurrency/restaurant2/RestaurantWithQueues.java +// tasks/restaurant2/RestaurantWithQueues.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {Args: 5} -package concurrency.restaurant2; +package tasks.restaurant2; import enums.menu.*; import java.util.concurrent.*; import java.util.*; @@ -88,14 +88,17 @@ class WaitPerson implements Runnable { private final Restaurant restaurant; BlockingQueue filledOrders = new LinkedBlockingQueue<>(); - public WaitPerson(Restaurant rest) { restaurant = rest; } + public WaitPerson(Restaurant rest) { + restaurant = rest; + } public void placeOrder(Customer cust, Food food) { try { // Shouldn't actually block because this is // a LinkedBlockingQueue with no size limit: restaurant.orders.put(new Order(cust, this, food)); } catch(InterruptedException e) { - System.out.println(this + " placeOrder interrupted"); + System.out.println( + this + " placeOrder interrupted"); } } @Override @@ -124,7 +127,7 @@ class Chef implements Runnable { private static int counter = 0; private final int id = counter++; private final Restaurant restaurant; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); public Chef(Restaurant rest) { restaurant = rest; } @Override public void run() { @@ -152,7 +155,7 @@ class Restaurant implements Runnable { new ArrayList<>(); private List chefs = new ArrayList<>(); private ExecutorService exec; - private static Random rand = new Random(47); + private static SplittableRandom rand = new SplittableRandom(47); BlockingQueue orders = new LinkedBlockingQueue<>(); public Restaurant(ExecutorService e, int nWaitPersons, @@ -188,17 +191,18 @@ class Restaurant implements Runnable { } public class RestaurantWithQueues { - public static void main(String[] args) throws Exception { - ExecutorService exec = Executors.newCachedThreadPool(); - Restaurant restaurant = new Restaurant(exec, 5, 2); - exec.execute(restaurant); + public static void + main(String[] args) throws Exception { + ExecutorService es = Executors.newCachedThreadPool(); + Restaurant restaurant = new Restaurant(es, 5, 2); + es.execute(restaurant); if(args.length > 0) // Optional argument TimeUnit.SECONDS.sleep(new Integer(args[0])); else { System.out.println("Press 'Enter' to quit"); System.in.read(); } - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: (First and last 10 Lines) diff --git a/concurrency/waxomatic/WaxOMatic.java b/tasks/waxomatic/WaxOMatic.java similarity index 85% rename from concurrency/waxomatic/WaxOMatic.java rename to tasks/waxomatic/WaxOMatic.java index b0056da8..42d15c7e 100644 --- a/concurrency/waxomatic/WaxOMatic.java +++ b/tasks/waxomatic/WaxOMatic.java @@ -1,9 +1,9 @@ -// concurrency/waxomatic/WaxOMatic.java +// tasks/waxomatic/WaxOMatic.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Basic task cooperation. -package concurrency.waxomatic; +// Basic task cooperation +package tasks.waxomatic; import java.util.concurrent.*; class Car { @@ -67,13 +67,14 @@ class WaxOff implements Runnable { } public class WaxOMatic { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Car car = new Car(); - ExecutorService exec = Executors.newCachedThreadPool(); - exec.execute(new WaxOff(car)); - exec.execute(new WaxOn(car)); + ExecutorService es = Executors.newCachedThreadPool(); + es.execute(new WaxOff(car)); + es.execute(new WaxOn(car)); TimeUnit.SECONDS.sleep(5); // Run for a while... - exec.shutdownNow(); // Interrupt all tasks + es.shutdownNow(); // Interrupt all tasks } } /* Output: diff --git a/concurrency/waxomatic2/WaxOMatic2.java b/tasks/waxomatic2/WaxOMatic2.java similarity index 83% rename from concurrency/waxomatic2/WaxOMatic2.java rename to tasks/waxomatic2/WaxOMatic2.java index 5db01e44..2c9ed53b 100644 --- a/concurrency/waxomatic2/WaxOMatic2.java +++ b/tasks/waxomatic2/WaxOMatic2.java @@ -1,9 +1,9 @@ -// concurrency/waxomatic2/WaxOMatic2.java +// tasks/waxomatic2/WaxOMatic2.java // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using Lock and Condition objects. -package concurrency.waxomatic2; +// Using Lock and Condition objects +package tasks.waxomatic2; import java.util.concurrent.*; import java.util.concurrent.locks.*; @@ -29,7 +29,8 @@ class Car { lock.unlock(); } } - public void waitForWaxing() throws InterruptedException { + public void + waitForWaxing() throws InterruptedException { lock.lock(); try { while(waxOn == false) @@ -38,7 +39,8 @@ class Car { lock.unlock(); } } - public void waitForBuffing() throws InterruptedException{ + public void + waitForBuffing() throws InterruptedException{ lock.lock(); try { while(waxOn == true) @@ -88,13 +90,14 @@ class WaxOff implements Runnable { } public class WaxOMatic2 { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Car car = new Car(); - ExecutorService exec = Executors.newCachedThreadPool(); - exec.execute(new WaxOff(car)); - exec.execute(new WaxOn(car)); + ExecutorService es = Executors.newCachedThreadPool(); + es.execute(new WaxOff(car)); + es.execute(new WaxOn(car)); TimeUnit.SECONDS.sleep(5); - exec.shutdownNow(); + es.shutdownNow(); } } /* Output: diff --git a/typeinfo/AnonymousImplementation.java b/typeinfo/AnonymousImplementation.java index cf716399..4c98347c 100644 --- a/typeinfo/AnonymousImplementation.java +++ b/typeinfo/AnonymousImplementation.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://mindviewinc.com/Books/OnJava/ for more book information. -// Anonymous inner classes can't hide from reflection. +// Anonymous inner classes can't hide from reflection import typeinfo.interfacea.*; class AnonymousA { @@ -28,7 +28,8 @@ class AnonymousA { } public class AnonymousImplementation { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { A a = AnonymousA.makeA(); a.f(); System.out.println(a.getClass().getName()); diff --git a/typeinfo/ClassInitialization.java b/typeinfo/ClassInitialization.java index a129201a..0c3080ba 100644 --- a/typeinfo/ClassInitialization.java +++ b/typeinfo/ClassInitialization.java @@ -29,7 +29,8 @@ class Initable3 { public class ClassInitialization { public static Random rand = new Random(47); - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Class initable = Initable.class; System.out.println("After creating Initable ref"); // Does not trigger initialization: diff --git a/typeinfo/HiddenImplementation.java b/typeinfo/HiddenImplementation.java index 1c5d709c..08b75a97 100644 --- a/typeinfo/HiddenImplementation.java +++ b/typeinfo/HiddenImplementation.java @@ -2,13 +2,14 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Sneaking around package hiding. +// Sneaking around package hiding import typeinfo.interfacea.*; import typeinfo.packageaccess.*; import java.lang.reflect.*; public class HiddenImplementation { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { A a = HiddenC.makeA(); a.f(); System.out.println(a.getClass().getName()); @@ -24,7 +25,8 @@ public class HiddenImplementation { callHiddenMethod(a, "v"); callHiddenMethod(a, "w"); } - static void callHiddenMethod(Object a, String methodName) + static void + callHiddenMethod(Object a, String methodName) throws Exception { Method g = a.getClass().getDeclaredMethod(methodName); g.setAccessible(true); diff --git a/typeinfo/InnerImplementation.java b/typeinfo/InnerImplementation.java index 56a72ac9..4dfa5725 100644 --- a/typeinfo/InnerImplementation.java +++ b/typeinfo/InnerImplementation.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://mindviewinc.com/Books/OnJava/ for more book information. -// Private inner classes can't hide from reflection. +// Private inner classes can't hide from reflection import typeinfo.interfacea.*; class InnerA { @@ -27,7 +27,8 @@ class InnerA { } public class InnerImplementation { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { A a = InnerA.makeA(); a.f(); System.out.println(a.getClass().getName()); diff --git a/typeinfo/InterfaceViolation.java b/typeinfo/InterfaceViolation.java index 38c645a0..8d4c16f3 100644 --- a/typeinfo/InterfaceViolation.java +++ b/typeinfo/InterfaceViolation.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://mindviewinc.com/Books/OnJava/ for more book information. -// Sneaking around an interface. +// Sneaking around an interface import typeinfo.interfacea.*; class B implements A { diff --git a/typeinfo/ModifyingPrivateFields.java b/typeinfo/ModifyingPrivateFields.java index 4c502a00..a9bf54aa 100644 --- a/typeinfo/ModifyingPrivateFields.java +++ b/typeinfo/ModifyingPrivateFields.java @@ -15,8 +15,10 @@ class WithPrivateFinalField { } public class ModifyingPrivateFields { - public static void main(String[] args) throws Exception { - WithPrivateFinalField pf = new WithPrivateFinalField(); + public static void + main(String[] args) throws Exception { + WithPrivateFinalField pf = + new WithPrivateFinalField(); System.out.println(pf); Field f = pf.getClass().getDeclaredField("i"); f.setAccessible(true); diff --git a/typeinfo/NullRobot.java b/typeinfo/NullRobot.java index 0aeb6ecb..2713dcfc 100644 --- a/typeinfo/NullRobot.java +++ b/typeinfo/NullRobot.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using a dynamic proxy to create an Optional. +// Using a dynamic proxy to create an Optional import java.lang.reflect.*; import java.util.*; import java.util.stream.*; diff --git a/typeinfo/Operation.java b/typeinfo/Operation.java index 294349ee..f6c94da7 100644 --- a/typeinfo/Operation.java +++ b/typeinfo/Operation.java @@ -7,7 +7,8 @@ import java.util.function.*; public class Operation { public final Supplier description; public final Runnable command; - public Operation (Supplier descr, Runnable cmd) { + public + Operation (Supplier descr, Runnable cmd) { description = descr; command = cmd; } diff --git a/typeinfo/Person.java b/typeinfo/Person.java index 04662cf8..ec4f355d 100644 --- a/typeinfo/Person.java +++ b/typeinfo/Person.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using Optional with regular classes. +// Using Optional with regular classes import onjava.*; import java.util.*; @@ -12,7 +12,8 @@ class Person { public final Optional address; // etc. public final boolean empty; - public Person(String first, String last, String address){ + public + Person(String first, String last, String address) { this.first = Optional.ofNullable(first); this.last = Optional.ofNullable(last); this.address = Optional.ofNullable(address); diff --git a/typeinfo/PetCount.java b/typeinfo/PetCount.java index e82e3902..475cdc8f 100644 --- a/typeinfo/PetCount.java +++ b/typeinfo/PetCount.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using instanceof. +// Using instanceof import typeinfo.pets.*; import java.util.*; diff --git a/typeinfo/PetCount3.java b/typeinfo/PetCount3.java index 0d77efb9..7fcaa0da 100644 --- a/typeinfo/PetCount3.java +++ b/typeinfo/PetCount3.java @@ -11,7 +11,7 @@ public class PetCount3 { static class Counter extends LinkedHashMap, Integer> { public Counter() { - super(MapData.map(LiteralPetCreator.allTypes, 0)); + super(FilledMap.map(LiteralPetCreator.allTypes, 0)); } public void count(Pet pet) { // Class.isInstance() eliminates instanceofs: diff --git a/typeinfo/RegisteredFactories.java b/typeinfo/RegisteredFactories.java index ace2d2ce..20859977 100644 --- a/typeinfo/RegisteredFactories.java +++ b/typeinfo/RegisteredFactories.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://mindviewinc.com/Books/OnJava/ for more book information. -// Registering Factories in the base class. +// Registering Factories in the base class import java.util.*; import java.util.function.*; import java.util.stream.*; diff --git a/typeinfo/SelectingMethods.java b/typeinfo/SelectingMethods.java index aedf572f..6c7b4df7 100644 --- a/typeinfo/SelectingMethods.java +++ b/typeinfo/SelectingMethods.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://mindviewinc.com/Books/OnJava/ for more book information. -// Looking for particular methods in a dynamic proxy. +// Looking for particular methods in a dynamic proxy import java.lang.reflect.*; class MethodSelector implements InvocationHandler { @@ -43,10 +43,11 @@ class Implementation implements SomeMethods { class SelectingMethods { public static void main(String[] args) { - SomeMethods proxy= (SomeMethods)Proxy.newProxyInstance( - SomeMethods.class.getClassLoader(), - new Class[]{ SomeMethods.class }, - new MethodSelector(new Implementation())); + SomeMethods proxy = + (SomeMethods)Proxy.newProxyInstance( + SomeMethods.class.getClassLoader(), + new Class[]{ SomeMethods.class }, + new MethodSelector(new Implementation())); proxy.boring1(); proxy.boring2(); proxy.interesting("bonobo"); diff --git a/typeinfo/ShowMethods.java b/typeinfo/ShowMethods.java index 6a22f722..bd99b43a 100644 --- a/typeinfo/ShowMethods.java +++ b/typeinfo/ShowMethods.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Using reflection to show all the methods of a class, -// even if the methods are defined in the base class. +// even if the methods are defined in the base class // {Args: ShowMethods} import java.lang.reflect.*; import java.util.regex.*; @@ -37,8 +37,8 @@ public class ShowMethods { } else { for(Method method : methods) if(method.toString().contains(args[1])) { - System.out.println( - p.matcher(method.toString()).replaceAll("")); + System.out.println(p.matcher( + method.toString()).replaceAll("")); lines++; } for(Constructor ctor : ctors) diff --git a/typeinfo/SimpleProxyDemo.java b/typeinfo/SimpleProxyDemo.java index e2f2845f..c6fd64f8 100644 --- a/typeinfo/SimpleProxyDemo.java +++ b/typeinfo/SimpleProxyDemo.java @@ -31,7 +31,8 @@ class SimpleProxy implements Interface { } @Override public void somethingElse(String arg) { - System.out.println("SimpleProxy somethingElse " + arg); + System.out.println( + "SimpleProxy somethingElse " + arg); proxied.somethingElse(arg); } } diff --git a/typeinfo/SweetShop.java b/typeinfo/SweetShop.java index 0773cbd8..7d67210c 100644 --- a/typeinfo/SweetShop.java +++ b/typeinfo/SweetShop.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://mindviewinc.com/Books/OnJava/ for more book information. -// Examination of the way the class loader works. +// Examination of the way the class loader works class Cookie { static { System.out.println("Loading Cookie"); } diff --git a/typeinfo/pets/Individual.java b/typeinfo/pets/Individual.java index 1835f631..23b06a23 100644 --- a/typeinfo/pets/Individual.java +++ b/typeinfo/pets/Individual.java @@ -4,7 +4,8 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package typeinfo.pets; -public class Individual implements Comparable { +public class +Individual implements Comparable { private static long counter = 0; private final long id = counter++; private String name; diff --git a/typeinfo/pets/LiteralPetCreator.java b/typeinfo/pets/LiteralPetCreator.java index 40c60974..ffdafe74 100644 --- a/typeinfo/pets/LiteralPetCreator.java +++ b/typeinfo/pets/LiteralPetCreator.java @@ -2,18 +2,20 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Using class literals. +// Using class literals package typeinfo.pets; import java.util.*; public class LiteralPetCreator extends PetCreator { // No try block needed. @SuppressWarnings("unchecked") - public static final List> allTypes = + public static + final List> allTypes = 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)); + 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), diff --git a/typeinfo/pets/PetCreator.java b/typeinfo/pets/PetCreator.java index ec0c6dd0..973f2417 100644 --- a/typeinfo/pets/PetCreator.java +++ b/typeinfo/pets/PetCreator.java @@ -2,12 +2,13 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Creates random sequences of Pets. +// Creates random sequences of Pets package typeinfo.pets; import java.util.*; import java.util.function.*; -public abstract class PetCreator implements Supplier { +public abstract +class PetCreator implements Supplier { private Random rand = new Random(47); // The List of the different types of Pet to create: public abstract List> types(); diff --git a/typeinfo/pets/Pets.java b/typeinfo/pets/Pets.java index c092db00..5d84b42f 100644 --- a/typeinfo/pets/Pets.java +++ b/typeinfo/pets/Pets.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://mindviewinc.com/Books/OnJava/ for more book information. -// Facade to produce a default PetCreator. +// Facade to produce a default PetCreator package typeinfo.pets; import java.util.*; import java.util.stream.*; diff --git a/typeinfo/toys/GenericToyTest.java b/typeinfo/toys/GenericToyTest.java index 53ebed2a..73492fa5 100644 --- a/typeinfo/toys/GenericToyTest.java +++ b/typeinfo/toys/GenericToyTest.java @@ -2,11 +2,12 @@ // (c)2016 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. -// Testing class Class. +// Testing class Class package typeinfo.toys; public class GenericToyTest { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { Class ftClass = FancyToy.class; // Produces exact type: FancyToy fancyToy = ftClass.newInstance(); diff --git a/typeinfo/toys/ToyTest.java b/typeinfo/toys/ToyTest.java index a97e6ff5..247577ea 100644 --- a/typeinfo/toys/ToyTest.java +++ b/typeinfo/toys/ToyTest.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://mindviewinc.com/Books/OnJava/ for more book information. -// Testing class Class. +// Testing class Class package typeinfo.toys; interface HasBatteries {} diff --git a/ui/BorderLayout1.java b/ui/BorderLayout1.java index 1bf76005..6236f4e9 100644 --- a/ui/BorderLayout1.java +++ b/ui/BorderLayout1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates BorderLayout. +// Demonstrates BorderLayout import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/Borders.java b/ui/Borders.java index acd6a7de..55bf25c3 100644 --- a/ui/Borders.java +++ b/ui/Borders.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://mindviewinc.com/Books/OnJava/ for more book information. -// Different Swing borders. +// Different Swing borders import javax.swing.*; import javax.swing.border.*; import java.awt.*; diff --git a/ui/Button1.java b/ui/Button1.java index 19d98933..7f49c9fe 100644 --- a/ui/Button1.java +++ b/ui/Button1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Putting buttons on a Swing application. +// Putting buttons on a Swing application import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/Button2.java b/ui/Button2.java index fdcac1d1..2762bf37 100644 --- a/ui/Button2.java +++ b/ui/Button2.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://mindviewinc.com/Books/OnJava/ for more book information. -// Responding to button presses. +// Responding to button presses import javax.swing.*; import java.awt.*; import java.awt.event.*; diff --git a/ui/Button2b.java b/ui/Button2b.java index 3eb08cc4..ebb09dc3 100644 --- a/ui/Button2b.java +++ b/ui/Button2b.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using anonymous inner classes. +// Using anonymous inner classes import javax.swing.*; import java.awt.*; import java.awt.event.*; diff --git a/ui/ButtonGroups.java b/ui/ButtonGroups.java index ed7a1c97..6c9acb08 100644 --- a/ui/ButtonGroups.java +++ b/ui/ButtonGroups.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Uses reflection to create groups -// of different types of AbstractButton. +// of different types of AbstractButton import javax.swing.*; import javax.swing.border.*; import java.awt.*; diff --git a/ui/Buttons.java b/ui/Buttons.java index e0890ca9..7a0ca193 100644 --- a/ui/Buttons.java +++ b/ui/Buttons.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://mindviewinc.com/Books/OnJava/ for more book information. -// Various Swing buttons. +// Various Swing buttons import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.basic.*; diff --git a/ui/CheckBoxes.java b/ui/CheckBoxes.java index 8db02036..1aa99a84 100644 --- a/ui/CheckBoxes.java +++ b/ui/CheckBoxes.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using JCheckBoxes. +// Using JCheckBoxes import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/ColorBoxes.java b/ui/ColorBoxes.java index f137d749..403be798 100644 --- a/ui/ColorBoxes.java +++ b/ui/ColorBoxes.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://mindviewinc.com/Books/OnJava/ for more book information. -// A visual demonstration of threading. +// A visual demonstration of threading import javax.swing.*; import java.awt.*; import java.util.concurrent.*; @@ -11,7 +11,7 @@ import static onjava.SwingConsole.*; class CBox extends JPanel implements Runnable { private int pause; - private static Random rand = new Random(); + private static SplittableRandom rand = new SplittableRandom(); private Color color = new Color(0); public void paintComponent(Graphics g) { g.setColor(color); diff --git a/ui/ComboBoxes.java b/ui/ComboBoxes.java index d91ff596..aa2475c5 100644 --- a/ui/ComboBoxes.java +++ b/ui/ComboBoxes.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using drop-down lists. +// Using drop-down lists import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/Dialogs.java b/ui/Dialogs.java index 982c3c75..ae1fb96b 100644 --- a/ui/Dialogs.java +++ b/ui/Dialogs.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating and using Dialog Boxes. +// Creating and using Dialog Boxes import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/Faces.java b/ui/Faces.java index 4de88977..834dae89 100644 --- a/ui/Faces.java +++ b/ui/Faces.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://mindviewinc.com/Books/OnJava/ for more book information. -// Icon behavior in JButtons. +// Icon behavior in JButtons import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/FileChooserTest.java b/ui/FileChooserTest.java index 69d70801..240b3ebf 100644 --- a/ui/FileChooserTest.java +++ b/ui/FileChooserTest.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstration of File dialog boxes. +// Demonstration of File dialog boxes import javax.swing.*; import java.awt.*; import java.awt.event.*; @@ -17,22 +17,7 @@ public class FileChooserTest extends JFrame { save = new JButton("Save"); public FileChooserTest() { JPanel p = new JPanel(); - open.addActionListener(new OpenL()); - p.add(open); - save.addActionListener(new SaveL()); - p.add(save); - add(p, BorderLayout.SOUTH); - dir.setEditable(false); - fileName.setEditable(false); - p = new JPanel(); - p.setLayout(new GridLayout(2,1)); - p.add(fileName); - p.add(dir); - add(p, BorderLayout.NORTH); - } - class OpenL implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { + open.addActionListener(event -> { JFileChooser c = new JFileChooser(); // Demonstrate "Open" dialog: int rVal = c.showOpenDialog(FileChooserTest.this); @@ -44,11 +29,9 @@ public class FileChooserTest extends JFrame { fileName.setText("You pressed cancel"); dir.setText(""); } - } - } - class SaveL implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { + }); + p.add(open); + save.addActionListener(event -> { JFileChooser c = new JFileChooser(); // Demonstrate "Save" dialog: int rVal = c.showSaveDialog(FileChooserTest.this); @@ -60,7 +43,16 @@ public class FileChooserTest extends JFrame { fileName.setText("You pressed cancel"); dir.setText(""); } - } + }); + p.add(save); + add(p, BorderLayout.SOUTH); + dir.setEditable(false); + fileName.setEditable(false); + p = new JPanel(); + p.setLayout(new GridLayout(2,1)); + p.add(fileName); + p.add(dir); + add(p, BorderLayout.NORTH); } public static void main(String[] args) { run(new FileChooserTest(), 250, 150); diff --git a/ui/FlowLayout1.java b/ui/FlowLayout1.java index 43a67db6..5d707aee 100644 --- a/ui/FlowLayout1.java +++ b/ui/FlowLayout1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates FlowLayout. +// Demonstrates FlowLayout import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/GridLayout1.java b/ui/GridLayout1.java index ad90d85a..0ff08ddc 100644 --- a/ui/GridLayout1.java +++ b/ui/GridLayout1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates GridLayout. +// Demonstrates GridLayout import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/HTMLButton.java b/ui/HTMLButton.java index ec400a96..9581439f 100644 --- a/ui/HTMLButton.java +++ b/ui/HTMLButton.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://mindviewinc.com/Books/OnJava/ for more book information. -// Putting HTML text on Swing components. +// Putting HTML text on Swing components import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/HelloLabel.java b/ui/HelloLabel.java index 46947f67..76115ea9 100644 --- a/ui/HelloLabel.java +++ b/ui/HelloLabel.java @@ -6,7 +6,8 @@ import javax.swing.*; import java.util.concurrent.*; public class HelloLabel { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { JFrame frame = new JFrame("Hello Swing"); JLabel label = new JLabel("A Label"); frame.add(label); diff --git a/ui/InterruptableLongRunningCallable.java b/ui/InterruptableLongRunningCallable.java index 6aa1c6a9..95dc5ce5 100644 --- a/ui/InterruptableLongRunningCallable.java +++ b/ui/InterruptableLongRunningCallable.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using Callables for long-running tasks. +// Using Callables for long-running tasks import javax.swing.*; import java.awt.*; import java.util.concurrent.*; diff --git a/ui/InterruptableLongRunningTask.java b/ui/InterruptableLongRunningTask.java index 4477f4c1..a40dc783 100644 --- a/ui/InterruptableLongRunningTask.java +++ b/ui/InterruptableLongRunningTask.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://mindviewinc.com/Books/OnJava/ for more book information. -// Long-running tasks in threads. +// Long-running tasks in threads import javax.swing.*; import java.awt.*; import java.util.concurrent.*; diff --git a/ui/LongRunningTask.java b/ui/LongRunningTask.java index 73e276c1..4cbc3e14 100644 --- a/ui/LongRunningTask.java +++ b/ui/LongRunningTask.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://mindviewinc.com/Books/OnJava/ for more book information. -// A badly designed program. +// A badly designed program import javax.swing.*; import java.awt.*; import java.util.concurrent.*; diff --git a/ui/LookAndFeel.java b/ui/LookAndFeel.java index 2b3fd2da..b49f5e64 100644 --- a/ui/LookAndFeel.java +++ b/ui/LookAndFeel.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://mindviewinc.com/Books/OnJava/ for more book information. -// Selecting different looks & feels. +// Selecting different looks & feels // {Args: motif} import javax.swing.*; import java.awt.*; diff --git a/ui/Menus.java b/ui/Menus.java index fe38e513..a8328d4b 100644 --- a/ui/Menus.java +++ b/ui/Menus.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Submenus, check box menu items, swapping menus, -// mnemonics (shortcuts) and action commands. +// mnemonics (shortcuts) and action commands import javax.swing.*; import java.awt.*; import java.awt.event.*; diff --git a/ui/MessageBoxes.java b/ui/MessageBoxes.java index 5cf13992..bd2fab08 100644 --- a/ui/MessageBoxes.java +++ b/ui/MessageBoxes.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates JOptionPane. +// Demonstrates JOptionPane import javax.swing.*; import java.awt.*; import java.awt.event.*; @@ -45,7 +45,9 @@ public class MessageBoxes extends JFrame { break; } case "3 Vals": { - Object[] selections = {"First", "Second", "Third"}; + Object[] selections = { + "First", "Second", "Third" + }; Object val = JOptionPane.showInputDialog( null, "Choose one", "Input", JOptionPane.INFORMATION_MESSAGE, diff --git a/ui/MonitoredLongRunningCallable.java b/ui/MonitoredLongRunningCallable.java index 644fcd92..adbf6bad 100644 --- a/ui/MonitoredLongRunningCallable.java +++ b/ui/MonitoredLongRunningCallable.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://mindviewinc.com/Books/OnJava/ for more book information. -// Displaying task progress with ProgressMonitors. +// Displaying task progress with ProgressMonitors // {IgnoreOutput} import javax.swing.*; import java.awt.*; diff --git a/ui/Popup.java b/ui/Popup.java index 062542d4..67469e36 100644 --- a/ui/Popup.java +++ b/ui/Popup.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://mindviewinc.com/Books/OnJava/ for more book information. -// Creating popup menus with Swing. +// Creating popup menus with Swing import javax.swing.*; import java.awt.*; import java.awt.event.*; diff --git a/ui/Progress.java b/ui/Progress.java index 9d29200b..a1e4b99c 100644 --- a/ui/Progress.java +++ b/ui/Progress.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using sliders, progress bars and progress monitors. +// Using sliders, progress bars and progress monitors import javax.swing.*; import javax.swing.border.*; import java.awt.*; diff --git a/ui/RadioButtons.java b/ui/RadioButtons.java index 51f57a4f..180e0d5b 100644 --- a/ui/RadioButtons.java +++ b/ui/RadioButtons.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using JRadioButtons. +// Using JRadioButtons import javax.swing.*; import java.awt.*; import java.awt.event.*; diff --git a/ui/ShowAddListeners.java b/ui/ShowAddListeners.java index 532d883a..e8b8b47d 100644 --- a/ui/ShowAddListeners.java +++ b/ui/ShowAddListeners.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://mindviewinc.com/Books/OnJava/ for more book information. -// Display the "addXXXListener" methods of any Swing class. +// Display the "addXXXListener" methods of any Swing class import javax.swing.*; import java.awt.*; import java.awt.event.*; @@ -47,7 +47,8 @@ public class ShowAddListeners extends JFrame { NameL nameListener = new NameL(); name.addActionListener(nameListener); JPanel top = new JPanel(); - top.add(new JLabel("Swing class name (press Enter):")); + top.add(new JLabel( + "Swing class name (press Enter):")); top.add(name); add(BorderLayout.NORTH, top); add(new JScrollPane(results)); diff --git a/ui/SineWave.java b/ui/SineWave.java index e6b66044..6f1915f1 100644 --- a/ui/SineWave.java +++ b/ui/SineWave.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://mindviewinc.com/Books/OnJava/ for more book information. -// Drawing with Swing, using a JSlider. +// Drawing with Swing, using a JSlider import javax.swing.*; import javax.swing.event.*; import java.awt.*; diff --git a/ui/SubmitLabelManipulationTask.java b/ui/SubmitLabelManipulationTask.java index 3f132983..1616387b 100644 --- a/ui/SubmitLabelManipulationTask.java +++ b/ui/SubmitLabelManipulationTask.java @@ -6,7 +6,8 @@ import javax.swing.*; import java.util.concurrent.*; public class SubmitLabelManipulationTask { - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { JFrame frame = new JFrame("Hello Swing"); final JLabel label = new JLabel("A Label"); frame.add(label); diff --git a/ui/SubmitSwingProgram.java b/ui/SubmitSwingProgram.java index db4e59fe..fe029cf0 100644 --- a/ui/SubmitSwingProgram.java +++ b/ui/SubmitSwingProgram.java @@ -16,7 +16,8 @@ public class SubmitSwingProgram extends JFrame { setVisible(true); } static SubmitSwingProgram ssp; - public static void main(String[] args) throws Exception { + public static void + main(String[] args) throws Exception { SwingUtilities.invokeLater(() -> ssp = new SubmitSwingProgram()); TimeUnit.SECONDS.sleep(1); diff --git a/ui/TabbedPane1.java b/ui/TabbedPane1.java index ef63535f..0d529dec 100644 --- a/ui/TabbedPane1.java +++ b/ui/TabbedPane1.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://mindviewinc.com/Books/OnJava/ for more book information. -// Demonstrates the Tabbed Pane. +// Demonstrates the Tabbed Pane import javax.swing.*; import java.awt.*; import static onjava.SwingConsole.*; diff --git a/ui/TextArea.java b/ui/TextArea.java index da5921f2..ab8d8dfb 100644 --- a/ui/TextArea.java +++ b/ui/TextArea.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://mindviewinc.com/Books/OnJava/ for more book information. -// Using the JTextArea control. +// Using the JTextArea control import javax.swing.*; import java.awt.*; import java.util.*; diff --git a/ui/TextFields.java b/ui/TextFields.java index 129d3e4d..eba0abe8 100644 --- a/ui/TextFields.java +++ b/ui/TextFields.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://mindviewinc.com/Books/OnJava/ for more book information. -// Text fields and Java events. +// Text fields and Java events import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; @@ -83,9 +83,9 @@ class UpperCaseDocument extends PlainDocument { upperCase = flag; } @Override - public void - insertString(int offset, String str, AttributeSet attSet) - throws BadLocationException { + public void insertString( + int offset, String str, AttributeSet attSet) + throws BadLocationException { if(upperCase) str = str.toUpperCase(); super.insertString(offset, str, attSet); } diff --git a/ui/TextPane.java b/ui/TextPane.java index e99ed621..046dd7ac 100644 --- a/ui/TextPane.java +++ b/ui/TextPane.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://mindviewinc.com/Books/OnJava/ for more book information. -// The JTextPane control is a little editor. +// The JTextPane control is a little editor import javax.swing.*; import java.awt.*; import java.util.function.*; @@ -12,8 +12,8 @@ import static onjava.SwingConsole.*; public class TextPane extends JFrame { private JButton b = new JButton("Add Text"); private JTextPane tp = new JTextPane(); - private static Supplier sg = - new RandomSupplier.String(7); + private static Supplier sg = + new Rand.String(7); public TextPane() { b.addActionListener(e -> { for(int i = 1; i < 10; i++) diff --git a/ui/TicTacToe.java b/ui/TicTacToe.java index 0d1c7538..d7ada215 100644 --- a/ui/TicTacToe.java +++ b/ui/TicTacToe.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://mindviewinc.com/Books/OnJava/ for more book information. -// Dialog boxes and creating your own components. +// Dialog boxes and creating your own components import javax.swing.*; import java.awt.*; import java.awt.event.*; @@ -60,15 +60,6 @@ public class TicTacToe extends JFrame { } } } - class BL implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - JDialog d = new ToeDialog( - new Integer(rows.getText()), - new Integer(cols.getText())); - d.setVisible(true); - } - } public TicTacToe() { JPanel p = new JPanel(); p.setLayout(new GridLayout(2,2)); @@ -78,7 +69,12 @@ public class TicTacToe extends JFrame { p.add(cols); add(p, BorderLayout.NORTH); JButton b = new JButton("go"); - b.addActionListener(new BL()); + b.addActionListener(e -> { + JDialog d = new ToeDialog( + new Integer(rows.getText()), + new Integer(cols.getText())); + d.setVisible(true); + }); add(b, BorderLayout.SOUTH); } public static void main(String[] args) { diff --git a/ui/TrackEvent.java b/ui/TrackEvent.java index 211630f6..1192955c 100644 --- a/ui/TrackEvent.java +++ b/ui/TrackEvent.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://mindviewinc.com/Books/OnJava/ for more book information. -// Show events as they happen. +// Show events as they happen import javax.swing.*; import java.awt.*; import java.awt.event.*; diff --git a/unittesting/JUnitDemo.java b/unittesting/JUnitDemo.java index 96f3a978..8ad0a846 100644 --- a/unittesting/JUnitDemo.java +++ b/unittesting/JUnitDemo.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Simple use of JUnit to test ArrayList -// (Install libraries from www.junit.org) +// (Install libraries from junit.org) import java.util.*; import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/verify_output.py b/verify_output.py index 4eefb21b..1a04a027 100644 --- a/verify_output.py +++ b/verify_output.py @@ -23,7 +23,7 @@ def clean(): "strategies.txt", "validate_successes.txt", "validate_failures.txt", - ]): + ]): if p.exists(): p.unlink()