From d5cf2b736434aebb13f786870f90a3b57729ff6d Mon Sep 17 00:00:00 2001 From: Bruce Eckel Date: Tue, 5 May 2015 11:20:13 -0700 Subject: [PATCH] New chapters and Netbeans mods --- Copyright.txt | 40 ++-- access/SingleImport.java | 2 +- access/build.xml | 24 +++ annotations/AtUnitExample4.java | 2 +- annotations/AtUnitExample5.java | 1 + annotations/HashSetTest.java | 2 +- annotations/InterfaceExtractorProcessor.java | 4 +- .../InterfaceExtractorProcessorFactory.java | 2 +- annotations/StackL.java | 2 +- annotations/UseCaseTracker.java | 2 +- annotations/build.xml | 25 +++ annotations/database/Member.java | 1 + .../TableCreationProcessorFactory.java | 2 +- annotations/database/TableCreator.java | 2 +- arrays/ArrayOfGenerics.java | 6 +- arrays/CompType.java | 3 + arrays/ContainerComparison.java | 6 +- arrays/PythonLists.py | 23 +++ arrays/build.xml | 39 ++++ assertions/Assert1.java | 11 ++ assertions/Assert2.java | 10 + assertions/LoaderAssertions.java | 18 ++ assertions/Queue.java | 172 ++++++++++++++++++ assertions/build.xml | 17 ++ concurrency/ActiveObjectDemo.java | 4 +- concurrency/AtomicEvenGenerator.java | 3 +- concurrency/AtomicIntegerTest.java | 2 + concurrency/AtomicityTest.java | 1 + concurrency/AttemptLocking.java | 1 + concurrency/BankTellerSimulation.java | 10 +- concurrency/CallableDemo.java | 4 +- concurrency/CaptureUncaughtException.java | 7 +- concurrency/CarBuilder.java | 5 +- concurrency/CloseResource.java | 2 +- concurrency/CountDownLatchDemo.java | 4 + concurrency/CriticalSection.java | 13 +- concurrency/DaemonFromFactory.java | 1 + concurrency/Daemons.java | 2 + concurrency/DaemonsDontRunFinally.java | 1 + concurrency/DelayQueueDemo.java | 10 +- concurrency/EvenChecker.java | 1 + concurrency/EvenGenerator.java | 1 + concurrency/ExceptionThread.java | 1 + concurrency/ExchangerDemo.java | 12 +- concurrency/ExplicitCriticalSection.java | 4 +- concurrency/FastSimulation.java | 1 + concurrency/Fat.java | 1 + concurrency/GreenhouseScheduler.java | 15 +- concurrency/HorseRace.java | 5 +- concurrency/Interrupting.java | 4 + concurrency/Interrupting2.java | 1 + concurrency/InterruptingIdiom.java | 1 + concurrency/Joining.java | 2 + concurrency/LiftOff.java | 1 + concurrency/ListComparisons.java | 4 +- concurrency/MapComparisons.java | 4 +- concurrency/MultiLock.java | 1 + concurrency/MutexEvenGenerator.java | 3 +- concurrency/NIOInterruption.java | 1 + concurrency/NaiveExceptionHandling.java | 2 +- concurrency/NotifyVsNotifyAll.java | 3 + concurrency/OrnamentalGarden.java | 4 +- concurrency/Philosopher.java | 2 + concurrency/PipedIO.java | 2 + concurrency/Pool.java | 2 +- concurrency/PriorityBlockingQueueDemo.java | 12 +- concurrency/ReaderWriterList.java | 8 +- concurrency/ResponsiveUI.java | 3 +- concurrency/Restaurant.java | 3 + concurrency/SelfManaged.java | 2 + concurrency/SemaphoreDemo.java | 10 +- concurrency/SerialNumberChecker.java | 3 +- concurrency/SettingDefaultHandler.java | 4 +- concurrency/SimpleDaemons.java | 1 + concurrency/SimpleMicroBenchmark.java | 2 + concurrency/SimplePriorities.java | 4 +- concurrency/SimpleThread.java | 2 + concurrency/SleepingTask.java | 3 +- concurrency/SyncObject.java | 1 + concurrency/SynchronizationComparisons.java | 9 + concurrency/SynchronizedEvenGenerator.java | 3 +- concurrency/TestBlockingQueues.java | 9 +- concurrency/ThreadLocalVariableHolder.java | 3 + concurrency/ThreadVariations.java | 10 + concurrency/ToastOMatic.java | 5 + concurrency/build.xml | 80 ++++++++ .../restaurant2/RestaurantWithQueues.java | 21 ++- concurrency/waxomatic/WaxOMatic.java | 2 + concurrency/waxomatic2/WaxOMatic2.java | 2 + containers/AssociativeArray.java | 3 +- containers/CanonicalMapping.java | 7 +- containers/CollectionDataGeneration.java | 8 +- containers/CollectionDataTest.java | 5 +- containers/CollectionMethods.java | 18 +- containers/CountedString.java | 7 +- containers/DequeTest.java | 2 +- containers/Enumerations.java | 6 +- containers/FailFast.java | 2 +- containers/FillingLists.java | 3 +- containers/Groundhog.java | 1 + containers/Groundhog2.java | 2 + containers/IndividualTest.java | 2 +- containers/LinkedHashMapDemo.java | 6 +- containers/ListPerformance.java | 24 ++- containers/ListSortSearch.java | 2 +- containers/Lists.java | 16 +- containers/MapDataTest.java | 8 +- containers/MapEntry.java | 6 + containers/MapPerformance.java | 17 +- containers/Maps.java | 22 +-- containers/Prediction.java | 1 + containers/QueueBehavior.java | 13 +- containers/RandomBounds.java | 27 +-- containers/ReadOnly.java | 20 +- containers/References.java | 20 +- containers/SetPerformance.java | 11 +- containers/SimpleHashMap.java | 16 +- containers/SlowMap.java | 19 +- containers/SortedMapDemo.java | 2 +- containers/SortedSetDemo.java | 2 +- containers/SpringDetector.java | 5 +- containers/SpringDetector2.java | 2 +- containers/Stacks.java | 6 +- containers/Synchronization.java | 13 +- containers/Tester.java | 6 +- containers/ToDoList.java | 2 + containers/TypesForSets.java | 24 ++- containers/Unsupported.java | 6 +- containers/Utilities.java | 2 +- containers/build.xml | 50 +++++ control/StringSwitch.java | 38 ++++ control/build.xml | 26 +++ debugging/SimpleDebugging.java | 21 +++ debugging/build.xml | 14 ++ enumerated/Burrito.java | 1 + enumerated/CarWash.java | 8 + enumerated/ConstantSpecificMethod.java | 3 + enumerated/EnumMaps.java | 6 +- enumerated/Input.java | 4 +- enumerated/NonEnum.java | 2 +- enumerated/NotClasses.java | 9 +- enumerated/OverrideConstantSpecific.java | 1 + enumerated/PostOffice.java | 9 + enumerated/Reflection.java | 4 +- enumerated/RoShamBo1.java | 15 ++ enumerated/RoShamBo2.java | 1 + enumerated/RoShamBo3.java | 4 + enumerated/RoShamBo4.java | 3 + enumerated/RoShamBo5.java | 7 +- enumerated/RoShamBo6.java | 1 + enumerated/SpaceShip.java | 1 + enumerated/TrafficLight.java | 1 + enumerated/VendingMachine.java | 13 +- enumerated/VendingMachineInput.txt | 2 + enumerated/build.xml | 40 ++++ enumerated/cartoons/EnumImplementation.java | 1 + exceptions/DynamicFields.java | 3 +- exceptions/ExtraFeatures.java | 1 + exceptions/LostMessage.java | 2 + exceptions/StormyInning.java | 5 +- exceptions/Switch.java | 1 + exceptions/build.xml | 37 ++++ generics/Apply.java | 10 +- generics/ArrayMaker.java | 2 +- generics/ArrayOfGeneric.java | 2 +- generics/BankTeller.java | 8 +- generics/BasicBounds.java | 6 +- generics/ByteSet.java | 4 +- generics/CaptureConversion.java | 4 +- generics/CheckedList.java | 8 +- generics/ClassTypeCapture.java | 4 +- generics/ComparablePet.java | 1 + generics/CountedObject.java | 1 + generics/CovariantReturnTypes.java | 1 + generics/CreatorGeneric.java | 1 + generics/Diamond.java | 15 ++ generics/DogsAndRobots.java | 2 + generics/DogsAndRobots.py | 27 +++ generics/DynamicProxyMixin.java | 4 +- generics/EpicBattle.java | 2 + generics/ErasureAndInheritance.java | 2 +- generics/FactoryConstraint.java | 6 +- generics/Fibonacci.java | 1 + generics/Fill.java | 5 +- generics/Fill2.java | 10 +- generics/FilledListMaker.java | 4 +- generics/Functional.java | 23 ++- generics/Generators.java | 4 +- generics/GenericArray.java | 3 +- generics/GenericArray2.java | 4 +- generics/GenericArrayWithTypeToken.java | 2 +- generics/GenericCast.java | 2 +- generics/GenericHolder.java | 2 +- generics/GenericReading.java | 4 +- generics/GenericVarargs.java | 2 +- generics/GenericWriting.java | 6 +- generics/GenericsAndCovariance.java | 2 +- generics/Holder.java | 3 +- generics/Holder3.java | 2 +- generics/InheritBounds.java | 2 +- generics/InstantiateGenericType.java | 4 +- generics/IterableFibonacci.java | 4 + generics/LatentReflection.java | 1 + generics/LinkedStack.java | 6 +- generics/ListMaker.java | 4 +- generics/ListOfGenerics.java | 2 +- generics/ListOfInt.java | 2 +- generics/LostInformation.java | 8 +- generics/Manipulation.java | 4 +- generics/Mixins.java | 6 + generics/NonCovariantGenerics.java | 2 +- generics/RandomList.java | 4 +- generics/SelfBounding.java | 2 +- generics/SimpleQueue.java | 3 +- generics/Store.java | 5 +- generics/ThrowGenericException.java | 8 +- generics/TupleList.java | 2 +- generics/TupleTest.java | 9 +- generics/UnboundedWildcards1.java | 8 +- generics/UnboundedWildcards2.java | 6 +- generics/UseList.java | 2 +- generics/Wildcards.java | 10 +- generics/build.xml | 84 +++++++++ generics/coffee/Coffee.java | 1 + generics/coffee/CoffeeGenerator.java | 7 +- generics/decorator/Decoration.java | 2 + gui/Button2.java | 1 + gui/Button2b.java | 1 + gui/CheckBoxes.java | 3 + gui/ColorBoxes.java | 2 +- gui/ComboBoxes.java | 2 + gui/Dialogs.java | 2 + gui/Faces.java | 2 + gui/FileChooserTest.java | 2 + gui/HTMLButton.java | 1 + gui/InterruptableLongRunningCallable.java | 6 +- gui/InterruptableLongRunningTask.java | 4 + gui/List.java | 4 +- gui/LongRunningTask.java | 2 + gui/LookAndFeel.java | 50 ++--- gui/Menus.java | 29 ++- gui/MessageBoxes.java | 24 ++- gui/MonitoredLongRunningCallable.java | 11 +- gui/Popup.java | 3 + gui/Progress.java | 1 + gui/RadioButtons.java | 1 + gui/ShowAddListeners.java | 1 + gui/SimpleMenus.java | 1 + gui/SubmitLabelManipulationTask.java | 1 + gui/SubmitSwingProgram.java | 2 + gui/TabbedPane1.java | 1 + gui/TextArea.java | 5 +- gui/TextFields.java | 7 + gui/TextPane.java | 1 + gui/TicTacToe.java | 3 + gui/TrackEvent.java | 14 +- gui/build.xml | 53 ++++++ holding/AdapterMethodIdiom.java | 8 +- holding/AddingGroups.java | 2 +- holding/ApplesAndOrangesWithGenerics.java | 2 +- holding/AsListInference.java | 2 +- holding/CollectionSequence.java | 5 + holding/CrossContainerIteration.java | 8 +- holding/ForEachCollections.java | 2 +- holding/GenericsAndUpcasting.java | 2 +- holding/InterfaceVsIterator.java | 9 +- holding/IterableClass.java | 4 + holding/LinkedListFeatures.java | 2 +- holding/ListFeatures.java | 4 +- holding/MapOfList.java | 18 +- holding/ModifyingArraysAsList.java | 2 +- holding/MultiIterableClass.java | 7 +- holding/NonCollectionSequence.java | 3 + holding/PetMap.java | 4 +- holding/PrintingContainers.java | 20 +- holding/PriorityQueueDemo.java | 14 +- holding/QueueDemo.java | 4 +- holding/SetOfInteger.java | 4 +- holding/SetOperations.java | 10 +- holding/SimpleCollection.java | 2 +- holding/SortedSetOfInteger.java | 2 +- holding/StackCollision.java | 6 +- holding/StackTest.java | 2 +- holding/Statistics.java | 5 +- holding/UniqueWords.java | 2 +- holding/UniqueWordsAlphabetic.java | 2 +- holding/build.xml | 48 +++++ initialization/TerminationCondition.java | 1 + initialization/build.xml | 46 +++++ innerclasses/AnonymousConstructor.java | 1 + innerclasses/BigEgg2.java | 1 + innerclasses/Callbacks.java | 3 + innerclasses/ClassInInterface.java | 1 + innerclasses/Games.java | 1 + innerclasses/GreenhouseControls.java | 18 ++ innerclasses/LambdaExpressions.java | 15 ++ innerclasses/LocalInnerClass.java | 2 + innerclasses/Parcel10.java | 1 + innerclasses/Parcel11.java | 2 + innerclasses/Parcel5.java | 1 + innerclasses/Parcel7.java | 1 + innerclasses/Parcel7b.java | 1 + innerclasses/Parcel8.java | 1 + innerclasses/Parcel9.java | 1 + innerclasses/Sequence.java | 3 + innerclasses/TestParcel.java | 2 + innerclasses/build.xml | 42 +++++ innerclasses/controller/Controller.java | 4 +- interfaces/AdaptedRandomDoubles.java | 1 + interfaces/Factories.java | 2 + interfaces/Games.java | 4 + interfaces/HorrorShow.java | 6 + interfaces/InterfaceCollision.java | 4 + interfaces/RandomWords.java | 1 + interfaces/build.xml | 27 +++ interfaces/classprocessor/Apply.java | 3 + interfaces/filters/BandPass.java | 1 + interfaces/filters/HighPass.java | 1 + interfaces/filters/LowPass.java | 1 + interfaces/filters/Waveform.java | 1 + .../interfaceprocessor/FilterProcessor.java | 2 + .../interfaceprocessor/StringProcessor.java | 5 + interfaces/music4/Music4.java | 13 ++ interfaces/music5/Music5.java | 11 ++ interfaces/nesting/NestingInterfaces.java | 12 ++ io/AStoreCADState.java | 106 +++++++++++ io/AvailableCharSets.java | 10 +- io/Blip3.java | 3 + io/Blips.java | 4 + io/DirList.java | 1 + io/DirList2.java | 1 + io/DirList3.java | 1 + io/Echo.java | 2 +- io/FormattedMemoryInput.java | 2 +- io/GZIPcompress.java | 2 +- io/GetChannel.java | 2 +- io/LargeMappedFiles.java | 3 +- io/LockingMappedFiles.java | 2 +- io/Logon.java | 1 + io/MakeDirectories.java | 2 +- io/MappedIO.java | 6 + io/MyWorld.java | 3 +- io/RecoverCADState.java | 2 +- io/SerialCtl.java | 1 + io/TestEOF.java | 2 +- io/Worm.java | 2 + io/ZipCompress.java | 2 +- io/build.xml | 57 ++++++ io/xfiles/ThawAlien.java | 6 +- logging/ConfigureLogging.java | 36 ++++ logging/CustomHandler.java | 29 +++ logging/EmailLogger.java | 92 ++++++++++ logging/InfoLogging.java | 11 ++ logging/InfoLogging2.java | 13 ++ logging/LogToFile.java | 12 ++ logging/LogToFile2.java | 14 ++ logging/LoggingLevelManipulation.java | 56 ++++++ logging/LoggingLevels.java | 34 ++++ logging/MultipleHandlers.java | 15 ++ logging/MultipleHandlers2.java | 16 ++ logging/PrintableLogRecord.java | 38 ++++ logging/SimpleFilter.java | 30 +++ logging/SimpleFormatterExample.java | 27 +++ logging/build.xml | 25 +++ logging/log.prop | 33 ++++ net/build.xml | 25 +++ net/mindview/atunit/AtUnit.java | 4 +- net/mindview/atunit/AtUnitRemover.java | 3 +- net/mindview/atunit/ClassNameFinder.java | 6 +- net/mindview/atunit/TestProperty.java | 2 +- net/mindview/util/BasicGenerator.java | 3 +- net/mindview/util/CollectionData.java | 2 +- .../util/ContainerMethodDifferences.java | 4 +- net/mindview/util/CountingGenerator.java | 9 + net/mindview/util/CountingIntegerList.java | 4 +- net/mindview/util/CountingMapData.java | 10 +- net/mindview/util/Countries.java | 50 +++-- net/mindview/util/DaemonThreadFactory.java | 1 + .../util/DaemonThreadPoolExecutor.java | 2 +- net/mindview/util/Deque.java | 3 +- net/mindview/util/Directory.java | 7 +- net/mindview/util/FiveTuple.java | 1 + net/mindview/util/FourTuple.java | 1 + net/mindview/util/Generated.java | 6 +- net/mindview/util/MapData.java | 10 +- net/mindview/util/New.java | 10 +- net/mindview/util/PPrint.java | 2 +- net/mindview/util/Print.java | 6 +- net/mindview/util/ProcessFiles.java | 1 + net/mindview/util/RandomGenerator.java | 8 + net/mindview/util/Range.java | 2 +- net/mindview/util/Sets.java | 6 +- net/mindview/util/Stack.java | 3 +- net/mindview/util/SwingConsole.java | 1 + net/mindview/util/TaskManager.java | 8 +- net/mindview/util/TextFile.java | 2 +- net/mindview/util/ThreeTuple.java | 1 + net/mindview/util/Tuple.java | 8 +- net/mindview/util/TwoTuple.java | 1 + net/mindview/util/TypeCounter.java | 1 + network/ChatterClient.java | 64 +++++++ network/ChatterServer.java | 48 +++++ network/Dgram.java | 26 +++ network/MultiSimpleClient.java | 85 +++++++++ network/MultiSimpleServer.java | 72 ++++++++ network/SimpleClient.java | 53 ++++++ network/SimpleServer.java | 47 +++++ network/WhoAmI.java | 19 ++ network/build.xml | 20 ++ object/build.xml | 15 ++ operators/PassObject.java | 2 +- operators/build.xml | 34 ++++ patterns/CommandPattern.java | 49 +++++ patterns/Facade.java | 21 +++ patterns/PaperScissorsRock.java | 131 +++++++++++++ patterns/ProxyDemo.java | 43 +++++ patterns/ShapeFactory2.java | 96 ++++++++++ patterns/SingletonPattern.java | 32 ++++ patterns/StateDemo.java | 76 ++++++++ patterns/TemplateMethod.java | 35 ++++ patterns/absfactory/GameEnvironment.java | 97 ++++++++++ patterns/adapt/Adapter.java | 81 +++++++++ patterns/build.xml | 36 ++++ patterns/chain/ChainOfResponsibility.java | 87 +++++++++ patterns/doubledispatch/DDAluminum.java | 16 ++ patterns/doubledispatch/DDCardboard.java | 16 ++ patterns/doubledispatch/DDGlass.java | 16 ++ patterns/doubledispatch/DDPaper.java | 16 ++ patterns/doubledispatch/DDTrash.dat | 35 ++++ patterns/doubledispatch/DoubleDispatch.java | 71 ++++++++ patterns/doubledispatch/TypedBin.java | 28 +++ patterns/doubledispatch/TypedBinMember.java | 10 + patterns/dynatrash/DynaTrash.java | 50 +++++ patterns/dynatrash/Trash.dat | 35 ++++ patterns/factory/ShapeFactory1.java | 66 +++++++ patterns/observer/ObservedFlower.java | 143 +++++++++++++++ patterns/recyclea/RecycleA.java | 102 +++++++++++ patterns/recycleap/RecycleAP.java | 33 ++++ patterns/recycleap/Trash.dat | 35 ++++ patterns/recycleb/RecycleB.java | 66 +++++++ patterns/recycleb/Trash.dat | 35 ++++ patterns/state/StateMachineDemo.java | 77 ++++++++ patterns/strategy/StrategyPattern.java | 65 +++++++ patterns/trash/Aluminum.java | 13 ++ patterns/trash/Cardboard.java | 13 ++ patterns/trash/Fillable.java | 7 + patterns/trash/FillableArrayList.java | 14 ++ patterns/trash/Glass.java | 13 ++ patterns/trash/Paper.java | 13 ++ patterns/trash/ParseTrash.java | 40 ++++ patterns/trash/Trash.java | 86 +++++++++ patterns/trashvisitor/TrashVisitor.java | 110 +++++++++++ patterns/trashvisitor/VAluminum.java | 13 ++ patterns/trashvisitor/VCardboard.java | 13 ++ patterns/trashvisitor/VGlass.java | 13 ++ patterns/trashvisitor/VPaper.java | 13 ++ patterns/trashvisitor/VTrash.dat | 35 ++++ patterns/trashvisitor/Visitable.java | 11 ++ patterns/trashvisitor/Visitor.java | 11 ++ patterns/visitor/BeeAndFlowers.java | 97 ++++++++++ patterns/visualobserver/BoxObserver.java | 90 +++++++++ polymorphism/CovariantReturn.java | 3 + polymorphism/FieldAccess.java | 1 + polymorphism/Frog.java | 3 + polymorphism/PolyConstructors.java | 1 + polymorphism/RTTI.java | 2 + polymorphism/ReferenceCounting.java | 2 + polymorphism/StaticPolymorphism.java | 1 + polymorphism/Transmogrify.java | 2 + polymorphism/build.xml | 27 +++ polymorphism/music/Music2.java | 2 + polymorphism/music/Wind.java | 1 + polymorphism/music3/Music3.java | 13 ++ polymorphism/shape/Circle.java | 2 + polymorphism/shape/Square.java | 2 + polymorphism/shape/Triangle.java | 2 + references/AddingClone.java | 54 ++++++ references/Alias1.java | 17 ++ references/Alias2.java | 15 ++ references/CheckCloneable.java | 90 +++++++++ references/Cloning.java | 28 +++ references/Compete.java | 70 +++++++ references/CopyConstructor.java | 152 ++++++++++++++++ references/DeepCopy.java | 111 +++++++++++ references/HorrorFlick.java | 30 +++ references/Immutable1.java | 25 +++ references/Immutable2.java | 55 ++++++ references/ImmutableInteger.java | 12 ++ references/ImmutableStrings.java | 17 ++ references/LocalCopy.java | 47 +++++ references/MutableInteger.java | 25 +++ references/PassReferences.java | 13 ++ references/Snake.java | 44 +++++ references/Stringer.java | 14 ++ references/build.xml | 31 ++++ remote/build.xml | 13 ++ remote/ptime/DisplayPerfectTime.java | 22 +++ remote/ptime/PerfectTime.java | 37 ++++ remote/ptime/PerfectTimeI.java | 8 + reusing/Bath.java | 2 + reusing/CADSystem.java | 4 + reusing/Detergent.java | 2 + reusing/FinalData.java | 1 + reusing/Orc.java | 2 + reusing/SpaceShip.java | 1 + reusing/SprinklerSystem.java | 2 + reusing/build.xml | 32 ++++ strings/ArrayListDisplay.java | 2 +- strings/InfiniteRecursion.java | 6 +- strings/Receipt.java | 2 +- strings/TestRegularExpression.java | 2 +- strings/UsingStringBuilder.java | 1 + strings/build.xml | 41 +++++ swt/ColorBoxes.java | 3 + swt/DisplayEnvironment.java | 1 + swt/Menus.java | 3 +- swt/SineWave.java | 1 + swt/TabbedPane.java | 1 + swt/build.xml | 21 +++ typeinfo/FilledList.java | 5 +- typeinfo/ModifyingPrivateFields.java | 1 + typeinfo/NullRobot.java | 4 + typeinfo/Person.java | 2 + typeinfo/PetCount.java | 2 +- typeinfo/PetCount3.java | 1 + typeinfo/Position.java | 1 + typeinfo/RegisteredFactories.java | 10 +- typeinfo/SelectingMethods.java | 5 + typeinfo/Shapes.java | 4 + typeinfo/SimpleDynamicProxy.java | 1 + typeinfo/SimpleProxyDemo.java | 4 + typeinfo/SnowRemovalRobot.java | 8 + typeinfo/build.xml | 42 +++++ typeinfo/packageaccess/HiddenC.java | 1 + typeinfo/pets/ForNameCreator.java | 3 +- typeinfo/pets/Individual.java | 4 + typeinfo/pets/LiteralPetCreator.java | 1 + typeinfo/pets/PetCreator.java | 2 +- unittesting/build.xml | 14 ++ xml/APerson.java | 3 +- xml/People.java | 2 +- xml/build.xml | 15 ++ 542 files changed, 6909 insertions(+), 595 deletions(-) create mode 100644 access/build.xml create mode 100644 annotations/build.xml create mode 100644 arrays/PythonLists.py create mode 100644 arrays/build.xml create mode 100644 assertions/Assert1.java create mode 100644 assertions/Assert2.java create mode 100644 assertions/LoaderAssertions.java create mode 100644 assertions/Queue.java create mode 100644 assertions/build.xml create mode 100644 concurrency/build.xml create mode 100644 containers/build.xml create mode 100644 control/StringSwitch.java create mode 100644 control/build.xml create mode 100644 debugging/SimpleDebugging.java create mode 100644 debugging/build.xml create mode 100644 enumerated/build.xml create mode 100644 exceptions/build.xml create mode 100644 generics/Diamond.java create mode 100644 generics/DogsAndRobots.py create mode 100644 generics/build.xml create mode 100644 gui/build.xml create mode 100644 holding/build.xml create mode 100644 initialization/build.xml create mode 100644 innerclasses/LambdaExpressions.java create mode 100644 innerclasses/build.xml create mode 100644 interfaces/build.xml create mode 100644 io/AStoreCADState.java create mode 100644 io/build.xml create mode 100644 logging/ConfigureLogging.java create mode 100644 logging/CustomHandler.java create mode 100644 logging/EmailLogger.java create mode 100644 logging/InfoLogging.java create mode 100644 logging/InfoLogging2.java create mode 100644 logging/LogToFile.java create mode 100644 logging/LogToFile2.java create mode 100644 logging/LoggingLevelManipulation.java create mode 100644 logging/LoggingLevels.java create mode 100644 logging/MultipleHandlers.java create mode 100644 logging/MultipleHandlers2.java create mode 100644 logging/PrintableLogRecord.java create mode 100644 logging/SimpleFilter.java create mode 100644 logging/SimpleFormatterExample.java create mode 100644 logging/build.xml create mode 100644 logging/log.prop create mode 100644 net/build.xml create mode 100644 network/ChatterClient.java create mode 100644 network/ChatterServer.java create mode 100644 network/Dgram.java create mode 100644 network/MultiSimpleClient.java create mode 100644 network/MultiSimpleServer.java create mode 100644 network/SimpleClient.java create mode 100644 network/SimpleServer.java create mode 100644 network/WhoAmI.java create mode 100644 network/build.xml create mode 100644 object/build.xml create mode 100644 operators/build.xml create mode 100644 patterns/CommandPattern.java create mode 100644 patterns/Facade.java create mode 100644 patterns/PaperScissorsRock.java create mode 100644 patterns/ProxyDemo.java create mode 100644 patterns/ShapeFactory2.java create mode 100644 patterns/SingletonPattern.java create mode 100644 patterns/StateDemo.java create mode 100644 patterns/TemplateMethod.java create mode 100644 patterns/absfactory/GameEnvironment.java create mode 100644 patterns/adapt/Adapter.java create mode 100644 patterns/build.xml create mode 100644 patterns/chain/ChainOfResponsibility.java create mode 100644 patterns/doubledispatch/DDAluminum.java create mode 100644 patterns/doubledispatch/DDCardboard.java create mode 100644 patterns/doubledispatch/DDGlass.java create mode 100644 patterns/doubledispatch/DDPaper.java create mode 100644 patterns/doubledispatch/DDTrash.dat create mode 100644 patterns/doubledispatch/DoubleDispatch.java create mode 100644 patterns/doubledispatch/TypedBin.java create mode 100644 patterns/doubledispatch/TypedBinMember.java create mode 100644 patterns/dynatrash/DynaTrash.java create mode 100644 patterns/dynatrash/Trash.dat create mode 100644 patterns/factory/ShapeFactory1.java create mode 100644 patterns/observer/ObservedFlower.java create mode 100644 patterns/recyclea/RecycleA.java create mode 100644 patterns/recycleap/RecycleAP.java create mode 100644 patterns/recycleap/Trash.dat create mode 100644 patterns/recycleb/RecycleB.java create mode 100644 patterns/recycleb/Trash.dat create mode 100644 patterns/state/StateMachineDemo.java create mode 100644 patterns/strategy/StrategyPattern.java create mode 100644 patterns/trash/Aluminum.java create mode 100644 patterns/trash/Cardboard.java create mode 100644 patterns/trash/Fillable.java create mode 100644 patterns/trash/FillableArrayList.java create mode 100644 patterns/trash/Glass.java create mode 100644 patterns/trash/Paper.java create mode 100644 patterns/trash/ParseTrash.java create mode 100644 patterns/trash/Trash.java create mode 100644 patterns/trashvisitor/TrashVisitor.java create mode 100644 patterns/trashvisitor/VAluminum.java create mode 100644 patterns/trashvisitor/VCardboard.java create mode 100644 patterns/trashvisitor/VGlass.java create mode 100644 patterns/trashvisitor/VPaper.java create mode 100644 patterns/trashvisitor/VTrash.dat create mode 100644 patterns/trashvisitor/Visitable.java create mode 100644 patterns/trashvisitor/Visitor.java create mode 100644 patterns/visitor/BeeAndFlowers.java create mode 100644 patterns/visualobserver/BoxObserver.java create mode 100644 polymorphism/build.xml create mode 100644 references/AddingClone.java create mode 100644 references/Alias1.java create mode 100644 references/Alias2.java create mode 100644 references/CheckCloneable.java create mode 100644 references/Cloning.java create mode 100644 references/Compete.java create mode 100644 references/CopyConstructor.java create mode 100644 references/DeepCopy.java create mode 100644 references/HorrorFlick.java create mode 100644 references/Immutable1.java create mode 100644 references/Immutable2.java create mode 100644 references/ImmutableInteger.java create mode 100644 references/ImmutableStrings.java create mode 100644 references/LocalCopy.java create mode 100644 references/MutableInteger.java create mode 100644 references/PassReferences.java create mode 100644 references/Snake.java create mode 100644 references/Stringer.java create mode 100644 references/build.xml create mode 100644 remote/build.xml create mode 100644 remote/ptime/DisplayPerfectTime.java create mode 100644 remote/ptime/PerfectTime.java create mode 100644 remote/ptime/PerfectTimeI.java create mode 100644 reusing/build.xml create mode 100644 strings/build.xml create mode 100644 swt/build.xml create mode 100644 typeinfo/build.xml create mode 100644 unittesting/build.xml create mode 100644 xml/build.xml diff --git a/Copyright.txt b/Copyright.txt index 78338904..d30c4a4c 100644 --- a/Copyright.txt +++ b/Copyright.txt @@ -1,4 +1,5 @@ -This computer source code is Copyright (c)2006 MindView, Inc. +//: Copyright.txt +This computer source code is Copyright 2015 MindView LLC All Rights Reserved. Permission to use, copy, modify, and distribute this @@ -20,47 +21,54 @@ Java" is cited as the origin. 3. Permission to incorporate the Source Code into printed media may be obtained by contacting: -MindView, Inc. 5343 Valle Vista La Mesa, California 91941 -Wayne@MindView.net +MindView LLC, PO Box 969, Crested Butte, CO 81224 +MindViewInc@gmail.com 4. The Source Code and documentation are copyrighted by -MindView, Inc. The Source code is provided without express +MindView LLC. The Source code is provided without express or implied warranty of any kind, including any implied warranty of merchantability, fitness for a particular -purpose or non-infringement. MindView, Inc. does not -warrant that the operation of any program that includes the Source Code will be uninterrupted or error-free. MindView, -Inc. makes no representation about the suitability of the +purpose or non-infringement. MindView LLC does not +warrant that the operation of any program that includes the +Source Code will be uninterrupted or error-free. MindView +LLC makes no representation about the suitability of the Source Code or of any software that includes the Source Code for any purpose. The entire risk as to the quality and performance of any program that includes the Source Code is with the user of the Source Code. The user -understands that the Source Code was developed for research and instructional purposes and is advised not to rely +understands that the Source Code was developed for research +and instructional purposes and is advised not to rely exclusively for any reason on the Source Code or any program that includes the Source Code. Should the Source Code or any resulting software prove defective, the user assumes the cost of all necessary servicing, repair, or correction. -5. IN NO EVENT SHALL MINDVIEW, INC., OR ITS PUBLISHER BE +5. IN NO EVENT SHALL MINDVIEW LLC, OR ITS PUBLISHER BE LIABLE TO ANY PARTY UNDER ANY LEGAL THEORY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR PERSONAL INJURIES, ARISING OUT OF THE USE OF THIS SOURCE -CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY TO USE ANY RESULTING PROGRAM, EVEN IF MINDVIEW, INC., OR +CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY +TO USE ANY RESULTING PROGRAM, EVEN IF MINDVIEW LLC, OR ITS PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. MINDVIEW, INC. SPECIFICALLY DISCLAIMS ANY +DAMAGE. MINDVIEW LLC SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, WITHOUT ANY ACCOMPANYING -SERVICES FROM MINDVIEW, INC., AND MINDVIEW, INC. HAS NO +SERVICES FROM MINDVIEW LLC, AND MINDVIEW LLC HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. -Please note that MindView, Inc. maintains a Web site which -is the sole distribution point for electronic copies of the Source Code, http://www.MindView.net (and official mirror -sites), where it is freely available under the terms stated above. +Please note that MindView LLC maintains a Web site which +is the sole distribution point for electronic copies of the +Source Code, http://www.MindView.net (and official mirror +sites), where it is freely available under the terms stated +above. If you think you've found an error in the Source Code, -please submit a correction using the feedback system that you will find at http://www.MindView.net. +please submit a correction using the feedback system that +you will find at http://www.MindView.net. +///:~ diff --git a/access/SingleImport.java b/access/SingleImport.java index ecb7c8dd..5f98455c 100644 --- a/access/SingleImport.java +++ b/access/SingleImport.java @@ -5,4 +5,4 @@ public class SingleImport { public static void main(String[] args) { ArrayList list = new ArrayList(); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/access/build.xml b/access/build.xml new file mode 100644 index 00000000..cfae737b --- /dev/null +++ b/access/build.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java index ca5c51cb..1e3684e7 100644 --- a/annotations/AtUnitExample4.java +++ b/annotations/AtUnitExample4.java @@ -14,7 +14,7 @@ public class AtUnitExample4 { public AtUnitExample4(String word) { this.word = word; } public String getWord() { return word; } public String scrambleWord() { - List chars = new ArrayList(); + List chars = new ArrayList<>(); for(Character c : word.toCharArray()) chars.add(c); Collections.shuffle(chars, rand); diff --git a/annotations/AtUnitExample5.java b/annotations/AtUnitExample5.java index 28c0bb8b..294f74c2 100644 --- a/annotations/AtUnitExample5.java +++ b/annotations/AtUnitExample5.java @@ -7,6 +7,7 @@ import net.mindview.util.*; public class AtUnitExample5 { private String text; public AtUnitExample5(String text) { this.text = text; } + @Override public String toString() { return text; } @TestProperty static PrintWriter output; @TestProperty static int counter; diff --git a/annotations/HashSetTest.java b/annotations/HashSetTest.java index 2aa05334..a8b638e8 100644 --- a/annotations/HashSetTest.java +++ b/annotations/HashSetTest.java @@ -5,7 +5,7 @@ import net.mindview.atunit.*; import net.mindview.util.*; public class HashSetTest { - HashSet testObject = new HashSet(); + HashSet testObject = new HashSet<>(); @Test void initialization() { assert testObject.isEmpty(); } diff --git a/annotations/InterfaceExtractorProcessor.java b/annotations/InterfaceExtractorProcessor.java index 738c5d37..840ba3a5 100644 --- a/annotations/InterfaceExtractorProcessor.java +++ b/annotations/InterfaceExtractorProcessor.java @@ -14,7 +14,7 @@ public class InterfaceExtractorProcessor implements AnnotationProcessor { private final AnnotationProcessorEnvironment env; private ArrayList interfaceMethods = - new ArrayList(); + new ArrayList<>(); public InterfaceExtractorProcessor( AnnotationProcessorEnvironment env) { this.env = env; } public void process() { @@ -58,4 +58,4 @@ public class InterfaceExtractorProcessor } } } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/annotations/InterfaceExtractorProcessorFactory.java b/annotations/InterfaceExtractorProcessorFactory.java index 59c432ca..22aabb97 100644 --- a/annotations/InterfaceExtractorProcessorFactory.java +++ b/annotations/InterfaceExtractorProcessorFactory.java @@ -20,4 +20,4 @@ public class InterfaceExtractorProcessorFactory public Collection supportedOptions() { return Collections.emptySet(); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/annotations/StackL.java b/annotations/StackL.java index 80fd0c03..ce572b05 100644 --- a/annotations/StackL.java +++ b/annotations/StackL.java @@ -4,7 +4,7 @@ package annotations; import java.util.*; public class StackL { - private LinkedList list = new LinkedList(); + private LinkedList list = new LinkedList<>(); public void push(T v) { list.addFirst(v); } public T top() { return list.getFirst(); } public T pop() { return list.removeFirst(); } diff --git a/annotations/UseCaseTracker.java b/annotations/UseCaseTracker.java index 530da6c0..924ee6fc 100644 --- a/annotations/UseCaseTracker.java +++ b/annotations/UseCaseTracker.java @@ -18,7 +18,7 @@ public class UseCaseTracker { } } public static void main(String[] args) { - List useCases = new ArrayList(); + List useCases = new ArrayList<>(); Collections.addAll(useCases, 47, 48, 49, 50); trackUseCases(useCases, PasswordUtils.class); } diff --git a/annotations/build.xml b/annotations/build.xml new file mode 100644 index 00000000..f83f83e4 --- /dev/null +++ b/annotations/build.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/annotations/database/Member.java b/annotations/database/Member.java index 4e832de0..89a815fa 100644 --- a/annotations/database/Member.java +++ b/annotations/database/Member.java @@ -13,6 +13,7 @@ public class Member { public String getHandle() { return handle; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } + @Override public String toString() { return handle; } public Integer getAge() { return age; } } ///:~ diff --git a/annotations/database/TableCreationProcessorFactory.java b/annotations/database/TableCreationProcessorFactory.java index 883d7377..54b100e0 100644 --- a/annotations/database/TableCreationProcessorFactory.java +++ b/annotations/database/TableCreationProcessorFactory.java @@ -98,4 +98,4 @@ public class TableCreationProcessorFactory } } } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/annotations/database/TableCreator.java b/annotations/database/TableCreator.java index 14685ae1..37953dde 100644 --- a/annotations/database/TableCreator.java +++ b/annotations/database/TableCreator.java @@ -24,7 +24,7 @@ public class TableCreator { // If the name is empty, use the Class name: if(tableName.length() < 1) tableName = cl.getName().toUpperCase(); - List columnDefs = new ArrayList(); + List columnDefs = new ArrayList<>(); for(Field field : cl.getDeclaredFields()) { String columnName = null; Annotation[] anns = field.getDeclaredAnnotations(); diff --git a/arrays/ArrayOfGenerics.java b/arrays/ArrayOfGenerics.java index d831bb5c..c48ce23f 100644 --- a/arrays/ArrayOfGenerics.java +++ b/arrays/ArrayOfGenerics.java @@ -8,14 +8,14 @@ public class ArrayOfGenerics { List[] ls; List[] la = new List[10]; ls = (List[])la; // "Unchecked" warning - ls[0] = new ArrayList(); + ls[0] = new ArrayList<>(); // Compile-time checking produces an error: //! ls[1] = new ArrayList(); // The problem: List is a subtype of Object Object[] objects = ls; // So assignment is OK // Compiles and runs without complaint: - objects[1] = new ArrayList(); + objects[1] = new ArrayList<>(); // However, if your needs are straightforward it is // possible to create an array of generics, albeit @@ -23,6 +23,6 @@ public class ArrayOfGenerics { List[] spheres = (List[])new List[10]; for(int i = 0; i < spheres.length; i++) - spheres[i] = new ArrayList(); + spheres[i] = new ArrayList<>(); } } ///:~ diff --git a/arrays/CompType.java b/arrays/CompType.java index 77d56fff..aa19da10 100644 --- a/arrays/CompType.java +++ b/arrays/CompType.java @@ -12,18 +12,21 @@ public class CompType implements Comparable { i = n1; j = n2; } + @Override public String toString() { String result = "[i = " + i + ", j = " + j + "]"; if(count++ % 3 == 0) result += "\n"; return result; } + @Override public int compareTo(CompType rv) { return (i < rv.i ? -1 : (i == rv.i ? 0 : 1)); } private static Random r = new Random(47); public static Generator generator() { return new Generator() { + @Override public CompType next() { return new CompType(r.nextInt(100),r.nextInt(100)); } diff --git a/arrays/ContainerComparison.java b/arrays/ContainerComparison.java index bb0311b6..288b4a28 100644 --- a/arrays/ContainerComparison.java +++ b/arrays/ContainerComparison.java @@ -5,6 +5,7 @@ import static net.mindview.util.Print.*; class BerylliumSphere { private static long counter; private final long id = counter++; + @Override public String toString() { return "Sphere " + id; } } @@ -16,8 +17,7 @@ public class ContainerComparison { print(Arrays.toString(spheres)); print(spheres[4]); - List sphereList = - new ArrayList(); + List sphereList= new ArrayList<>(); for(int i = 0; i < 5; i++) sphereList.add(new BerylliumSphere()); print(sphereList); @@ -27,7 +27,7 @@ public class ContainerComparison { print(Arrays.toString(integers)); print(integers[4]); - List intList = new ArrayList( + List intList = new ArrayList<>( Arrays.asList(0, 1, 2, 3, 4, 5)); intList.add(97); print(intList); diff --git a/arrays/PythonLists.py b/arrays/PythonLists.py new file mode 100644 index 00000000..79a50460 --- /dev/null +++ b/arrays/PythonLists.py @@ -0,0 +1,23 @@ +#: arrays/PythonLists.py + +aList = [1, 2, 3, 4, 5] +print(type(aList)) # +print(aList) # [1, 2, 3, 4, 5] +print(aList[4]) # 5 Basic list indexing +aList.append(6) # lists can be resized +aList += [7, 8] # Add a list to a list +print(aList) # [1, 2, 3, 4, 5, 6, 7, 8] +aSlice = aList[2:4] +print(aSlice) # [3, 4] + +class MyList(list): # Inherit from list + # Define a method, 'this' pointer is explicit: + def getReversed(self): + reversed = self[:] # Copy list using slices + reversed.reverse() # Built-in list method + return reversed + +list2 = MyList(aList) # No 'new' needed for object creation +print(type(list2)) # +print(list2.getReversed()) # [8, 7, 6, 5, 4, 3, 2, 1] +#:~ diff --git a/arrays/build.xml b/arrays/build.xml new file mode 100644 index 00000000..605f4ea7 --- /dev/null +++ b/arrays/build.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assertions/Assert1.java b/assertions/Assert1.java new file mode 100644 index 00000000..63ced5f4 --- /dev/null +++ b/assertions/Assert1.java @@ -0,0 +1,11 @@ +//: assertions/Assert1.java +// Non-informative style of assert +// Compile with: javac -source 1.4 Assert1.java +// {JVMArgs: -ea} // Must run with -ea +// {ThrowsException} + +public class Assert1 { + public static void main(String[] args) { + assert false; + } +} ///:~ diff --git a/assertions/Assert2.java b/assertions/Assert2.java new file mode 100644 index 00000000..b5bad5c1 --- /dev/null +++ b/assertions/Assert2.java @@ -0,0 +1,10 @@ +//: assertions/Assert2.java +// Assert with an informative message +// {JVMArgs: -ea} +// {ThrowsException} + +public class Assert2 { + public static void main(String[] args) { + assert false: "Here's a message saying what happened"; + } +} ///:~ diff --git a/assertions/LoaderAssertions.java b/assertions/LoaderAssertions.java new file mode 100644 index 00000000..2dc4699b --- /dev/null +++ b/assertions/LoaderAssertions.java @@ -0,0 +1,18 @@ +//: assertions/LoaderAssertions.java +// Using the class loader to enable assertions +// Compile with: javac -source 1.4 LoaderAssertions.java +// {ThrowsException} + +public class LoaderAssertions { + public static void main(String[] args) { + ClassLoader.getSystemClassLoader() + .setDefaultAssertionStatus(true); + new Loaded().go(); + } +} + +class Loaded { + public void go() { + assert false: "Loaded.go()"; + } +} ///:~ diff --git a/assertions/Queue.java b/assertions/Queue.java new file mode 100644 index 00000000..bf177318 --- /dev/null +++ b/assertions/Queue.java @@ -0,0 +1,172 @@ +//: assertions/Queue.java +// Demonstration of Design by Contract (DBC) combined +// with white-box unit testing. +// {Depends: junit.jar} +import junit.framework.*; +import java.util.*; + +public class Queue { + private Object[] data; + private int + in = 0, // Next available storage space + out = 0; // Next gettable object + // Has it wrapped around the circular queue? + private boolean wrapped = false; + public static class + QueueException extends RuntimeException { + public QueueException(String why) { super(why); } + } + public Queue(int size) { + data = new Object[size]; + assert invariant(); // Must be true after construction + } + public boolean empty() { + return !wrapped && in == out; + } + public boolean full() { + return wrapped && in == out; + } + public void put(Object item) { + precondition(item != null, "put() null item"); + precondition(!full(), "put() into full Queue"); + assert invariant(); + data[in++] = item; + if(in >= data.length) { + in = 0; + wrapped = true; + } + assert invariant(); + } + public Object get() { + precondition(!empty(), "get() from empty Queue"); + assert invariant(); + Object returnVal = data[out]; + data[out] = null; + out++; + if(out >= data.length) { + out = 0; + wrapped = false; + } + assert postcondition( + returnVal != null, "Null item in Queue"); + assert invariant(); + return returnVal; + } + // Design-by-contract support methods: + private static void + precondition(boolean cond, String msg) { + if(!cond) throw new QueueException(msg); + } + private static boolean + postcondition(boolean cond, String msg) { + if(!cond) throw new QueueException(msg); + return true; + } + private boolean invariant() { + // Guarantee that no null values are in the + // region of 'data' that holds objects: + for(int i = out; i != in; i = (i + 1) % data.length) + if(data[i] == null) + throw new QueueException("null in queue"); + // Guarantee that only null values are outside the + // region of 'data' that holds objects: + if(full()) return true; + for(int i = in; i != out; i = (i + 1) % data.length) + if(data[i] != null) + throw new QueueException( + "non-null outside of queue range: " + dump()); + return true; + } + private String dump() { + return "in = " + in + + ", out = " + out + + ", full() = " + full() + + ", empty() = " + empty() + + ", queue = " + Arrays.asList(data); + } + // JUnit testing. + // As an inner class, this has access to privates: + public static class WhiteBoxTest extends TestCase { + private Queue queue = new Queue(10); + private int i = 0; + public WhiteBoxTest(String name) { + super(name); + while(i < 5) // Preload with some data + queue.put("" + i++); + } + // Support methods: + private void showFullness() { + assertTrue(queue.full()); + assertFalse(queue.empty()); + // Dump is private, white-box testing allows access: + System.out.println(queue.dump()); + } + private void showEmptiness() { + assertFalse(queue.full()); + assertTrue(queue.empty()); + System.out.println(queue.dump()); + } + public void testFull() { + System.out.println("testFull"); + System.out.println(queue.dump()); + System.out.println(queue.get()); + System.out.println(queue.get()); + while(!queue.full()) + queue.put("" + i++); + String msg = ""; + try { + queue.put(""); + } catch(QueueException e) { + msg = e.getMessage(); + System.out.println(msg); + } + assertEquals(msg, "put() into full Queue"); + showFullness(); + } + public void testEmpty() { + System.out.println("testEmpty"); + while(!queue.empty()) + System.out.println(queue.get()); + String msg = ""; + try { + queue.get(); + } catch(QueueException e) { + msg = e.getMessage(); + System.out.println(msg); + } + assertEquals(msg, "get() from empty Queue"); + showEmptiness(); + } + public void testNullPut() { + System.out.println("testNullPut"); + String msg = ""; + try { + queue.put(null); + } catch(QueueException e) { + msg = e.getMessage(); + System.out.println(msg); + } + assertEquals(msg, "put() null item"); + } + public void testCircularity() { + System.out.println("testCircularity"); + while(!queue.full()) + queue.put("" + i++); + showFullness(); + // White-box testing accesses private field: + assertTrue(queue.wrapped); + while(!queue.empty()) + System.out.println(queue.get()); + showEmptiness(); + while(!queue.full()) + queue.put("" + i++); + showFullness(); + while(!queue.empty()) + System.out.println(queue.get()); + showEmptiness(); + } + } + public static void main(String[] args) { + junit.textui.TestRunner.run(Queue.WhiteBoxTest.class); + } +} ///:~ diff --git a/assertions/build.xml b/assertions/build.xml new file mode 100644 index 00000000..5c65b0b4 --- /dev/null +++ b/assertions/build.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/concurrency/ActiveObjectDemo.java b/concurrency/ActiveObjectDemo.java index c84ad18a..aa274a3d 100644 --- a/concurrency/ActiveObjectDemo.java +++ b/concurrency/ActiveObjectDemo.java @@ -23,6 +23,7 @@ public class ActiveObjectDemo { public Future calculateInt(final int x, final int y) { return ex.submit(new Callable() { + @Override public Integer call() { print("starting " + x + " + " + y); pause(500); @@ -33,6 +34,7 @@ public class ActiveObjectDemo { public Future calculateFloat(final float x, final float y) { return ex.submit(new Callable() { + @Override public Float call() { print("starting " + x + " + " + y); pause(2000); @@ -45,7 +47,7 @@ public class ActiveObjectDemo { ActiveObjectDemo d1 = new ActiveObjectDemo(); // Prevents ConcurrentModificationException: List> results = - new CopyOnWriteArrayList>(); + new CopyOnWriteArrayList<>(); for(float f = 0.0f; f < 1.0f; f += 0.2f) results.add(d1.calculateFloat(f, f)); for(int i = 0; i < 5; i++) diff --git a/concurrency/AtomicEvenGenerator.java b/concurrency/AtomicEvenGenerator.java index 4ca8797b..c355f282 100644 --- a/concurrency/AtomicEvenGenerator.java +++ b/concurrency/AtomicEvenGenerator.java @@ -1,11 +1,12 @@ //: concurrency/AtomicEvenGenerator.java // Atomic classes are occasionally useful in regular code. -// {RunByHand} +// {TimeOutDuringTesting} import java.util.concurrent.atomic.*; public class AtomicEvenGenerator extends IntGenerator { private AtomicInteger currentEvenValue = new AtomicInteger(0); + @Override public int next() { return currentEvenValue.addAndGet(2); } diff --git a/concurrency/AtomicIntegerTest.java b/concurrency/AtomicIntegerTest.java index 5ae816aa..8ef05eff 100644 --- a/concurrency/AtomicIntegerTest.java +++ b/concurrency/AtomicIntegerTest.java @@ -7,12 +7,14 @@ public class AtomicIntegerTest implements Runnable { private AtomicInteger i = new AtomicInteger(0); public int getValue() { return i.get(); } private void evenIncrement() { i.addAndGet(2); } + @Override public void run() { while(true) evenIncrement(); } public static void main(String[] args) { new Timer().schedule(new TimerTask() { + @Override public void run() { System.err.println("Aborting"); System.exit(0); diff --git a/concurrency/AtomicityTest.java b/concurrency/AtomicityTest.java index 958bdeb7..2fe558b8 100644 --- a/concurrency/AtomicityTest.java +++ b/concurrency/AtomicityTest.java @@ -5,6 +5,7 @@ public class AtomicityTest implements Runnable { private int i = 0; public int getValue() { return i; } private synchronized void evenIncrement() { i++; i++; } + @Override public void run() { while(true) evenIncrement(); diff --git a/concurrency/AttemptLocking.java b/concurrency/AttemptLocking.java index ac2aa9b3..c54df34a 100644 --- a/concurrency/AttemptLocking.java +++ b/concurrency/AttemptLocking.java @@ -37,6 +37,7 @@ public class AttemptLocking { // Now create a separate task to grab the lock: new Thread() { { setDaemon(true); } + @Override public void run() { al.lock.lock(); System.out.println("acquired"); diff --git a/concurrency/BankTellerSimulation.java b/concurrency/BankTellerSimulation.java index fa4d2ebe..b0022385 100644 --- a/concurrency/BankTellerSimulation.java +++ b/concurrency/BankTellerSimulation.java @@ -19,6 +19,7 @@ class CustomerLine extends ArrayBlockingQueue { public CustomerLine(int maxLineSize) { super(maxLineSize); } + @Override public String toString() { if(this.size() == 0) return "[Empty]"; @@ -36,6 +37,7 @@ class CustomerGenerator implements Runnable { public CustomerGenerator(CustomerLine cq) { customers = cq; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -96,9 +98,9 @@ class TellerManager implements Runnable { private ExecutorService exec; private CustomerLine customers; private PriorityQueue workingTellers = - new PriorityQueue(); + new PriorityQueue<>(); private Queue tellersDoingOtherThings = - new LinkedList(); + new LinkedList<>(); private int adjustmentPeriod; public TellerManager(ExecutorService e, @@ -146,6 +148,7 @@ class TellerManager implements Runnable { teller.doSomethingElse(); tellersDoingOtherThings.offer(teller); } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -161,6 +164,7 @@ class TellerManager implements Runnable { } System.out.println(this + "terminating"); } + @Override public String toString() { return "TellerManager "; } } @@ -201,4 +205,4 @@ Teller 0 interrupted Teller 0 terminating CustomerGenerator interrupted CustomerGenerator terminating -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/CallableDemo.java b/concurrency/CallableDemo.java index 2538defa..3d27d8c7 100644 --- a/concurrency/CallableDemo.java +++ b/concurrency/CallableDemo.java @@ -7,6 +7,7 @@ class TaskWithResult implements Callable { public TaskWithResult(int id) { this.id = id; } + @Override public String call() { return "result of TaskWithResult " + id; } @@ -15,8 +16,7 @@ class TaskWithResult implements Callable { public class CallableDemo { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); - ArrayList> results = - new ArrayList>(); + ArrayList> results = new ArrayList<>(); for(int i = 0; i < 10; i++) results.add(exec.submit(new TaskWithResult(i))); for(Future fs : results) diff --git a/concurrency/CaptureUncaughtException.java b/concurrency/CaptureUncaughtException.java index aa33ca6f..6ca80ba6 100644 --- a/concurrency/CaptureUncaughtException.java +++ b/concurrency/CaptureUncaughtException.java @@ -1,8 +1,9 @@ //: concurrency/CaptureUncaughtException.java -// {RunByHand} +// {TimeOutDuringTesting} import java.util.concurrent.*; class ExceptionThread2 implements Runnable { + @Override public void run() { Thread t = Thread.currentThread(); System.out.println("run() by " + t); @@ -14,12 +15,14 @@ class ExceptionThread2 implements Runnable { class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { + @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("caught " + e); } } class HandlerThreadFactory implements ThreadFactory { + @Override public Thread newThread(Runnable r) { System.out.println(this + " creating new Thread"); Thread t = new Thread(r); @@ -45,4 +48,4 @@ eh = MyUncaughtExceptionHandler@1fb8ee3 run() by Thread[Thread-0,5,main] eh = MyUncaughtExceptionHandler@1fb8ee3 caught java.lang.RuntimeException -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/CarBuilder.java b/concurrency/CarBuilder.java index b038fb63..5bf308b6 100644 --- a/concurrency/CarBuilder.java +++ b/concurrency/CarBuilder.java @@ -30,6 +30,7 @@ class ChassisBuilder implements Runnable { private CarQueue carQueue; private int counter = 0; public ChassisBuilder(CarQueue cq) { carQueue = cq; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -59,6 +60,7 @@ class Assembler implements Runnable { } public Car car() { return car; } public CyclicBarrier barrier() { return barrier; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -85,6 +87,7 @@ class Assembler implements Runnable { class Reporter implements Runnable { private CarQueue carQueue; public Reporter(CarQueue cq) { carQueue = cq; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -167,7 +170,7 @@ class WheelRobot extends Robot { class RobotPool { // Quietly prevents identical entries: - private Set pool = new HashSet(); + private Set pool = new HashSet<>(); public synchronized void add(Robot r) { pool.add(r); notifyAll(); diff --git a/concurrency/CloseResource.java b/concurrency/CloseResource.java index 416e763e..aa8ad31a 100644 --- a/concurrency/CloseResource.java +++ b/concurrency/CloseResource.java @@ -1,7 +1,7 @@ //: concurrency/CloseResource.java // Interrupting a blocked task by // closing the underlying resource. -// {RunByHand} +// {TimeOutDuringTesting} import java.net.*; import java.util.concurrent.*; import java.io.*; diff --git a/concurrency/CountDownLatchDemo.java b/concurrency/CountDownLatchDemo.java index 740afe98..62eecaf9 100644 --- a/concurrency/CountDownLatchDemo.java +++ b/concurrency/CountDownLatchDemo.java @@ -12,6 +12,7 @@ class TaskPortion implements Runnable { TaskPortion(CountDownLatch latch) { this.latch = latch; } + @Override public void run() { try { doWork(); @@ -24,6 +25,7 @@ class TaskPortion implements Runnable { TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000)); print(this + "completed"); } + @Override public String toString() { return String.format("%1$-3d ", id); } @@ -37,6 +39,7 @@ class WaitingTask implements Runnable { WaitingTask(CountDownLatch latch) { this.latch = latch; } + @Override public void run() { try { latch.await(); @@ -45,6 +48,7 @@ class WaitingTask implements Runnable { print(this + " interrupted"); } } + @Override public String toString() { return String.format("WaitingTask %1$-3d ", id); } diff --git a/concurrency/CriticalSection.java b/concurrency/CriticalSection.java index 9ba36521..8e11ed68 100644 --- a/concurrency/CriticalSection.java +++ b/concurrency/CriticalSection.java @@ -1,5 +1,6 @@ //: concurrency/CriticalSection.java -// {RunByHand} (Behavior may have changed in Java 8). +// {TimeOutDuringTesting} +// (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. @@ -19,6 +20,7 @@ class Pair { // Not thread-safe public int getY() { return y; } public void incrementX() { x++; } public void incrementY() { y++; } + @Override public String toString() { return "x: " + x + ", y: " + y; } @@ -40,7 +42,7 @@ abstract class PairManager { AtomicInteger checkCounter = new AtomicInteger(0); protected Pair p = new Pair(); private List storage = - Collections.synchronizedList(new ArrayList()); + Collections.synchronizedList(new ArrayList<>()); public synchronized Pair getPair() { // Make a copy to keep the original safe: return new Pair(p.getX(), p.getY()); @@ -57,6 +59,7 @@ abstract class PairManager { // Synchronize the entire method: class PairManager1 extends PairManager { + @Override public synchronized void increment() { p.incrementX(); p.incrementY(); @@ -66,6 +69,7 @@ class PairManager1 extends PairManager { // Use a critical section: class PairManager2 extends PairManager { + @Override public void increment() { Pair temp; synchronized(this) { @@ -82,10 +86,12 @@ class PairManipulator implements Runnable { public PairManipulator(PairManager pm) { this.pm = pm; } + @Override public void run() { while(true) pm.increment(); } + @Override public String toString() { return "Pair: " + pm.getPair() + " checkCounter = " + pm.checkCounter.get(); @@ -97,6 +103,7 @@ class PairChecker implements Runnable { public PairChecker(PairManager pm) { this.pm = pm; } + @Override public void run() { while(true) { pm.checkCounter.incrementAndGet(); @@ -137,4 +144,4 @@ public class CriticalSection { } /* Output: (Sample) pm1: Pair: x: 15, y: 15 checkCounter = 272565 pm2: Pair: x: 16, y: 16 checkCounter = 3956974 -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/DaemonFromFactory.java b/concurrency/DaemonFromFactory.java index 150cacda..c6fad692 100644 --- a/concurrency/DaemonFromFactory.java +++ b/concurrency/DaemonFromFactory.java @@ -5,6 +5,7 @@ import net.mindview.util.*; import static net.mindview.util.Print.*; public class DaemonFromFactory implements Runnable { + @Override public void run() { try { while(true) { diff --git a/concurrency/Daemons.java b/concurrency/Daemons.java index 60000956..bff30b86 100644 --- a/concurrency/Daemons.java +++ b/concurrency/Daemons.java @@ -5,6 +5,7 @@ import static net.mindview.util.Print.*; class Daemon implements Runnable { private Thread[] t = new Thread[10]; + @Override public void run() { for(int i = 0; i < t.length; i++) { t[i] = new Thread(new DaemonSpawn()); @@ -20,6 +21,7 @@ class Daemon implements Runnable { } class DaemonSpawn implements Runnable { + @Override public void run() { while(true) Thread.yield(); diff --git a/concurrency/DaemonsDontRunFinally.java b/concurrency/DaemonsDontRunFinally.java index 0db66da3..743558b6 100644 --- a/concurrency/DaemonsDontRunFinally.java +++ b/concurrency/DaemonsDontRunFinally.java @@ -4,6 +4,7 @@ import java.util.concurrent.*; import static net.mindview.util.Print.*; class ADaemon implements Runnable { + @Override public void run() { try { print("Starting ADaemon"); diff --git a/concurrency/DelayQueueDemo.java b/concurrency/DelayQueueDemo.java index 838c2aa6..1b42e8d6 100644 --- a/concurrency/DelayQueueDemo.java +++ b/concurrency/DelayQueueDemo.java @@ -10,24 +10,28 @@ class DelayedTask implements Runnable, Delayed { private final int delta; private final long trigger; protected static List sequence = - new ArrayList(); + new ArrayList<>(); public DelayedTask(int delayInMilliseconds) { delta = delayInMilliseconds; trigger = System.nanoTime() + NANOSECONDS.convert(delta, MILLISECONDS); sequence.add(this); } + @Override public long getDelay(TimeUnit unit) { return unit.convert( trigger - System.nanoTime(), NANOSECONDS); } + @Override public int compareTo(Delayed arg) { DelayedTask that = (DelayedTask)arg; if(trigger < that.trigger) return -1; if(trigger > that.trigger) return 1; return 0; } + @Override public void run() { printnb(this + " "); } + @Override public String toString() { return String.format("[%1$-4d]", delta) + " Task " + id; @@ -41,6 +45,7 @@ class DelayedTask implements Runnable, Delayed { super(delay); exec = e; } + @Override public void run() { for(DelayedTask pt : sequence) { printnb(pt.summary() + " "); @@ -57,6 +62,7 @@ class DelayedTaskConsumer implements Runnable { public DelayedTaskConsumer(DelayQueue q) { this.q = q; } + @Override public void run() { try { while(!Thread.interrupted()) @@ -73,7 +79,7 @@ public class DelayQueueDemo { Random rand = new Random(47); ExecutorService exec = Executors.newCachedThreadPool(); DelayQueue queue = - new DelayQueue(); + new DelayQueue<>(); // Fill with tasks that have random delays: for(int i = 0; i < 20; i++) queue.put(new DelayedTask(rand.nextInt(5000))); diff --git a/concurrency/EvenChecker.java b/concurrency/EvenChecker.java index c1c96e69..7874581d 100644 --- a/concurrency/EvenChecker.java +++ b/concurrency/EvenChecker.java @@ -8,6 +8,7 @@ public class EvenChecker implements Runnable { generator = g; id = ident; } + @Override public void run() { while(!generator.isCanceled()) { int val = generator.next(); diff --git a/concurrency/EvenGenerator.java b/concurrency/EvenGenerator.java index 33497e6d..4a5136de 100644 --- a/concurrency/EvenGenerator.java +++ b/concurrency/EvenGenerator.java @@ -3,6 +3,7 @@ public class EvenGenerator extends IntGenerator { private int currentEvenValue = 0; + @Override public int next() { ++currentEvenValue; // Danger point here! ++currentEvenValue; diff --git a/concurrency/ExceptionThread.java b/concurrency/ExceptionThread.java index 469e4e94..386d6ed7 100644 --- a/concurrency/ExceptionThread.java +++ b/concurrency/ExceptionThread.java @@ -3,6 +3,7 @@ import java.util.concurrent.*; public class ExceptionThread implements Runnable { + @Override public void run() { throw new RuntimeException(); } diff --git a/concurrency/ExchangerDemo.java b/concurrency/ExchangerDemo.java index e03b559d..467c722a 100644 --- a/concurrency/ExchangerDemo.java +++ b/concurrency/ExchangerDemo.java @@ -13,6 +13,7 @@ class ExchangerProducer implements Runnable { generator = gen; this.holder = holder; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -35,6 +36,7 @@ class ExchangerConsumer implements Runnable { exchanger = ex; this.holder = holder; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -60,14 +62,14 @@ public class ExchangerDemo { if(args.length > 1) delay = new Integer(args[1]); ExecutorService exec = Executors.newCachedThreadPool(); - Exchanger> xc = new Exchanger>(); + Exchanger> xc = new Exchanger<>(); List - producerList = new CopyOnWriteArrayList(), - consumerList = new CopyOnWriteArrayList(); - exec.execute(new ExchangerProducer(xc, + producerList = new CopyOnWriteArrayList<>(), + consumerList = new CopyOnWriteArrayList<>(); + exec.execute(new ExchangerProducer<>(xc, BasicGenerator.create(Fat.class), producerList)); exec.execute( - new ExchangerConsumer(xc,consumerList)); + new ExchangerConsumer<>(xc,consumerList)); TimeUnit.SECONDS.sleep(delay); exec.shutdownNow(); } diff --git a/concurrency/ExplicitCriticalSection.java b/concurrency/ExplicitCriticalSection.java index dbf99dc7..1191ad7f 100644 --- a/concurrency/ExplicitCriticalSection.java +++ b/concurrency/ExplicitCriticalSection.java @@ -7,6 +7,7 @@ import java.util.concurrent.locks.*; // Synchronize the entire method: class ExplicitPairManager1 extends PairManager { private Lock lock = new ReentrantLock(); + @Override public void increment() { lock.lock(); try { @@ -22,6 +23,7 @@ class ExplicitPairManager1 extends PairManager { // Use a critical section: class ExplicitPairManager2 extends PairManager { private Lock lock = new ReentrantLock(); + @Override public void increment() { Pair temp; lock.lock(); @@ -43,4 +45,4 @@ public class ExplicitCriticalSection { pman2 = new ExplicitPairManager2(); CriticalSection.testApproaches(pman1, pman2); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/concurrency/FastSimulation.java b/concurrency/FastSimulation.java index 7a4e3e52..8d60d45e 100644 --- a/concurrency/FastSimulation.java +++ b/concurrency/FastSimulation.java @@ -12,6 +12,7 @@ public class FastSimulation { new AtomicInteger[N_ELEMENTS][N_GENES]; static Random rand = new Random(47); static class Evolver implements Runnable { + @Override public void run() { while(!Thread.interrupted()) { // Randomly select an element to work on: diff --git a/concurrency/Fat.java b/concurrency/Fat.java index 48f849d3..0be5590a 100644 --- a/concurrency/Fat.java +++ b/concurrency/Fat.java @@ -12,5 +12,6 @@ public class Fat { } } public void operation() { System.out.println(this); } + @Override public String toString() { return "Fat id: " + id; } } ///:~ diff --git a/concurrency/GreenhouseScheduler.java b/concurrency/GreenhouseScheduler.java index 4cb3902c..3aefcf37 100644 --- a/concurrency/GreenhouseScheduler.java +++ b/concurrency/GreenhouseScheduler.java @@ -26,6 +26,7 @@ public class GreenhouseScheduler { event, initialDelay, period, TimeUnit.MILLISECONDS); } class LightOn implements Runnable { + @Override public void run() { // Put hardware control code here to // physically turn on the light. @@ -34,6 +35,7 @@ public class GreenhouseScheduler { } } class LightOff implements Runnable { + @Override public void run() { // Put hardware control code here to // physically turn off the light. @@ -42,6 +44,7 @@ public class GreenhouseScheduler { } } class WaterOn implements Runnable { + @Override public void run() { // Put hardware control code here. System.out.println("Turning greenhouse water on"); @@ -49,6 +52,7 @@ public class GreenhouseScheduler { } } class WaterOff implements Runnable { + @Override public void run() { // Put hardware control code here. System.out.println("Turning greenhouse water off"); @@ -56,6 +60,7 @@ public class GreenhouseScheduler { } } class ThermostatNight implements Runnable { + @Override public void run() { // Put hardware control code here. System.out.println("Thermostat to night setting"); @@ -63,6 +68,7 @@ public class GreenhouseScheduler { } } class ThermostatDay implements Runnable { + @Override public void run() { // Put hardware control code here. System.out.println("Thermostat to day setting"); @@ -70,15 +76,18 @@ public class GreenhouseScheduler { } } class Bell implements Runnable { + @Override public void run() { System.out.println("Bing!"); } } class Terminate implements Runnable { + @Override public void run() { System.out.println("Terminating"); scheduler.shutdownNow(); // Must start a separate task to do this job, // since the scheduler was shut down: new Thread() { + @Override public void run() { for(DataPoint d : data) System.out.println(d); @@ -96,6 +105,7 @@ public class GreenhouseScheduler { temperature = temp; humidity = hum; } + @Override public String toString() { return time.getTime() + String.format( @@ -114,8 +124,9 @@ public class GreenhouseScheduler { private int humidityDirection = +1; private Random rand = new Random(47); List data = Collections.synchronizedList( - new ArrayList()); + new ArrayList<>()); class CollectData implements Runnable { + @Override public void run() { System.out.println("Collecting data"); synchronized(GreenhouseScheduler.this) { @@ -153,4 +164,4 @@ public class GreenhouseScheduler { gh.repeat(gh.new ThermostatDay(), 0, 1400); gh.repeat(gh.new CollectData(), 500, 500); } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/concurrency/HorseRace.java b/concurrency/HorseRace.java index 13de71f7..d23f5a99 100644 --- a/concurrency/HorseRace.java +++ b/concurrency/HorseRace.java @@ -12,6 +12,7 @@ class Horse implements Runnable { private static CyclicBarrier barrier; public Horse(CyclicBarrier b) { barrier = b; } public synchronized int getStrides() { return strides; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -27,6 +28,7 @@ class Horse implements Runnable { throw new RuntimeException(e); } } + @Override public String toString() { return "Horse " + id + " "; } public String tracks() { StringBuilder s = new StringBuilder(); @@ -39,12 +41,13 @@ class Horse implements Runnable { public class HorseRace { static final int FINISH_LINE = 75; - private List horses = new ArrayList(); + private List horses = new ArrayList<>(); private ExecutorService exec = Executors.newCachedThreadPool(); private CyclicBarrier barrier; public HorseRace(int nHorses, final int pause) { barrier = new CyclicBarrier(nHorses, new Runnable() { + @Override public void run() { StringBuilder s = new StringBuilder(); for(int i = 0; i < FINISH_LINE; i++) diff --git a/concurrency/Interrupting.java b/concurrency/Interrupting.java index a6cfecfe..c31858c6 100644 --- a/concurrency/Interrupting.java +++ b/concurrency/Interrupting.java @@ -5,6 +5,7 @@ import java.io.*; import static net.mindview.util.Print.*; class SleepBlocked implements Runnable { + @Override public void run() { try { TimeUnit.SECONDS.sleep(100); @@ -18,6 +19,7 @@ class SleepBlocked implements Runnable { class IOBlocked implements Runnable { private InputStream in; public IOBlocked(InputStream is) { in = is; } + @Override public void run() { try { print("Waiting for read():"); @@ -40,11 +42,13 @@ class SynchronizedBlocked implements Runnable { } public SynchronizedBlocked() { new Thread() { + @Override public void run() { f(); // Lock acquired by this thread } }.start(); } + @Override public void run() { print("Trying to call f()"); f(); diff --git a/concurrency/Interrupting2.java b/concurrency/Interrupting2.java index b84b97b2..cd56abf1 100644 --- a/concurrency/Interrupting2.java +++ b/concurrency/Interrupting2.java @@ -24,6 +24,7 @@ class BlockedMutex { class Blocked2 implements Runnable { BlockedMutex blocked = new BlockedMutex(); + @Override public void run() { print("Waiting for f() in BlockedMutex"); blocked.f(); diff --git a/concurrency/InterruptingIdiom.java b/concurrency/InterruptingIdiom.java index 1973be84..7347144f 100644 --- a/concurrency/InterruptingIdiom.java +++ b/concurrency/InterruptingIdiom.java @@ -17,6 +17,7 @@ class NeedsCleanup { class Blocked3 implements Runnable { private volatile double d = 0.0; + @Override public void run() { try { while(!Thread.interrupted()) { diff --git a/concurrency/Joining.java b/concurrency/Joining.java index 4a40c926..0b637615 100644 --- a/concurrency/Joining.java +++ b/concurrency/Joining.java @@ -9,6 +9,7 @@ class Sleeper extends Thread { duration = sleepTime; start(); } + @Override public void run() { try { sleep(duration); @@ -28,6 +29,7 @@ class Joiner extends Thread { this.sleeper = sleeper; start(); } + @Override public void run() { try { sleeper.join(); diff --git a/concurrency/LiftOff.java b/concurrency/LiftOff.java index 6564aedd..d15bcaa7 100644 --- a/concurrency/LiftOff.java +++ b/concurrency/LiftOff.java @@ -13,6 +13,7 @@ public class LiftOff implements Runnable { return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "), "; } + @Override public void run() { while(countDown-- > 0) { System.out.print(status()); diff --git a/concurrency/ListComparisons.java b/concurrency/ListComparisons.java index 66067923..638dd27b 100644 --- a/concurrency/ListComparisons.java +++ b/concurrency/ListComparisons.java @@ -42,7 +42,7 @@ abstract class ListTest extends Tester> { class SynchronizedArrayListTest extends ListTest { List containerInitializer() { return Collections.synchronizedList( - new ArrayList( + new ArrayList<>( new CountingIntegerList(containerSize))); } SynchronizedArrayListTest(int nReaders, int nWriters) { @@ -52,7 +52,7 @@ class SynchronizedArrayListTest extends ListTest { class CopyOnWriteArrayListTest extends ListTest { List containerInitializer() { - return new CopyOnWriteArrayList( + return new CopyOnWriteArrayList<>( new CountingIntegerList(containerSize)); } CopyOnWriteArrayListTest(int nReaders, int nWriters) { diff --git a/concurrency/MapComparisons.java b/concurrency/MapComparisons.java index 76bf4156..6c87fb46 100644 --- a/concurrency/MapComparisons.java +++ b/concurrency/MapComparisons.java @@ -43,7 +43,7 @@ extends Tester> { class SynchronizedHashMapTest extends MapTest { Map containerInitializer() { return Collections.synchronizedMap( - new HashMap( + new HashMap<>( MapData.map( new CountingGenerator.Integer(), new CountingGenerator.Integer(), @@ -56,7 +56,7 @@ class SynchronizedHashMapTest extends MapTest { class ConcurrentHashMapTest extends MapTest { Map containerInitializer() { - return new ConcurrentHashMap( + return new ConcurrentHashMap<>( MapData.map( new CountingGenerator.Integer(), new CountingGenerator.Integer(), containerSize)); diff --git a/concurrency/MultiLock.java b/concurrency/MultiLock.java index f705fec7..6a547137 100644 --- a/concurrency/MultiLock.java +++ b/concurrency/MultiLock.java @@ -18,6 +18,7 @@ public class MultiLock { public static void main(String[] args) throws Exception { final MultiLock multiLock = new MultiLock(); new Thread() { + @Override public void run() { multiLock.f1(10); } diff --git a/concurrency/MutexEvenGenerator.java b/concurrency/MutexEvenGenerator.java index c68cd175..650b2187 100644 --- a/concurrency/MutexEvenGenerator.java +++ b/concurrency/MutexEvenGenerator.java @@ -1,11 +1,12 @@ //: concurrency/MutexEvenGenerator.java // Preventing thread collisions with mutexes. -// {RunByHand} +// {TimeOutDuringTesting} import java.util.concurrent.locks.*; public class MutexEvenGenerator extends IntGenerator { private int currentEvenValue = 0; private Lock lock = new ReentrantLock(); + @Override public int next() { lock.lock(); try { diff --git a/concurrency/NIOInterruption.java b/concurrency/NIOInterruption.java index cdf5cae2..719d1024 100644 --- a/concurrency/NIOInterruption.java +++ b/concurrency/NIOInterruption.java @@ -10,6 +10,7 @@ import static net.mindview.util.Print.*; class NIOBlocked implements Runnable { private final SocketChannel sc; public NIOBlocked(SocketChannel sc) { this.sc = sc; } + @Override public void run() { try { print("Waiting for read() in " + this); diff --git a/concurrency/NaiveExceptionHandling.java b/concurrency/NaiveExceptionHandling.java index 8911e656..4feb1ac3 100644 --- a/concurrency/NaiveExceptionHandling.java +++ b/concurrency/NaiveExceptionHandling.java @@ -13,4 +13,4 @@ public class NaiveExceptionHandling { System.out.println("Exception was handled!"); } } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/concurrency/NotifyVsNotifyAll.java b/concurrency/NotifyVsNotifyAll.java index 8e7f33fa..fdae2b5f 100644 --- a/concurrency/NotifyVsNotifyAll.java +++ b/concurrency/NotifyVsNotifyAll.java @@ -19,12 +19,14 @@ class Blocker { class Task implements Runnable { static Blocker blocker = new Blocker(); + @Override public void run() { blocker.waitingCall(); } } class Task2 implements Runnable { // A separate Blocker object: static Blocker blocker = new Blocker(); + @Override public void run() { blocker.waitingCall(); } } @@ -37,6 +39,7 @@ public class NotifyVsNotifyAll { Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { boolean prod = true; + @Override public void run() { if(prod) { System.out.print("\nnotify() "); diff --git a/concurrency/OrnamentalGarden.java b/concurrency/OrnamentalGarden.java index 5d1aae09..1e17e1ef 100644 --- a/concurrency/OrnamentalGarden.java +++ b/concurrency/OrnamentalGarden.java @@ -19,7 +19,7 @@ class Count { class Entrance implements Runnable { private static Count count = new Count(); private static List entrances = - new ArrayList(); + new ArrayList<>(); private int number = 0; // Doesn't need synchronization to read: private final int id; @@ -32,6 +32,7 @@ class Entrance implements Runnable { // garbage collection of dead tasks: entrances.add(this); } + @Override public void run() { while(!canceled) { synchronized(this) { @@ -47,6 +48,7 @@ class Entrance implements Runnable { print("Stopping " + this); } public synchronized int getValue() { return number; } + @Override public String toString() { return "Entrance " + id + ": " + getValue(); } diff --git a/concurrency/Philosopher.java b/concurrency/Philosopher.java index bd5f6f07..a5ddb961 100644 --- a/concurrency/Philosopher.java +++ b/concurrency/Philosopher.java @@ -22,6 +22,7 @@ public class Philosopher implements Runnable { id = ident; ponderFactor = ponder; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -41,5 +42,6 @@ public class Philosopher implements Runnable { print(this + " " + "exiting via interrupt"); } } + @Override public String toString() { return "Philosopher " + id; } } ///:~ diff --git a/concurrency/PipedIO.java b/concurrency/PipedIO.java index 796f82f3..038a57bd 100644 --- a/concurrency/PipedIO.java +++ b/concurrency/PipedIO.java @@ -9,6 +9,7 @@ class Sender implements Runnable { private Random rand = new Random(47); private PipedWriter out = new PipedWriter(); public PipedWriter getPipedWriter() { return out; } + @Override public void run() { try { while(true) @@ -29,6 +30,7 @@ class Receiver implements Runnable { public Receiver(Sender sender) throws IOException { in = new PipedReader(sender.getPipedWriter()); } + @Override public void run() { try { while(true) { diff --git a/concurrency/Pool.java b/concurrency/Pool.java index bb4ad841..bd9b52db 100644 --- a/concurrency/Pool.java +++ b/concurrency/Pool.java @@ -6,7 +6,7 @@ import java.util.*; public class Pool { private int size; - private List items = new ArrayList(); + private List items = new ArrayList<>(); private volatile boolean[] checkedOut; private Semaphore available; public Pool(Class classObject, int size) { diff --git a/concurrency/PriorityBlockingQueueDemo.java b/concurrency/PriorityBlockingQueueDemo.java index 0f34fc41..9121fc11 100644 --- a/concurrency/PriorityBlockingQueueDemo.java +++ b/concurrency/PriorityBlockingQueueDemo.java @@ -10,15 +10,17 @@ Runnable, Comparable { private final int id = counter++; private final int priority; protected static List sequence = - new ArrayList(); + new ArrayList<>(); public PrioritizedTask(int priority) { this.priority = priority; sequence.add(this); } + @Override public int compareTo(PrioritizedTask arg) { return priority < arg.priority ? 1 : (priority > arg.priority ? -1 : 0); } + @Override public void run() { try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(250)); @@ -27,6 +29,7 @@ Runnable, Comparable { } print(this); } + @Override public String toString() { return String.format("[%1$-3d]", priority) + " Task " + id; @@ -40,6 +43,7 @@ Runnable, Comparable { super(-1); // Lowest priority in this program exec = e; } + @Override public void run() { int count = 0; for(PrioritizedTask pt : sequence) { @@ -63,6 +67,7 @@ class PrioritizedTaskProducer implements Runnable { queue = q; exec = e; // Used for EndSentinel } + @Override public void run() { // Unbounded queue; never blocks. // Fill it up fast with random priorities: @@ -94,6 +99,7 @@ class PrioritizedTaskConsumer implements Runnable { PriorityBlockingQueue q) { this.q = q; } + @Override public void run() { try { while(!Thread.interrupted()) @@ -110,8 +116,8 @@ public class PriorityBlockingQueueDemo { public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); PriorityBlockingQueue queue = - new PriorityBlockingQueue(); + new PriorityBlockingQueue<>(); exec.execute(new PrioritizedTaskProducer(queue, exec)); exec.execute(new PrioritizedTaskConsumer(queue)); } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/concurrency/ReaderWriterList.java b/concurrency/ReaderWriterList.java index 74996444..48d1f1af 100644 --- a/concurrency/ReaderWriterList.java +++ b/concurrency/ReaderWriterList.java @@ -10,7 +10,7 @@ public class ReaderWriterList { private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); public ReaderWriterList(int size, T initialValue) { - lockedList = new ArrayList( + lockedList = new ArrayList<>( Collections.nCopies(size, initialValue)); } public T set(int index, T element) { @@ -45,8 +45,9 @@ class ReaderWriterListTest { private final static int SIZE = 100; private static Random rand = new Random(47); private ReaderWriterList list = - new ReaderWriterList(SIZE, 0); + new ReaderWriterList<>(SIZE, 0); private class Writer implements Runnable { + @Override public void run() { try { for(int i = 0; i < 20; i++) { // 2 second test @@ -61,6 +62,7 @@ class ReaderWriterListTest { } } private class Reader implements Runnable { + @Override public void run() { try { while(!Thread.interrupted()) { @@ -80,4 +82,4 @@ class ReaderWriterListTest { for(int i = 0; i < writers; i++) exec.execute(new Writer()); } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/concurrency/ResponsiveUI.java b/concurrency/ResponsiveUI.java index fb9d89e9..5f03b380 100644 --- a/concurrency/ResponsiveUI.java +++ b/concurrency/ResponsiveUI.java @@ -1,6 +1,6 @@ //: concurrency/ResponsiveUI.java // User interface responsiveness. -// {RunByHand} +// {TimeOutDuringTesting} class UnresponsiveUI { private volatile double d = 1; @@ -17,6 +17,7 @@ public class ResponsiveUI extends Thread { setDaemon(true); start(); } + @Override public void run() { while(true) { d = d + (Math.PI + Math.E) / d; diff --git a/concurrency/Restaurant.java b/concurrency/Restaurant.java index 2a3e9c95..2d0d9ed4 100644 --- a/concurrency/Restaurant.java +++ b/concurrency/Restaurant.java @@ -6,12 +6,14 @@ import static net.mindview.util.Print.*; class Meal { private final int orderNum; public Meal(int orderNum) { this.orderNum = orderNum; } + @Override public String toString() { return "Meal " + orderNum; } } class WaitPerson implements Runnable { private Restaurant restaurant; public WaitPerson(Restaurant r) { restaurant = r; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -35,6 +37,7 @@ class Chef implements Runnable { private Restaurant restaurant; private int count = 0; public Chef(Restaurant r) { restaurant = r; } + @Override public void run() { try { while(!Thread.interrupted()) { diff --git a/concurrency/SelfManaged.java b/concurrency/SelfManaged.java index 732b047d..7ceae3e5 100644 --- a/concurrency/SelfManaged.java +++ b/concurrency/SelfManaged.java @@ -5,10 +5,12 @@ public class SelfManaged implements Runnable { private int countDown = 5; private Thread t = new Thread(this); public SelfManaged() { t.start(); } + @Override public String toString() { return Thread.currentThread().getName() + "(" + countDown + "), "; } + @Override public void run() { while(true) { System.out.print(this); diff --git a/concurrency/SemaphoreDemo.java b/concurrency/SemaphoreDemo.java index 88a5cbd7..cccbe886 100644 --- a/concurrency/SemaphoreDemo.java +++ b/concurrency/SemaphoreDemo.java @@ -12,6 +12,7 @@ class CheckoutTask implements Runnable { public CheckoutTask(Pool pool) { this.pool = pool; } + @Override public void run() { try { T item = pool.checkOut(); @@ -23,6 +24,7 @@ class CheckoutTask implements Runnable { // Acceptable way to terminate } } + @Override public String toString() { return "CheckoutTask " + id + " "; } @@ -31,13 +33,12 @@ class CheckoutTask implements Runnable { public class SemaphoreDemo { final static int SIZE = 25; public static void main(String[] args) throws Exception { - final Pool pool = - new Pool(Fat.class, SIZE); + final Pool pool = new Pool<>(Fat.class, SIZE); ExecutorService exec = Executors.newCachedThreadPool(); for(int i = 0; i < SIZE; i++) - exec.execute(new CheckoutTask(pool)); + exec.execute(new CheckoutTask<>(pool)); print("All CheckoutTasks created"); - List list = new ArrayList(); + List list = new ArrayList<>(); for(int i = 0; i < SIZE; i++) { Fat f = pool.checkOut(); printnb(i + ": main() thread checked out "); @@ -45,6 +46,7 @@ public class SemaphoreDemo { list.add(f); } Future blocked = exec.submit(new Runnable() { + @Override public void run() { try { // Semaphore prevents additional checkout, diff --git a/concurrency/SerialNumberChecker.java b/concurrency/SerialNumberChecker.java index d8ef5477..903eca8c 100644 --- a/concurrency/SerialNumberChecker.java +++ b/concurrency/SerialNumberChecker.java @@ -36,6 +36,7 @@ public class SerialNumberChecker { private static ExecutorService exec = Executors.newCachedThreadPool(); static class SerialChecker implements Runnable { + @Override public void run() { while(true) { int serial = @@ -60,4 +61,4 @@ public class SerialNumberChecker { } } /* Output: (Sample) Duplicate: 8468656 -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/SettingDefaultHandler.java b/concurrency/SettingDefaultHandler.java index 95f266b1..5aad4ad8 100644 --- a/concurrency/SettingDefaultHandler.java +++ b/concurrency/SettingDefaultHandler.java @@ -1,5 +1,5 @@ //: concurrency/SettingDefaultHandler.java -// {RunByHand} +// {TimeOutDuringTesting} import java.util.concurrent.*; public class SettingDefaultHandler { @@ -11,4 +11,4 @@ public class SettingDefaultHandler { } } /* Output: caught java.lang.RuntimeException -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/SimpleDaemons.java b/concurrency/SimpleDaemons.java index 58f8326e..b17f0d20 100644 --- a/concurrency/SimpleDaemons.java +++ b/concurrency/SimpleDaemons.java @@ -4,6 +4,7 @@ import java.util.concurrent.*; import static net.mindview.util.Print.*; public class SimpleDaemons implements Runnable { + @Override public void run() { try { while(true) { diff --git a/concurrency/SimpleMicroBenchmark.java b/concurrency/SimpleMicroBenchmark.java index cc4e1c76..ac2a1f49 100644 --- a/concurrency/SimpleMicroBenchmark.java +++ b/concurrency/SimpleMicroBenchmark.java @@ -8,11 +8,13 @@ abstract class Incrementable { } class SynchronizingTest extends Incrementable { + @Override public synchronized void increment() { ++counter; } } class LockingTest extends Incrementable { private Lock lock = new ReentrantLock(); + @Override public void increment() { lock.lock(); try { diff --git a/concurrency/SimplePriorities.java b/concurrency/SimplePriorities.java index 9691b27e..e20c9167 100644 --- a/concurrency/SimplePriorities.java +++ b/concurrency/SimplePriorities.java @@ -9,9 +9,11 @@ public class SimplePriorities implements Runnable { public SimplePriorities(int priority) { this.priority = priority; } + @Override public String toString() { return Thread.currentThread() + ": " + countDown; } + @Override public void run() { Thread.currentThread().setPriority(priority); while(true) { @@ -46,4 +48,4 @@ Thread[pool-1-thread-1,1,main]: 5 Thread[pool-1-thread-5,1,main]: 5 Thread[pool-1-thread-4,1,main]: 5 ... -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/SimpleThread.java b/concurrency/SimpleThread.java index ef77ba25..56827863 100644 --- a/concurrency/SimpleThread.java +++ b/concurrency/SimpleThread.java @@ -9,9 +9,11 @@ public class SimpleThread extends Thread { super(Integer.toString(++threadCount)); start(); } + @Override public String toString() { return "#" + getName() + "(" + countDown + "), "; } + @Override public void run() { while(true) { System.out.print(this); diff --git a/concurrency/SleepingTask.java b/concurrency/SleepingTask.java index 3c0519d0..0c9ac9f5 100644 --- a/concurrency/SleepingTask.java +++ b/concurrency/SleepingTask.java @@ -3,13 +3,14 @@ import java.util.concurrent.*; public class SleepingTask extends LiftOff { + @Override public void run() { try { while(countDown-- > 0) { System.out.print(status()); // Old-style: // Thread.sleep(100); - // Java SE5/6-style: + // Java 5/6-style: TimeUnit.MILLISECONDS.sleep(100); } } catch(InterruptedException e) { diff --git a/concurrency/SyncObject.java b/concurrency/SyncObject.java index 4aec34f3..65d2739f 100644 --- a/concurrency/SyncObject.java +++ b/concurrency/SyncObject.java @@ -24,6 +24,7 @@ public class SyncObject { public static void main(String[] args) { final DualSynch ds = new DualSynch(); new Thread() { + @Override public void run() { ds.f(); } diff --git a/concurrency/SynchronizationComparisons.java b/concurrency/SynchronizationComparisons.java index 04c79448..693089db 100644 --- a/concurrency/SynchronizationComparisons.java +++ b/concurrency/SynchronizationComparisons.java @@ -29,6 +29,7 @@ abstract class Accumulator { public abstract void accumulate(); public abstract long read(); private class Modifier implements Runnable { + @Override public void run() { for(long i = 0; i < cycles; i++) accumulate(); @@ -41,6 +42,7 @@ abstract class Accumulator { } private class Reader implements Runnable { private volatile long value; + @Override public void run() { for(long i = 0; i < cycles; i++) value = read(); @@ -73,10 +75,12 @@ abstract class Accumulator { class SynchronizedTest extends Accumulator { { id = "synch"; } + @Override public synchronized void accumulate() { value += preLoaded[index++]; if(index >= SIZE) index = 0; } + @Override public synchronized long read() { return value; } @@ -85,6 +89,7 @@ class SynchronizedTest extends Accumulator { class LockTest extends Accumulator { { id = "Lock"; } private Lock lock = new ReentrantLock(); + @Override public void accumulate() { lock.lock(); try { @@ -94,6 +99,7 @@ class LockTest extends Accumulator { lock.unlock(); } } + @Override public long read() { lock.lock(); try { @@ -111,6 +117,7 @@ class AtomicTest extends Accumulator { // Relying on more than one Atomic at a time doesn't // work, so we still have to synchronize. But it gives // a performance indicator: + @Override public synchronized void accumulate() { int i; i = index.getAndIncrement(); @@ -118,7 +125,9 @@ class AtomicTest extends Accumulator { if(++i >= SIZE) index.set(0); } + @Override public synchronized long read() { return value.get(); } + @Override public void report(Accumulator acc2) { printf("%-22s: %.2f\n", "synch/(Atomic-synch)", (double)acc2.duration/ diff --git a/concurrency/SynchronizedEvenGenerator.java b/concurrency/SynchronizedEvenGenerator.java index 08a1130c..9210486e 100644 --- a/concurrency/SynchronizedEvenGenerator.java +++ b/concurrency/SynchronizedEvenGenerator.java @@ -1,10 +1,11 @@ //: concurrency/SynchronizedEvenGenerator.java // Simplifying mutexes with the synchronized keyword. -// {RunByHand} +// {TimeOutDuringTesting} public class SynchronizedEvenGenerator extends IntGenerator { private int currentEvenValue = 0; + @Override public synchronized int next() { ++currentEvenValue; Thread.yield(); // Cause failure faster diff --git a/concurrency/TestBlockingQueues.java b/concurrency/TestBlockingQueues.java index 6bedc6f6..a89f2df6 100644 --- a/concurrency/TestBlockingQueues.java +++ b/concurrency/TestBlockingQueues.java @@ -1,5 +1,5 @@ //: concurrency/TestBlockingQueues.java -// {RunByHand} +// {TimeOutDuringTesting} import java.util.concurrent.*; import java.io.*; import static net.mindview.util.Print.*; @@ -16,6 +16,7 @@ class LiftOffRunner implements Runnable { print("Interrupted during put()"); } } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -58,10 +59,10 @@ public class TestBlockingQueues { } public static void main(String[] args) { test("LinkedBlockingQueue", // Unlimited size - new LinkedBlockingQueue()); + new LinkedBlockingQueue<>()); test("ArrayBlockingQueue", // Fixed size - new ArrayBlockingQueue(3)); + new ArrayBlockingQueue<>(3)); test("SynchronousQueue", // Size of 1 - new SynchronousQueue()); + new SynchronousQueue<>()); } } ///:~ diff --git a/concurrency/ThreadLocalVariableHolder.java b/concurrency/ThreadLocalVariableHolder.java index 65e65810..25bacd8c 100644 --- a/concurrency/ThreadLocalVariableHolder.java +++ b/concurrency/ThreadLocalVariableHolder.java @@ -6,6 +6,7 @@ import java.util.*; class Accessor implements Runnable { private final int id; public Accessor(int idn) { id = idn; } + @Override public void run() { while(!Thread.currentThread().isInterrupted()) { ThreadLocalVariableHolder.increment(); @@ -13,6 +14,7 @@ class Accessor implements Runnable { Thread.yield(); } } + @Override public String toString() { return "#" + id + ": " + ThreadLocalVariableHolder.get(); @@ -23,6 +25,7 @@ public class ThreadLocalVariableHolder { private static ThreadLocal value = new ThreadLocal() { private Random rand = new Random(47); + @Override protected synchronized Integer initialValue() { return rand.nextInt(10000); } diff --git a/concurrency/ThreadVariations.java b/concurrency/ThreadVariations.java index 58dfaf36..5316a34e 100644 --- a/concurrency/ThreadVariations.java +++ b/concurrency/ThreadVariations.java @@ -12,6 +12,7 @@ class InnerThread1 { super(name); start(); } + @Override public void run() { try { while(true) { @@ -23,6 +24,7 @@ class InnerThread1 { print("interrupted"); } } + @Override public String toString() { return getName() + ": " + countDown; } @@ -38,6 +40,7 @@ class InnerThread2 { private Thread t; public InnerThread2(String name) { t = new Thread(name) { + @Override public void run() { try { while(true) { @@ -49,6 +52,7 @@ class InnerThread2 { print("sleep() interrupted"); } } + @Override public String toString() { return getName() + ": " + countDown; } @@ -67,6 +71,7 @@ class InnerRunnable1 { t = new Thread(this, name); t.start(); } + @Override public void run() { try { while(true) { @@ -78,6 +83,7 @@ class InnerRunnable1 { print("sleep() interrupted"); } } + @Override public String toString() { return t.getName() + ": " + countDown; } @@ -93,6 +99,7 @@ class InnerRunnable2 { private Thread t; public InnerRunnable2(String name) { t = new Thread(new Runnable() { + @Override public void run() { try { while(true) { @@ -104,6 +111,7 @@ class InnerRunnable2 { print("sleep() interrupted"); } } + @Override public String toString() { return Thread.currentThread().getName() + ": " + countDown; @@ -122,6 +130,7 @@ class ThreadMethod { public void runTask() { if(t == null) { t = new Thread(name) { + @Override public void run() { try { while(true) { @@ -133,6 +142,7 @@ class ThreadMethod { print("sleep() interrupted"); } } + @Override public String toString() { return getName() + ": " + countDown; } diff --git a/concurrency/ToastOMatic.java b/concurrency/ToastOMatic.java index 6969df3b..82af0021 100644 --- a/concurrency/ToastOMatic.java +++ b/concurrency/ToastOMatic.java @@ -13,6 +13,7 @@ class Toast { public void jam() { status = Status.JAMMED; } public Status getStatus() { return status; } public int getId() { return id; } + @Override public String toString() { return "Toast " + id + ": " + status; } @@ -25,6 +26,7 @@ class Toaster implements Runnable { private int count = 0; private Random rand = new Random(47); public Toaster(ToastQueue tq) { toastQueue = tq; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -50,6 +52,7 @@ class Butterer implements Runnable { dryQueue = dry; butteredQueue = buttered; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -73,6 +76,7 @@ class Jammer implements Runnable { butteredQueue = buttered; finishedQueue = finished; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -96,6 +100,7 @@ class Eater implements Runnable { public Eater(ToastQueue finished) { finishedQueue = finished; } + @Override public void run() { try { while(!Thread.interrupted()) { diff --git a/concurrency/build.xml b/concurrency/build.xml new file mode 100644 index 00000000..eab4523a --- /dev/null +++ b/concurrency/build.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/concurrency/restaurant2/RestaurantWithQueues.java b/concurrency/restaurant2/RestaurantWithQueues.java index acf52ed8..d9c39961 100644 --- a/concurrency/restaurant2/RestaurantWithQueues.java +++ b/concurrency/restaurant2/RestaurantWithQueues.java @@ -21,6 +21,7 @@ class Order { // (A data-transfer object) public Food item() { return food; } public Customer getCustomer() { return customer; } public WaitPerson getWaitPerson() { return waitPerson; } + @Override public String toString() { return "Order: " + id + " item: " + food + " for: " + customer + @@ -38,6 +39,7 @@ class Plate { } public Order getOrder() { return order; } public Food getFood() { return food; } + @Override public String toString() { return food.toString(); } } @@ -47,7 +49,7 @@ class Customer implements Runnable { private final WaitPerson waitPerson; // Only one course at a time can be received: private SynchronousQueue placeSetting = - new SynchronousQueue(); + new SynchronousQueue<>(); public Customer(WaitPerson w) { waitPerson = w; } public void deliver(Plate p) throws InterruptedException { @@ -55,6 +57,7 @@ class Customer implements Runnable { // eating the previous course: placeSetting.put(p); } + @Override public void run() { for(Course course : Course.values()) { Food food = course.randomSelection(); @@ -70,6 +73,7 @@ class Customer implements Runnable { } print(this + "finished meal, leaving"); } + @Override public String toString() { return "Customer " + id + " "; } @@ -80,7 +84,7 @@ class WaitPerson implements Runnable { private final int id = counter++; private final Restaurant restaurant; BlockingQueue filledOrders = - new LinkedBlockingQueue(); + new LinkedBlockingQueue<>(); public WaitPerson(Restaurant rest) { restaurant = rest; } public void placeOrder(Customer cust, Food food) { try { @@ -91,6 +95,7 @@ class WaitPerson implements Runnable { print(this + " placeOrder interrupted"); } } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -106,6 +111,7 @@ class WaitPerson implements Runnable { } print(this + " off duty"); } + @Override public String toString() { return "WaitPerson " + id + " "; } @@ -117,6 +123,7 @@ class Chef implements Runnable { private final Restaurant restaurant; private static Random rand = new Random(47); public Chef(Restaurant rest) { restaurant = rest; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -133,17 +140,18 @@ class Chef implements Runnable { } print(this + " off duty"); } + @Override public String toString() { return "Chef " + id + " "; } } class Restaurant implements Runnable { private List waitPersons = - new ArrayList(); - private List chefs = new ArrayList(); + new ArrayList<>(); + private List chefs = new ArrayList<>(); private ExecutorService exec; private static Random rand = new Random(47); BlockingQueue - orders = new LinkedBlockingQueue(); + orders = new LinkedBlockingQueue<>(); public Restaurant(ExecutorService e, int nWaitPersons, int nChefs) { exec = e; @@ -158,6 +166,7 @@ class Restaurant implements Runnable { exec.execute(chef); } } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -203,4 +212,4 @@ WaitPerson 3 received VINDALOO delivering to Customer 0 Customer 0 eating VINDALOO WaitPerson 0 received FRUIT delivering to Customer 1 ... -*///:~ \ No newline at end of file +*///:~ diff --git a/concurrency/waxomatic/WaxOMatic.java b/concurrency/waxomatic/WaxOMatic.java index 2e693371..74bc51d5 100644 --- a/concurrency/waxomatic/WaxOMatic.java +++ b/concurrency/waxomatic/WaxOMatic.java @@ -29,6 +29,7 @@ class Car { class WaxOn implements Runnable { private Car car; public WaxOn(Car c) { car = c; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -47,6 +48,7 @@ class WaxOn implements Runnable { class WaxOff implements Runnable { private Car car; public WaxOff(Car c) { car = c; } + @Override public void run() { try { while(!Thread.interrupted()) { diff --git a/concurrency/waxomatic2/WaxOMatic2.java b/concurrency/waxomatic2/WaxOMatic2.java index 1f817c81..836b301e 100644 --- a/concurrency/waxomatic2/WaxOMatic2.java +++ b/concurrency/waxomatic2/WaxOMatic2.java @@ -50,6 +50,7 @@ class Car { class WaxOn implements Runnable { private Car car; public WaxOn(Car c) { car = c; } + @Override public void run() { try { while(!Thread.interrupted()) { @@ -68,6 +69,7 @@ class WaxOn implements Runnable { class WaxOff implements Runnable { private Car car; public WaxOff(Car c) { car = c; } + @Override public void run() { try { while(!Thread.interrupted()) { diff --git a/containers/AssociativeArray.java b/containers/AssociativeArray.java index d56ffee4..fe9d466e 100644 --- a/containers/AssociativeArray.java +++ b/containers/AssociativeArray.java @@ -20,6 +20,7 @@ public class AssociativeArray { return (V)pairs[i][1]; return null; // Did not find key } + @Override public String toString() { StringBuilder result = new StringBuilder(); for(int i = 0; i < index; i++) { @@ -33,7 +34,7 @@ public class AssociativeArray { } public static void main(String[] args) { AssociativeArray map = - new AssociativeArray(6); + new AssociativeArray<>(6); map.put("sky", "blue"); map.put("grass", "green"); map.put("ocean", "dancing"); diff --git a/containers/CanonicalMapping.java b/containers/CanonicalMapping.java index 969067d2..56f21ef0 100644 --- a/containers/CanonicalMapping.java +++ b/containers/CanonicalMapping.java @@ -5,12 +5,16 @@ import java.util.*; class Element { private String ident; public Element(String id) { ident = id; } + @Override public String toString() { return ident; } + @Override public int hashCode() { return ident.hashCode(); } + @Override public boolean equals(Object r) { return r instanceof Element && ident.equals(((Element)r).ident); } + @Override protected void finalize() { System.out.println("Finalizing " + getClass().getSimpleName() + " " + ident); @@ -32,8 +36,7 @@ public class CanonicalMapping { if(args.length > 0) size = new Integer(args[0]); Key[] keys = new Key[size]; - WeakHashMap map = - new WeakHashMap(); + WeakHashMap map = new WeakHashMap<>(); for(int i = 0; i < size; i++) { Key k = new Key(Integer.toString(i)); Value v = new Value(Integer.toString(i)); diff --git a/containers/CollectionDataGeneration.java b/containers/CollectionDataGeneration.java index 86364a25..3e9db3a5 100644 --- a/containers/CollectionDataGeneration.java +++ b/containers/CollectionDataGeneration.java @@ -5,14 +5,14 @@ import net.mindview.util.*; public class CollectionDataGeneration { public static void main(String[] args) { - System.out.println(new ArrayList( + System.out.println(new ArrayList<>( CollectionData.list( // Convenience method new RandomGenerator.String(9), 10))); - System.out.println(new HashSet( - new CollectionData( + System.out.println(new HashSet<>( + new CollectionData<>( new RandomGenerator.Integer(), 10))); } } /* Output: [YNzbrnyGc, FOWZnTcQr, GseGZMmJM, RoEsuEcUO, neOEdLsmw, HLGEahKcx, rEqUCBbkI, naMesbtWH, kjUrUkZPg, wsqPzDyCy] -[573, 4779, 871, 4367, 6090, 7882, 2017, 8037, 3455, 299] +[2017, 3455, 4779, 871, 6090, 573, 7882, 299, 8037, 4367] *///:~ diff --git a/containers/CollectionDataTest.java b/containers/CollectionDataTest.java index 8bebe10a..2361eed2 100644 --- a/containers/CollectionDataTest.java +++ b/containers/CollectionDataTest.java @@ -7,13 +7,14 @@ class Government implements Generator { "distributing swords is no basis for a system of " + "government").split(" "); private int index; + @Override public String next() { return foundation[index++]; } } public class CollectionDataTest { public static void main(String[] args) { - Set set = new LinkedHashSet( - new CollectionData(new Government(), 15)); + Set set = new LinkedHashSet<>( + new CollectionData<>(new Government(), 15)); // Using the convenience method: set.addAll(CollectionData.list(new Government(), 15)); System.out.println(set); diff --git a/containers/CollectionMethods.java b/containers/CollectionMethods.java index 7dafc198..340a46a7 100644 --- a/containers/CollectionMethods.java +++ b/containers/CollectionMethods.java @@ -6,7 +6,7 @@ import static net.mindview.util.Print.*; public class CollectionMethods { public static void main(String[] args) { - Collection c = new ArrayList(); + Collection c = new ArrayList<>(); c.addAll(Countries.names(6)); c.add("ten"); c.add("eleven"); @@ -21,7 +21,7 @@ public class CollectionMethods { print("Collections.max(c) = " + Collections.max(c)); print("Collections.min(c) = " + Collections.min(c)); // Add a Collection to another Collection - Collection c2 = new ArrayList(); + Collection c2 = new ArrayList<>(); c2.addAll(Countries.names(6)); c.addAll(c2); print(c); @@ -50,25 +50,25 @@ public class CollectionMethods { // in c2 that also appear in c3: c2.removeAll(c3); print("c2.isEmpty() = " + c2.isEmpty()); - c = new ArrayList(); + c = new ArrayList<>(); c.addAll(Countries.names(6)); print(c); c.clear(); // Remove all elements print("after c.clear():" + c); } } /* Output: -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven] Collections.max(c) = ten Collections.min(c) = ALGERIA -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] -[ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] -[BENIN, BOTSWANA, BULGARIA, BURKINA FASO, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[BENIN, BOTSWANA, BURKINA FASO, BURUNDI, ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] [ten, eleven] -[ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] +[ten, eleven, ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] c.contains(BOTSWANA) = true c.containsAll(c2) = true [ANGOLA, BENIN] c2.isEmpty() = true -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] after c.clear():[] *///:~ diff --git a/containers/CountedString.java b/containers/CountedString.java index b11b1f1b..18c71f2a 100644 --- a/containers/CountedString.java +++ b/containers/CountedString.java @@ -5,7 +5,7 @@ import static net.mindview.util.Print.*; public class CountedString { private static List created = - new ArrayList(); + new ArrayList<>(); private String s; private int id = 0; public CountedString(String str) { @@ -17,10 +17,12 @@ public class CountedString { if(s2.equals(s)) id++; } + @Override public String toString() { return "String: " + s + " id: " + id + " hashCode(): " + hashCode(); } + @Override public int hashCode() { // The very simple approach: // return s.hashCode() * id; @@ -30,6 +32,7 @@ public class CountedString { result = 37 * result + id; return result; } + @Override public boolean equals(Object o) { return o instanceof CountedString && s.equals(((CountedString)o).s) && @@ -37,7 +40,7 @@ public class CountedString { } public static void main(String[] args) { Map map = - new HashMap(); + new HashMap<>(); CountedString[] cs = new CountedString[5]; for(int i = 0; i < cs.length; i++) { cs[i] = new CountedString("hi"); diff --git a/containers/DequeTest.java b/containers/DequeTest.java index 18be0daf..a7dde93d 100644 --- a/containers/DequeTest.java +++ b/containers/DequeTest.java @@ -10,7 +10,7 @@ public class DequeTest { deque.addLast(i); } public static void main(String[] args) { - Deque di = new Deque(); + Deque di = new Deque<>(); fillTest(di); print(di); while(di.size() != 0) diff --git a/containers/Enumerations.java b/containers/Enumerations.java index e2c99df7..c54dc134 100644 --- a/containers/Enumerations.java +++ b/containers/Enumerations.java @@ -6,13 +6,13 @@ import net.mindview.util.*; public class Enumerations { public static void main(String[] args) { Vector v = - new Vector(Countries.names(10)); + new Vector<>(Countries.names(10)); Enumeration e = v.elements(); while(e.hasMoreElements()) System.out.print(e.nextElement() + ", "); // Produce an Enumeration from a Collection: - e = Collections.enumeration(new ArrayList()); + e = Collections.enumeration(new ArrayList<>()); } } /* Output: -ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, +ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, CHAD, *///:~ diff --git a/containers/FailFast.java b/containers/FailFast.java index 6f579f45..a58e216b 100644 --- a/containers/FailFast.java +++ b/containers/FailFast.java @@ -4,7 +4,7 @@ import java.util.*; public class FailFast { public static void main(String[] args) { - Collection c = new ArrayList(); + Collection c = new ArrayList<>(); Iterator it = c.iterator(); c.add("An object"); try { diff --git a/containers/FillingLists.java b/containers/FillingLists.java index b3f6d78f..b468d088 100644 --- a/containers/FillingLists.java +++ b/containers/FillingLists.java @@ -5,6 +5,7 @@ import java.util.*; class StringAddress { private String s; public StringAddress(String s) { this.s = s; } + @Override public String toString() { return super.toString() + " " + s; } @@ -12,7 +13,7 @@ class StringAddress { public class FillingLists { public static void main(String[] args) { - List list= new ArrayList( + List list = new ArrayList<>( Collections.nCopies(4, new StringAddress("Hello"))); System.out.println(list); Collections.fill(list, new StringAddress("World!")); diff --git a/containers/Groundhog.java b/containers/Groundhog.java index 990a6afd..5b72eecd 100644 --- a/containers/Groundhog.java +++ b/containers/Groundhog.java @@ -4,6 +4,7 @@ public class Groundhog { protected int number; public Groundhog(int n) { number = n; } + @Override public String toString() { return "Groundhog #" + number; } diff --git a/containers/Groundhog2.java b/containers/Groundhog2.java index b0c42637..db8f88df 100644 --- a/containers/Groundhog2.java +++ b/containers/Groundhog2.java @@ -4,7 +4,9 @@ public class Groundhog2 extends Groundhog { public Groundhog2(int n) { super(n); } + @Override public int hashCode() { return number; } + @Override public boolean equals(Object o) { return o instanceof Groundhog2 && (number == ((Groundhog2)o).number); diff --git a/containers/IndividualTest.java b/containers/IndividualTest.java index d1d70120..a2c6d009 100644 --- a/containers/IndividualTest.java +++ b/containers/IndividualTest.java @@ -5,7 +5,7 @@ import java.util.*; public class IndividualTest { public static void main(String[] args) { - Set pets = new TreeSet(); + Set pets = new TreeSet<>(); for(List lp : MapOfList.petPeople.values()) for(Pet p : lp) diff --git a/containers/LinkedHashMapDemo.java b/containers/LinkedHashMapDemo.java index da04d33e..ca2a1a13 100644 --- a/containers/LinkedHashMapDemo.java +++ b/containers/LinkedHashMapDemo.java @@ -7,12 +7,10 @@ import static net.mindview.util.Print.*; public class LinkedHashMapDemo { public static void main(String[] args) { LinkedHashMap linkedMap = - new LinkedHashMap( - new CountingMapData(9)); + new LinkedHashMap<>(new CountingMapData(9)); print(linkedMap); // Least-recently-used order: - linkedMap = - new LinkedHashMap(16, 0.75f, true); + linkedMap = new LinkedHashMap<>(16, 0.75f, true); linkedMap.putAll(new CountingMapData(9)); print(linkedMap); for(int i = 0; i < 6; i++) // Cause accesses: diff --git a/containers/ListPerformance.java b/containers/ListPerformance.java index de6e100f..5b097c27 100644 --- a/containers/ListPerformance.java +++ b/containers/ListPerformance.java @@ -8,11 +8,12 @@ public class ListPerformance { static Random rand = new Random(); static int reps = 1000; static List>> tests = - new ArrayList>>(); + new ArrayList<>(); static List>> qTests = - new ArrayList>>(); + new ArrayList<>(); static { tests.add(new Test>("add") { + @Override int test(List list, TestParam tp) { int loops = tp.loops; int listSize = tp.size; @@ -25,6 +26,7 @@ public class ListPerformance { } }); tests.add(new Test>("get") { + @Override int test(List list, TestParam tp) { int loops = tp.loops * reps; int listSize = list.size(); @@ -34,6 +36,7 @@ public class ListPerformance { } }); tests.add(new Test>("set") { + @Override int test(List list, TestParam tp) { int loops = tp.loops * reps; int listSize = list.size(); @@ -43,6 +46,7 @@ public class ListPerformance { } }); tests.add(new Test>("iteradd") { + @Override int test(List list, TestParam tp) { final int LOOPS = 1000000; int half = list.size() / 2; @@ -53,6 +57,7 @@ public class ListPerformance { } }); tests.add(new Test>("insert") { + @Override int test(List list, TestParam tp) { int loops = tp.loops; for(int i = 0; i < loops; i++) @@ -61,6 +66,7 @@ public class ListPerformance { } }); tests.add(new Test>("remove") { + @Override int test(List list, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -75,6 +81,7 @@ public class ListPerformance { }); // Tests for queue behavior: qTests.add(new Test>("addFirst") { + @Override int test(LinkedList list, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -87,6 +94,7 @@ public class ListPerformance { } }); qTests.add(new Test>("addLast") { + @Override int test(LinkedList list, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -100,6 +108,7 @@ public class ListPerformance { }); qTests.add( new Test>("rmFirst") { + @Override int test(LinkedList list, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -113,6 +122,7 @@ public class ListPerformance { } }); qTests.add(new Test>("rmLast") { + @Override int test(LinkedList list, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -164,13 +174,13 @@ public class ListPerformance { 10, 5000, 100, 5000, 1000, 1000, 10000, 200); if(args.length > 0) Tester.defaultParams = TestParam.array(args); - ListTester.run(new ArrayList(), tests); - ListTester.run(new LinkedList(), tests); - ListTester.run(new Vector(), tests); + ListTester.run(new ArrayList<>(), tests); + ListTester.run(new LinkedList<>(), tests); + ListTester.run(new Vector<>(), tests); Tester.fieldWidth = 12; Tester> qTest = new Tester>( - new LinkedList(), qTests); + new LinkedList<>(), qTests); qTest.setHeadline("Queue tests"); qTest.timedTest(); } @@ -205,4 +215,4 @@ public class ListPerformance { 100 98 92 180 179 1000 99 93 216 212 10000 111 109 262 384 -*///:~ \ No newline at end of file +*///:~ diff --git a/containers/ListSortSearch.java b/containers/ListSortSearch.java index 89d137b8..6bf5774e 100644 --- a/containers/ListSortSearch.java +++ b/containers/ListSortSearch.java @@ -6,7 +6,7 @@ import static net.mindview.util.Print.*; public class ListSortSearch { public static void main(String[] args) { List list = - new ArrayList(Utilities.list); + new ArrayList<>(Utilities.list); list.addAll(Utilities.list); print(list); Collections.shuffle(list, new Random(47)); diff --git a/containers/Lists.java b/containers/Lists.java index e26460e2..3085c959 100644 --- a/containers/Lists.java +++ b/containers/Lists.java @@ -87,7 +87,7 @@ public class Lists { } // There are some things that only LinkedLists can do: public static void testLinkedList() { - LinkedList ll = new LinkedList(); + LinkedList ll = new LinkedList<>(); ll.addAll(Countries.names(25)); print(ll); // Treat it like a stack, pushing: @@ -107,19 +107,19 @@ public class Lists { public static void main(String[] args) { // Make and fill a new list each time: basicTest( - new LinkedList(Countries.names(25))); + new LinkedList<>(Countries.names(25))); basicTest( - new ArrayList(Countries.names(25))); + new ArrayList<>(Countries.names(25))); iterMotion( - new LinkedList(Countries.names(25))); + new LinkedList<>(Countries.names(25))); iterMotion( - new ArrayList(Countries.names(25))); + new ArrayList<>(Countries.names(25))); iterManipulation( - new LinkedList(Countries.names(25))); + new LinkedList<>(Countries.names(25))); iterManipulation( - new ArrayList(Countries.names(25))); + new ArrayList<>(Countries.names(25))); testVisual( - new LinkedList(Countries.names(25))); + new LinkedList<>(Countries.names(25))); testLinkedList(); } } /* (Execute to see output) *///:~ diff --git a/containers/MapDataTest.java b/containers/MapDataTest.java index 097bb0b8..051ea26a 100644 --- a/containers/MapDataTest.java +++ b/containers/MapDataTest.java @@ -8,14 +8,18 @@ class Letters implements Generator>, private int size = 9; private int number = 1; private char letter = 'A'; + @Override public Pair next() { - return new Pair( - number++, "" + letter++); + 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(); } diff --git a/containers/MapEntry.java b/containers/MapEntry.java index 7fa84417..38e3ba40 100644 --- a/containers/MapEntry.java +++ b/containers/MapEntry.java @@ -9,17 +9,22 @@ public class MapEntry implements Map.Entry { this.key = key; this.value = value; } + @Override public K getKey() { return key; } + @Override public V getValue() { return value; } + @Override public V setValue(V v) { V result = value; value = v; return result; } + @Override public int hashCode() { return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode()); } + @Override public boolean equals(Object o) { if(!(o instanceof MapEntry)) return false; @SuppressWarnings("unchecked") @@ -30,5 +35,6 @@ public class MapEntry implements Map.Entry { (value == null ? me.getValue()== null : value.equals(me.getValue())); } + @Override public String toString() { return key + "=" + value; } } ///:~ diff --git a/containers/MapPerformance.java b/containers/MapPerformance.java index 187cf83d..fd6afe7d 100644 --- a/containers/MapPerformance.java +++ b/containers/MapPerformance.java @@ -5,9 +5,10 @@ import java.util.*; public class MapPerformance { static List>> tests = - new ArrayList>>(); + new ArrayList<>(); static { tests.add(new Test>("put") { + @Override int test(Map map, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -20,6 +21,7 @@ public class MapPerformance { } }); tests.add(new Test>("get") { + @Override int test(Map map, TestParam tp) { int loops = tp.loops; int span = tp.size * 2; @@ -30,6 +32,7 @@ public class MapPerformance { } }); tests.add(new Test>("iterate") { + @Override int test(Map map, TestParam tp) { int loops = tp.loops * 10; for(int i = 0; i < loops; i ++) { @@ -44,13 +47,13 @@ public class MapPerformance { public static void main(String[] args) { if(args.length > 0) Tester.defaultParams = TestParam.array(args); - Tester.run(new TreeMap(), tests); - Tester.run(new HashMap(), tests); - Tester.run(new LinkedHashMap(),tests); + Tester.run(new TreeMap<>(), tests); + Tester.run(new HashMap<>(), tests); + Tester.run(new LinkedHashMap<>(),tests); Tester.run( - new IdentityHashMap(), tests); - Tester.run(new WeakHashMap(), tests); - Tester.run(new Hashtable(), tests); + new IdentityHashMap<>(), tests); + Tester.run(new WeakHashMap<>(), tests); + Tester.run(new Hashtable<>(), tests); } } /* Output: (Sample) ---------- TreeMap ---------- diff --git a/containers/Maps.java b/containers/Maps.java index a96a4ae6..39520224 100644 --- a/containers/Maps.java +++ b/containers/Maps.java @@ -37,23 +37,23 @@ public class Maps { print("map.isEmpty(): " + map.isEmpty()); } public static void main(String[] args) { - test(new HashMap()); - test(new TreeMap()); - test(new LinkedHashMap()); - test(new IdentityHashMap()); - test(new ConcurrentHashMap()); - test(new WeakHashMap()); + test(new HashMap<>()); + test(new TreeMap<>()); + test(new LinkedHashMap<>()); + test(new IdentityHashMap<>()); + test(new ConcurrentHashMap<>()); + test(new WeakHashMap<>()); } } /* Output: HashMap -Size = 25, Keys: [15, 8, 23, 16, 7, 22, 9, 21, 6, 1, 14, 24, 4, 19, 11, 18, 3, 12, 17, 2, 13, 20, 10, 5, 0] -Values: [P0, I0, X0, Q0, H0, W0, J0, V0, G0, B0, O0, Y0, E0, T0, L0, S0, D0, M0, R0, C0, N0, U0, K0, F0, A0] -{15=P0, 8=I0, 23=X0, 16=Q0, 7=H0, 22=W0, 9=J0, 21=V0, 6=G0, 1=B0, 14=O0, 24=Y0, 4=E0, 19=T0, 11=L0, 18=S0, 3=D0, 12=M0, 17=R0, 2=C0, 13=N0, 20=U0, 10=K0, 5=F0, 0=A0} +Size = 25, Keys: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 24] +Values: [A0, B0, C0, D0, E0, F0, G0, H0, I0, J0, K0, L0, M0, N0, O0, P0, R0, Q0, T0, S0, V0, U0, X0, W0, Y0] +{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0, 10=K0, 11=L0, 12=M0, 13=N0, 14=O0, 15=P0, 17=R0, 16=Q0, 19=T0, 18=S0, 21=V0, 20=U0, 23=X0, 22=W0, 24=Y0} map.containsKey(11): true map.get(11): L0 map.containsValue("F0"): true -First key in map: 15 -Size = 24, Keys: [8, 23, 16, 7, 22, 9, 21, 6, 1, 14, 24, 4, 19, 11, 18, 3, 12, 17, 2, 13, 20, 10, 5, 0] +First key in map: 0 +Size = 24, Keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 24] map.isEmpty(): true map.isEmpty(): true ... diff --git a/containers/Prediction.java b/containers/Prediction.java index 54370d95..b6a90bdf 100644 --- a/containers/Prediction.java +++ b/containers/Prediction.java @@ -5,6 +5,7 @@ import java.util.*; public class Prediction { private static Random rand = new Random(47); private boolean shadow = rand.nextDouble() > 0.5; + @Override public String toString() { if(shadow) return "Six more weeks of Winter!"; diff --git a/containers/QueueBehavior.java b/containers/QueueBehavior.java index 01d6e372..4bf4c541 100644 --- a/containers/QueueBehavior.java +++ b/containers/QueueBehavior.java @@ -17,15 +17,16 @@ public class QueueBehavior { String[] s = ("one two three four five six seven " + "eight nine ten").split(" "); int i; + @Override public String next() { return s[i++]; } } public static void main(String[] args) { - test(new LinkedList(), new Gen()); - test(new PriorityQueue(), new Gen()); - test(new ArrayBlockingQueue(count), new Gen()); - test(new ConcurrentLinkedQueue(), new Gen()); - test(new LinkedBlockingQueue(), new Gen()); - test(new PriorityBlockingQueue(), new Gen()); + test(new LinkedList<>(), new Gen()); + test(new PriorityQueue<>(), new Gen()); + test(new ArrayBlockingQueue<>(count), new Gen()); + test(new ConcurrentLinkedQueue<>(), new Gen()); + test(new LinkedBlockingQueue<>(), new Gen()); + test(new PriorityBlockingQueue<>(), new Gen()); } } /* Output: one two three four five six seven eight nine ten diff --git a/containers/RandomBounds.java b/containers/RandomBounds.java index 631c8a87..1fac6beb 100644 --- a/containers/RandomBounds.java +++ b/containers/RandomBounds.java @@ -1,6 +1,7 @@ //: containers/RandomBounds.java // Does Math.random() produce 0.0 and 1.0? -// {RunByHand} +// {TimeOutDuringTesting} +// {Args: lower} import static net.mindview.util.Print.*; public class RandomBounds { @@ -12,17 +13,19 @@ public class RandomBounds { } public static void main(String[] args) { if(args.length != 1) usage(); - if(args[0].equals("lower")) { - while(Math.random() != 0.0) - ; // Keep trying - print("Produced 0.0!"); + switch(args[0]) { + case "lower": + while(Math.random() != 0.0) + ; // Keep trying + print("Produced 0.0!"); + break; + case "upper": + while(Math.random() != 1.0) + ; // Keep trying + print("Produced 1.0!"); + break; + default: + usage(); } - else if(args[0].equals("upper")) { - while(Math.random() != 1.0) - ; // Keep trying - print("Produced 1.0!"); - } - else - usage(); } } ///:~ diff --git a/containers/ReadOnly.java b/containers/ReadOnly.java index fdf04259..0cc4e37a 100644 --- a/containers/ReadOnly.java +++ b/containers/ReadOnly.java @@ -6,42 +6,42 @@ import static net.mindview.util.Print.*; public class ReadOnly { static Collection data = - new ArrayList(Countries.names(6)); + new ArrayList<>(Countries.names(6)); public static void main(String[] args) { Collection c = Collections.unmodifiableCollection( - new ArrayList(data)); + new ArrayList<>(data)); print(c); // Reading is OK //! c.add("one"); // Can't change it List a = Collections.unmodifiableList( - new ArrayList(data)); + new ArrayList<>(data)); ListIterator lit = a.listIterator(); print(lit.next()); // Reading is OK //! lit.add("one"); // Can't change it Set s = Collections.unmodifiableSet( - new HashSet(data)); + new HashSet<>(data)); print(s); // Reading is OK //! s.add("one"); // Can't change it // For a SortedSet: Set ss = Collections.unmodifiableSortedSet( - new TreeSet(data)); + new TreeSet<>(data)); Map m = Collections.unmodifiableMap( - new HashMap(Countries.capitals(6))); + new HashMap<>(Countries.capitals(6))); print(m); // Reading is OK //! m.put("Ralph", "Howdy!"); // For a SortedMap: Map sm = Collections.unmodifiableSortedMap( - new TreeMap(Countries.capitals(6))); + new TreeMap<>(Countries.capitals(6))); } } /* Output: -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] ALGERIA -[BULGARIA, BURKINA FASO, BOTSWANA, BENIN, ANGOLA, ALGERIA] -{BULGARIA=Sofia, BURKINA FASO=Ouagadougou, BOTSWANA=Gaberone, BENIN=Porto-Novo, ANGOLA=Luanda, ALGERIA=Algiers} +[ANGOLA, ALGERIA, BURKINA FASO, BENIN, BURUNDI, BOTSWANA] +{ANGOLA=Luanda, ALGERIA=Algiers, BURKINA FASO=Ouagadougou, BENIN=Porto-Novo, BURUNDI=Bujumbura, BOTSWANA=Gaberone} *///:~ diff --git a/containers/References.java b/containers/References.java index 70b40d4a..77e4f063 100644 --- a/containers/References.java +++ b/containers/References.java @@ -8,7 +8,9 @@ class VeryBig { private long[] la = new long[SIZE]; private String ident; public VeryBig(String id) { ident = id; } + @Override public String toString() { return ident; } + @Override protected void finalize() { System.out.println("Finalizing " + ident); } @@ -16,7 +18,7 @@ class VeryBig { public class References { private static ReferenceQueue rq = - new ReferenceQueue(); + new ReferenceQueue<>(); public static void checkQueue() { Reference inq = rq.poll(); if(inq != null) @@ -28,30 +30,30 @@ public class References { if(args.length > 0) size = new Integer(args[0]); LinkedList> sa = - new LinkedList>(); + new LinkedList<>(); for(int i = 0; i < size; i++) { - sa.add(new SoftReference( + sa.add(new SoftReference<>( new VeryBig("Soft " + i), rq)); System.out.println("Just created: " + sa.getLast()); checkQueue(); } LinkedList> wa = - new LinkedList>(); + new LinkedList<>(); for(int i = 0; i < size; i++) { - wa.add(new WeakReference( + wa.add(new WeakReference<>( new VeryBig("Weak " + i), rq)); System.out.println("Just created: " + wa.getLast()); checkQueue(); } SoftReference s = - new SoftReference(new VeryBig("Soft")); + new SoftReference<>(new VeryBig("Soft")); WeakReference w = - new WeakReference(new VeryBig("Weak")); + new WeakReference<>(new VeryBig("Weak")); System.gc(); LinkedList> pa = - new LinkedList>(); + new LinkedList<>(); for(int i = 0; i < size; i++) { - pa.add(new PhantomReference( + pa.add(new PhantomReference<>( new VeryBig("Phantom " + i), rq)); System.out.println("Just created: " + pa.getLast()); checkQueue(); diff --git a/containers/SetPerformance.java b/containers/SetPerformance.java index 1b82ab28..7a0504a9 100644 --- a/containers/SetPerformance.java +++ b/containers/SetPerformance.java @@ -5,9 +5,10 @@ import java.util.*; public class SetPerformance { static List>> tests = - new ArrayList>>(); + new ArrayList<>(); static { tests.add(new Test>("add") { + @Override int test(Set set, TestParam tp) { int loops = tp.loops; int size = tp.size; @@ -20,6 +21,7 @@ public class SetPerformance { } }); tests.add(new Test>("contains") { + @Override int test(Set set, TestParam tp) { int loops = tp.loops; int span = tp.size * 2; @@ -30,6 +32,7 @@ public class SetPerformance { } }); tests.add(new Test>("iterate") { + @Override int test(Set set, TestParam tp) { int loops = tp.loops * 10; for(int i = 0; i < loops; i++) { @@ -45,9 +48,9 @@ public class SetPerformance { if(args.length > 0) Tester.defaultParams = TestParam.array(args); Tester.fieldWidth = 10; - Tester.run(new TreeSet(), tests); - Tester.run(new HashSet(), tests); - Tester.run(new LinkedHashSet(), tests); + Tester.run(new TreeSet<>(), tests); + Tester.run(new HashSet<>(), tests); + Tester.run(new LinkedHashSet<>(), tests); } } /* Output: (Sample) ------------- TreeSet ------------- diff --git a/containers/SimpleHashMap.java b/containers/SimpleHashMap.java index deaf75cd..6a80a883 100644 --- a/containers/SimpleHashMap.java +++ b/containers/SimpleHashMap.java @@ -12,13 +12,14 @@ public class SimpleHashMap extends AbstractMap { @SuppressWarnings("unchecked") LinkedList>[] buckets = new LinkedList[SIZE]; + @Override public V put(K key, V value) { V oldValue = null; int index = Math.abs(key.hashCode()) % SIZE; if(buckets[index] == null) - buckets[index] = new LinkedList>(); + buckets[index] = new LinkedList<>(); LinkedList> bucket = buckets[index]; - MapEntry pair = new MapEntry(key, value); + MapEntry pair = new MapEntry<>(key, value); boolean found = false; ListIterator> it = bucket.listIterator(); while(it.hasNext()) { @@ -34,6 +35,7 @@ public class SimpleHashMap extends AbstractMap { buckets[index].add(pair); return oldValue; } + @Override public V get(Object key) { int index = Math.abs(key.hashCode()) % SIZE; if(buckets[index] == null) return null; @@ -42,8 +44,9 @@ public class SimpleHashMap extends AbstractMap { return iPair.getValue(); return null; } + @Override public Set> entrySet() { - Set> set= new HashSet>(); + Set> set= new HashSet<>(); for(LinkedList> bucket : buckets) { if(bucket == null) continue; for(MapEntry mpair : bucket) @@ -52,15 +55,14 @@ 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")); System.out.println(m.entrySet()); } } /* Output: -{CAMEROON=Yaounde, CONGO=Brazzaville, CHAD=N'djamena, COTE D'IVOIR (IVORY COAST)=Yamoussoukro, CENTRAL AFRICAN REPUBLIC=Bangui, GUINEA=Conakry, BOTSWANA=Gaberone, BISSAU=Bissau, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ERITREA=Asmara, THE GAMBIA=Banjul, KENYA=Nairobi, GABON=Libreville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, GHANA=Accra, DJIBOUTI=Dijibouti, ETHIOPIA=Addis Ababa} +{CHAD=N'djamena, BISSAU=Bissau, CONGO=Brazzaville, BURUNDI=Bujumbura, DJIBOUTI=Dijibouti, EQUATORIAL GUINEA=Malabo, GUINEA=Conakry, LESOTHO=Maseru, EGYPT=Cairo, GHANA=Accra, CENTRAL AFRICAN REPUBLIC=Bangui, BENIN=Porto-Novo, GABON=Libreville, COTE D'IVOIR (IVORY COAST)=Yamoussoukro, KENYA=Nairobi, ETHIOPIA=Addis Ababa, ALGERIA=Algiers, BOTSWANA=Gaberone, COMOROS=Moroni, ANGOLA=Luanda, ERITREA=Asmara, CAPE VERDE=Praia, BURKINA FASO=Ouagadougou, THE GAMBIA=Banjul, CAMEROON=Yaounde} Asmara -[CAMEROON=Yaounde, CONGO=Brazzaville, CHAD=N'djamena, COTE D'IVOIR (IVORY COAST)=Yamoussoukro, CENTRAL AFRICAN REPUBLIC=Bangui, GUINEA=Conakry, BOTSWANA=Gaberone, BISSAU=Bissau, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ERITREA=Asmara, THE GAMBIA=Banjul, KENYA=Nairobi, GABON=Libreville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, GHANA=Accra, DJIBOUTI=Dijibouti, ETHIOPIA=Addis Ababa] +[CHAD=N'djamena, BISSAU=Bissau, CONGO=Brazzaville, BURUNDI=Bujumbura, DJIBOUTI=Dijibouti, EQUATORIAL GUINEA=Malabo, GUINEA=Conakry, LESOTHO=Maseru, EGYPT=Cairo, GHANA=Accra, CENTRAL AFRICAN REPUBLIC=Bangui, BENIN=Porto-Novo, GABON=Libreville, COTE D'IVOIR (IVORY COAST)=Yamoussoukro, KENYA=Nairobi, ETHIOPIA=Addis Ababa, ALGERIA=Algiers, BOTSWANA=Gaberone, COMOROS=Moroni, ANGOLA=Luanda, ERITREA=Asmara, CAPE VERDE=Praia, BURKINA FASO=Ouagadougou, THE GAMBIA=Banjul, CAMEROON=Yaounde] *///:~ diff --git a/containers/SlowMap.java b/containers/SlowMap.java index 7040b2e4..7de5602d 100644 --- a/containers/SlowMap.java +++ b/containers/SlowMap.java @@ -4,8 +4,9 @@ import java.util.*; import net.mindview.util.*; public class SlowMap extends AbstractMap { - private List keys = new ArrayList(); - private List values = new ArrayList(); + private List keys = new ArrayList<>(); + private List values = new ArrayList<>(); + @Override public V put(K key, V value) { V oldValue = get(key); // The old value or null if(!keys.contains(key)) { @@ -15,28 +16,30 @@ public class SlowMap extends AbstractMap { values.set(keys.indexOf(key), value); return oldValue; } + @Override public V get(Object key) { // key is type Object, not K if(!keys.contains(key)) return null; return values.get(keys.indexOf(key)); } + @Override public Set> entrySet() { - Set> set= new HashSet>(); + Set> set= new HashSet<>(); Iterator ki = keys.iterator(); Iterator vi = values.iterator(); while(ki.hasNext()) - set.add(new MapEntry(ki.next(), vi.next())); + set.add(new MapEntry<>(ki.next(), vi.next())); return set; } public static void main(String[] args) { - SlowMap m= new SlowMap(); + SlowMap m= new SlowMap<>(); m.putAll(Countries.capitals(15)); System.out.println(m); System.out.println(m.get("BULGARIA")); System.out.println(m.entrySet()); } } /* Output: -{CAMEROON=Yaounde, CHAD=N'djamena, CONGO=Brazzaville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, CENTRAL AFRICAN REPUBLIC=Bangui, BOTSWANA=Gaberone, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, DJIBOUTI=Dijibouti} -Sofia -[CAMEROON=Yaounde, CHAD=N'djamena, CONGO=Brazzaville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, CENTRAL AFRICAN REPUBLIC=Bangui, BOTSWANA=Gaberone, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, DJIBOUTI=Dijibouti] +{CHAD=N'djamena, ALGERIA=Algiers, BOTSWANA=Gaberone, BURUNDI=Bujumbura, CONGO=Brazzaville, DJIBOUTI=Dijibouti, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, ANGOLA=Luanda, EGYPT=Cairo, CAPE VERDE=Praia, BURKINA FASO=Ouagadougou, BENIN=Porto-Novo, CENTRAL AFRICAN REPUBLIC=Bangui, CAMEROON=Yaounde} +null +[CHAD=N'djamena, ALGERIA=Algiers, BOTSWANA=Gaberone, BURUNDI=Bujumbura, CONGO=Brazzaville, DJIBOUTI=Dijibouti, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, ANGOLA=Luanda, EGYPT=Cairo, CAPE VERDE=Praia, BURKINA FASO=Ouagadougou, BENIN=Porto-Novo, CENTRAL AFRICAN REPUBLIC=Bangui, CAMEROON=Yaounde] *///:~ diff --git a/containers/SortedMapDemo.java b/containers/SortedMapDemo.java index 4c2941a6..767d74d7 100644 --- a/containers/SortedMapDemo.java +++ b/containers/SortedMapDemo.java @@ -7,7 +7,7 @@ import static net.mindview.util.Print.*; public class SortedMapDemo { public static void main(String[] args) { TreeMap sortedMap = - new TreeMap(new CountingMapData(10)); + new TreeMap<>(new CountingMapData(10)); print(sortedMap); Integer low = sortedMap.firstKey(); Integer high = sortedMap.lastKey(); diff --git a/containers/SortedSetDemo.java b/containers/SortedSetDemo.java index 40c64e09..62a503bb 100644 --- a/containers/SortedSetDemo.java +++ b/containers/SortedSetDemo.java @@ -5,7 +5,7 @@ import static net.mindview.util.Print.*; public class SortedSetDemo { public static void main(String[] args) { - SortedSet sortedSet = new TreeSet(); + SortedSet sortedSet = new TreeSet<>(); Collections.addAll(sortedSet, "one two three four five six seven eight" .split(" ")); diff --git a/containers/SpringDetector.java b/containers/SpringDetector.java index aecbe0e6..87da2090 100644 --- a/containers/SpringDetector.java +++ b/containers/SpringDetector.java @@ -9,8 +9,7 @@ public class SpringDetector { public static void detectSpring(Class type) throws Exception { Constructor ghog = type.getConstructor(int.class); - Map map = - new HashMap(); + Map map = new HashMap<>(); for(int i = 0; i < 10; i++) map.put(ghog.newInstance(i), new Prediction()); print("map = " + map); @@ -25,7 +24,7 @@ public class SpringDetector { detectSpring(Groundhog.class); } } /* Output: -map = {Groundhog #3=Early Spring!, Groundhog #7=Early Spring!, Groundhog #5=Early Spring!, Groundhog #9=Six more weeks of Winter!, Groundhog #8=Six more weeks of Winter!, Groundhog #0=Six more weeks of Winter!, Groundhog #6=Early Spring!, Groundhog #4=Six more weeks of Winter!, Groundhog #1=Six more weeks of Winter!, Groundhog #2=Early Spring!} +map = {Groundhog #0=Six more weeks of Winter!, Groundhog #4=Six more weeks of Winter!, Groundhog #3=Early Spring!, Groundhog #8=Six more weeks of Winter!, Groundhog #2=Early Spring!, Groundhog #5=Early Spring!, Groundhog #9=Six more weeks of Winter!, Groundhog #7=Early Spring!, Groundhog #1=Six more weeks of Winter!, Groundhog #6=Early Spring!} Looking up prediction for Groundhog #3 Key not found: Groundhog #3 *///:~ diff --git a/containers/SpringDetector2.java b/containers/SpringDetector2.java index e9767d74..34cede17 100644 --- a/containers/SpringDetector2.java +++ b/containers/SpringDetector2.java @@ -6,7 +6,7 @@ public class SpringDetector2 { SpringDetector.detectSpring(Groundhog2.class); } } /* Output: -map = {Groundhog #2=Early Spring!, Groundhog #4=Six more weeks of Winter!, Groundhog #9=Six more weeks of Winter!, Groundhog #8=Six more weeks of Winter!, Groundhog #6=Early Spring!, Groundhog #1=Six more weeks of Winter!, Groundhog #3=Early Spring!, Groundhog #7=Early Spring!, Groundhog #5=Early Spring!, Groundhog #0=Six more weeks of Winter!} +map = {Groundhog #0=Six more weeks of Winter!, Groundhog #1=Six more weeks of Winter!, Groundhog #2=Early Spring!, Groundhog #3=Early Spring!, Groundhog #4=Six more weeks of Winter!, Groundhog #5=Early Spring!, Groundhog #6=Early Spring!, Groundhog #7=Early Spring!, Groundhog #8=Six more weeks of Winter!, Groundhog #9=Six more weeks of Winter!} Looking up prediction for Groundhog #3 Early Spring! *///:~ diff --git a/containers/Stacks.java b/containers/Stacks.java index 296f02cf..0677b01d 100644 --- a/containers/Stacks.java +++ b/containers/Stacks.java @@ -8,7 +8,7 @@ enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, public class Stacks { public static void main(String[] args) { - Stack stack = new Stack(); + Stack stack = new Stack<>(); for(Month m : Month.values()) stack.push(m.toString()); print("stack = " + stack); @@ -20,7 +20,7 @@ public class Stacks { printnb(stack.pop() + " "); // Using a LinkedList as a Stack: - LinkedList lstack = new LinkedList(); + LinkedList lstack = new LinkedList<>(); for(Month m : Month.values()) lstack.addFirst(m.toString()); print("lstack = " + lstack); @@ -30,7 +30,7 @@ public class Stacks { // Using the Stack class from // the Holding Your Objects Chapter: net.mindview.util.Stack stack2 = - new net.mindview.util.Stack(); + new net.mindview.util.Stack<>(); for(Month m : Month.values()) stack2.push(m.toString()); print("stack2 = " + stack2); diff --git a/containers/Synchronization.java b/containers/Synchronization.java index b7ab8b73..6259caab 100644 --- a/containers/Synchronization.java +++ b/containers/Synchronization.java @@ -6,17 +6,16 @@ public class Synchronization { public static void main(String[] args) { Collection c = Collections.synchronizedCollection( - new ArrayList()); + new ArrayList<>()); List list = Collections.synchronizedList( - new ArrayList()); + new ArrayList<>()); Set s = Collections.synchronizedSet( - new HashSet()); + new HashSet<>()); Set ss = Collections.synchronizedSortedSet( - new TreeSet()); + new TreeSet<>()); Map m = Collections.synchronizedMap( - new HashMap()); + new HashMap<>()); Map sm = - Collections.synchronizedSortedMap( - new TreeMap()); + Collections.synchronizedSortedMap(new TreeMap<>()); } } ///:~ diff --git a/containers/Tester.java b/containers/Tester.java index 1a0910ff..b7c1bbf6 100644 --- a/containers/Tester.java +++ b/containers/Tester.java @@ -36,11 +36,11 @@ public class Tester { } // Generic methods for convenience : public static void run(C cntnr, List> tests){ - new Tester(cntnr, tests).timedTest(); + new Tester<>(cntnr, tests).timedTest(); } public static void run(C cntnr, List> tests, TestParam[] paramList) { - new Tester(cntnr, tests, paramList).timedTest(); + new Tester<>(cntnr, tests, paramList).timedTest(); } private void displayHeader() { // Calculate width and pad with '-': @@ -78,4 +78,4 @@ public class Tester { System.out.println(); } } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/containers/ToDoList.java b/containers/ToDoList.java index fac8aeaa..39264f11 100644 --- a/containers/ToDoList.java +++ b/containers/ToDoList.java @@ -12,6 +12,7 @@ class ToDoList extends PriorityQueue { secondary = sec; item = td; } + @Override public int compareTo(ToDoItem arg) { if(primary > arg.primary) return +1; @@ -22,6 +23,7 @@ class ToDoList extends PriorityQueue { return 0; return -1; } + @Override public String toString() { return Character.toString(primary) + secondary + ": " + item; diff --git a/containers/TypesForSets.java b/containers/TypesForSets.java index 509d5f77..2ecb947a 100644 --- a/containers/TypesForSets.java +++ b/containers/TypesForSets.java @@ -5,20 +5,24 @@ import java.util.*; class SetType { int i; public SetType(int n) { i = n; } + @Override public boolean equals(Object o) { return o instanceof SetType && (i == ((SetType)o).i); } + @Override public String toString() { return Integer.toString(i); } } class HashType extends SetType { public HashType(int n) { super(n); } + @Override public int hashCode() { return i; } } class TreeType extends SetType implements Comparable { public TreeType(int n) { super(n); } + @Override public int compareTo(TreeType arg) { return (arg.i < i ? -1 : (arg.i == i ? 0 : 1)); } @@ -42,21 +46,21 @@ public class TypesForSets { System.out.println(set); } public static void main(String[] args) { - test(new HashSet(), HashType.class); - test(new LinkedHashSet(), HashType.class); - test(new TreeSet(), TreeType.class); + test(new HashSet<>(), HashType.class); + test(new LinkedHashSet<>(), HashType.class); + test(new TreeSet<>(), TreeType.class); // Things that don't work: - test(new HashSet(), SetType.class); - test(new HashSet(), TreeType.class); - test(new LinkedHashSet(), SetType.class); - test(new LinkedHashSet(), TreeType.class); + test(new HashSet<>(), SetType.class); + test(new HashSet<>(), TreeType.class); + test(new LinkedHashSet<>(), SetType.class); + test(new LinkedHashSet<>(), TreeType.class); try { - test(new TreeSet(), SetType.class); + test(new TreeSet<>(), SetType.class); } catch(Exception e) { System.out.println("Expected: " + e.getMessage()); } try { - test(new TreeSet(), HashType.class); + test(new TreeSet<>(), HashType.class); } catch(Exception e) { System.out.println("Expected: " + e.getMessage()); } @@ -71,4 +75,4 @@ public class TypesForSets { [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Expected: java.lang.ClassCastException: SetType cannot be cast to java.lang.Comparable Expected: java.lang.ClassCastException: HashType cannot be cast to java.lang.Comparable -*///:~ \ No newline at end of file +*///:~ diff --git a/containers/Unsupported.java b/containers/Unsupported.java index f23e2c50..353d30d8 100644 --- a/containers/Unsupported.java +++ b/containers/Unsupported.java @@ -8,7 +8,7 @@ public class Unsupported { Collection c = list; Collection subList = list.subList(1,8); // Copy of the sublist: - Collection c2 = new ArrayList(subList); + Collection c2 = new ArrayList<>(subList); try { c.retainAll(c2); } catch(Exception e) { System.out.println("retainAll(): " + e); } @@ -38,11 +38,11 @@ public class Unsupported { public static void main(String[] args) { List list = Arrays.asList("A B C D E F G H I J K L".split(" ")); - test("Modifiable Copy", new ArrayList(list)); + test("Modifiable Copy", new ArrayList<>(list)); test("Arrays.asList()", list); test("unmodifiableList()", Collections.unmodifiableList( - new ArrayList(list))); + new ArrayList<>(list))); } } /* Output: --- Modifiable Copy --- diff --git a/containers/Utilities.java b/containers/Utilities.java index 629fc98c..ee6b30ff 100644 --- a/containers/Utilities.java +++ b/containers/Utilities.java @@ -47,7 +47,7 @@ public class Utilities { Collections.disjoint(list, dups)); // Getting an old-style Enumeration: Enumeration e = Collections.enumeration(dups); - Vector v = new Vector(); + Vector v = new Vector<>(); while(e.hasMoreElements()) v.addElement(e.nextElement()); // Converting an old-style Vector diff --git a/containers/build.xml b/containers/build.xml new file mode 100644 index 00000000..95d5bb5f --- /dev/null +++ b/containers/build.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/control/StringSwitch.java b/control/StringSwitch.java new file mode 100644 index 00000000..1cb5fab8 --- /dev/null +++ b/control/StringSwitch.java @@ -0,0 +1,38 @@ +//: control/StringSwitch.java +import static net.mindview.util.Print.*; + +public class StringSwitch { + public static void main(String[] args) { + String color = "red"; + // Old way: using if-then + if(color == "red") { + print("RED"); + } else if(color == "green") { + print("GREEN"); + } else if(color == "blue") { + print("BLUE"); + } else if(color == "yellow") { + print("YELLOW"); + } else { + print("Unknown"); + } + // New way: Strings in switch + switch(color) { + case "red": + print("RED"); + break; + case "green": + print("GREEN"); + break; + case "blue": + print("BLUE"); + break; + case "yellow": + print("YELLOW"); + break; + default: + print("Unknown"); + break; + } + } +} ///:~ diff --git a/control/build.xml b/control/build.xml new file mode 100644 index 00000000..02e54739 --- /dev/null +++ b/control/build.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/debugging/SimpleDebugging.java b/debugging/SimpleDebugging.java new file mode 100644 index 00000000..cfb082d0 --- /dev/null +++ b/debugging/SimpleDebugging.java @@ -0,0 +1,21 @@ +//: debugging/SimpleDebugging.java +// {ThrowsException} +public class SimpleDebugging { + private static void foo1() { + System.out.println("In foo1"); + foo2(); + } + private static void foo2() { + System.out.println("In foo2"); + foo3(); + } + private static void foo3() { + System.out.println("In foo3"); + int j = 1; + j--; + int i = 5 / j; + } + public static void main(String[] args) { + foo1(); + } +} ///:~ diff --git a/debugging/build.xml b/debugging/build.xml new file mode 100644 index 00000000..6b201903 --- /dev/null +++ b/debugging/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/enumerated/Burrito.java b/enumerated/Burrito.java index b9b1961b..8eab04c4 100644 --- a/enumerated/Burrito.java +++ b/enumerated/Burrito.java @@ -5,6 +5,7 @@ import static enumerated.Spiciness.*; public class Burrito { Spiciness degree; public Burrito(Spiciness degree) { this.degree = degree;} + @Override public String toString() { return "Burrito is "+ degree;} public static void main(String[] args) { System.out.println(new Burrito(NOT)); diff --git a/enumerated/CarWash.java b/enumerated/CarWash.java index f89233ff..3ec38543 100644 --- a/enumerated/CarWash.java +++ b/enumerated/CarWash.java @@ -5,24 +5,31 @@ import static net.mindview.util.Print.*; public class CarWash { public enum Cycle { UNDERBODY { + @Override void action() { print("Spraying the underbody"); } }, WHEELWASH { + @Override void action() { print("Washing the wheels"); } }, PREWASH { + @Override void action() { print("Loosening the dirt"); } }, BASIC { + @Override void action() { print("The basic wash"); } }, HOTWAX { + @Override void action() { print("Applying hot wax"); } }, RINSE { + @Override void action() { print("Rinsing"); } }, BLOWDRY { + @Override void action() { print("Blowing dry"); } }; abstract void action(); @@ -34,6 +41,7 @@ public class CarWash { for(Cycle c : cycles) c.action(); } + @Override public String toString() { return cycles.toString(); } public static void main(String[] args) { CarWash wash = new CarWash(); diff --git a/enumerated/ConstantSpecificMethod.java b/enumerated/ConstantSpecificMethod.java index 030ea659..aa0f2d67 100644 --- a/enumerated/ConstantSpecificMethod.java +++ b/enumerated/ConstantSpecificMethod.java @@ -4,17 +4,20 @@ import java.text.*; public enum ConstantSpecificMethod { DATE_TIME { + @Override String getInfo() { return DateFormat.getDateInstance().format(new Date()); } }, CLASSPATH { + @Override String getInfo() { return System.getenv("CLASSPATH"); } }, VERSION { + @Override String getInfo() { return System.getProperty("java.version"); } diff --git a/enumerated/EnumMaps.java b/enumerated/EnumMaps.java index 64699906..5b49a4b3 100644 --- a/enumerated/EnumMaps.java +++ b/enumerated/EnumMaps.java @@ -10,11 +10,13 @@ interface Command { void action(); } public class EnumMaps { public static void main(String[] args) { EnumMap em = - new EnumMap(AlarmPoints.class); + new EnumMap<>(AlarmPoints.class); em.put(KITCHEN, new Command() { + @Override public void action() { print("Kitchen fire!"); } }); em.put(BATHROOM, new Command() { + @Override public void action() { print("Bathroom alert!"); } }); for(Map.Entry e : em.entrySet()) { @@ -31,4 +33,4 @@ public class EnumMaps { BATHROOM: Bathroom alert! KITCHEN: Kitchen fire! Expected: java.lang.NullPointerException -*///:~ \ No newline at end of file +*///:~ diff --git a/enumerated/Input.java b/enumerated/Input.java index a732271e..a24b2573 100644 --- a/enumerated/Input.java +++ b/enumerated/Input.java @@ -5,11 +5,13 @@ public enum Input { NICKEL(5), DIME(10), QUARTER(25), DOLLAR(100), TOOTHPASTE(200), CHIPS(75), SODA(100), SOAP(50), ABORT_TRANSACTION { + @Override public int amount() { // Disallow throw new RuntimeException("ABORT.amount()"); } }, STOP { // This must be the last instance. + @Override public int amount() { // Disallow throw new RuntimeException("SHUT_DOWN.amount()"); } @@ -23,4 +25,4 @@ public enum Input { // Don't include STOP: return values()[rand.nextInt(values().length - 1)]; } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/enumerated/NonEnum.java b/enumerated/NonEnum.java index 398908c7..7c5ee351 100644 --- a/enumerated/NonEnum.java +++ b/enumerated/NonEnum.java @@ -12,4 +12,4 @@ public class NonEnum { } } /* Output: Expected: java.lang.NullPointerException -*///:~ \ No newline at end of file +*///:~ diff --git a/enumerated/NotClasses.java b/enumerated/NotClasses.java index b85ae175..55efcc04 100644 --- a/enumerated/NotClasses.java +++ b/enumerated/NotClasses.java @@ -3,9 +3,12 @@ import static net.mindview.util.Print.*; enum LikeClasses { - WINKEN { void behavior() { print("Behavior1"); } }, - BLINKEN { void behavior() { print("Behavior2"); } }, - NOD { void behavior() { print("Behavior3"); } }; + WINKEN {@Override + void behavior() { print("Behavior1"); } }, + BLINKEN {@Override + void behavior() { print("Behavior2"); } }, + NOD {@Override + void behavior() { print("Behavior3"); } }; abstract void behavior(); } diff --git a/enumerated/OverrideConstantSpecific.java b/enumerated/OverrideConstantSpecific.java index df7e1349..0b574da1 100644 --- a/enumerated/OverrideConstantSpecific.java +++ b/enumerated/OverrideConstantSpecific.java @@ -4,6 +4,7 @@ import static net.mindview.util.Print.*; public enum OverrideConstantSpecific { NUT, BOLT, WASHER { + @Override void f() { print("Overridden method"); } }; void f() { print("default behavior"); } diff --git a/enumerated/PostOffice.java b/enumerated/PostOffice.java index 2f158f68..5a12049e 100644 --- a/enumerated/PostOffice.java +++ b/enumerated/PostOffice.java @@ -18,6 +18,7 @@ class Mail { ReturnAddress returnAddress; static long counter = 0; long id = counter++; + @Override public String toString() { return "Mail " + id; } public String details() { return toString() + @@ -40,10 +41,14 @@ class Mail { public static Iterable generator(final int count) { return new Iterable() { int n = count; + @Override public Iterator iterator() { return new Iterator() { + @Override public boolean hasNext() { return n-- > 0; } + @Override public Mail next() { return randomMail(); } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } @@ -56,6 +61,7 @@ class Mail { public class PostOffice { enum MailHandler { GENERAL_DELIVERY { + @Override boolean handle(Mail m) { switch(m.generalDelivery) { case YES: @@ -66,6 +72,7 @@ public class PostOffice { } }, MACHINE_SCAN { + @Override boolean handle(Mail m) { switch(m.scannability) { case UNSCANNABLE: return false; @@ -80,6 +87,7 @@ public class PostOffice { } }, VISUAL_INSPECTION { + @Override boolean handle(Mail m) { switch(m.readability) { case ILLEGIBLE: return false; @@ -94,6 +102,7 @@ public class PostOffice { } }, RETURN_TO_SENDER { + @Override boolean handle(Mail m) { switch(m.returnAddress) { case MISSING: return false; diff --git a/enumerated/Reflection.java b/enumerated/Reflection.java index b843d29a..12684f6f 100644 --- a/enumerated/Reflection.java +++ b/enumerated/Reflection.java @@ -15,7 +15,7 @@ public class Reflection { print(t); print("Base: " + enumClass.getSuperclass()); print("Methods: "); - Set methods = new TreeSet(); + Set methods = new TreeSet<>(); for(Method m : enumClass.getMethods()) methods.add(m.getName()); print(methods); @@ -51,7 +51,7 @@ Compiled from "Reflection.java" final class Explore extends java.lang.Enum{ public static final Explore HERE; public static final Explore THERE; - public static final Explore[] values(); + public static Explore[] values(); public static Explore valueOf(java.lang.String); static {}; } diff --git a/enumerated/RoShamBo1.java b/enumerated/RoShamBo1.java index a99e5a72..d92d59b8 100644 --- a/enumerated/RoShamBo1.java +++ b/enumerated/RoShamBo1.java @@ -12,26 +12,41 @@ interface Item { } class Paper implements Item { + @Override public Outcome compete(Item it) { return it.eval(this); } + @Override public Outcome eval(Paper p) { return DRAW; } + @Override public Outcome eval(Scissors s) { return WIN; } + @Override public Outcome eval(Rock r) { return LOSE; } + @Override public String toString() { return "Paper"; } } class Scissors implements Item { + @Override public Outcome compete(Item it) { return it.eval(this); } + @Override public Outcome eval(Paper p) { return LOSE; } + @Override public Outcome eval(Scissors s) { return DRAW; } + @Override public Outcome eval(Rock r) { return WIN; } + @Override public String toString() { return "Scissors"; } } class Rock implements Item { + @Override public Outcome compete(Item it) { return it.eval(this); } + @Override public Outcome eval(Paper p) { return WIN; } + @Override public Outcome eval(Scissors s) { return LOSE; } + @Override public Outcome eval(Rock r) { return DRAW; } + @Override public String toString() { return "Rock"; } } diff --git a/enumerated/RoShamBo2.java b/enumerated/RoShamBo2.java index 1deee4c5..dca102c9 100644 --- a/enumerated/RoShamBo2.java +++ b/enumerated/RoShamBo2.java @@ -13,6 +13,7 @@ public enum RoShamBo2 implements Competitor { this.vSCISSORS = scissors; this.vROCK = rock; } + @Override public Outcome compete(RoShamBo2 it) { switch(it) { default: diff --git a/enumerated/RoShamBo3.java b/enumerated/RoShamBo3.java index d0bcc151..b2baf0b2 100644 --- a/enumerated/RoShamBo3.java +++ b/enumerated/RoShamBo3.java @@ -5,6 +5,7 @@ import static enumerated.Outcome.*; public enum RoShamBo3 implements Competitor { PAPER { + @Override public Outcome compete(RoShamBo3 it) { switch(it) { default: // To placate the compiler @@ -15,6 +16,7 @@ public enum RoShamBo3 implements Competitor { } }, SCISSORS { + @Override public Outcome compete(RoShamBo3 it) { switch(it) { default: @@ -25,6 +27,7 @@ public enum RoShamBo3 implements Competitor { } }, ROCK { + @Override public Outcome compete(RoShamBo3 it) { switch(it) { default: @@ -34,6 +37,7 @@ public enum RoShamBo3 implements Competitor { } } }; + @Override public abstract Outcome compete(RoShamBo3 it); public static void main(String[] args) { RoShamBo.play(RoShamBo3.class, 20); diff --git a/enumerated/RoShamBo4.java b/enumerated/RoShamBo4.java index 3db20985..2eb3432a 100644 --- a/enumerated/RoShamBo4.java +++ b/enumerated/RoShamBo4.java @@ -3,16 +3,19 @@ package enumerated; public enum RoShamBo4 implements Competitor { ROCK { + @Override public Outcome compete(RoShamBo4 opponent) { return compete(SCISSORS, opponent); } }, SCISSORS { + @Override public Outcome compete(RoShamBo4 opponent) { return compete(PAPER, opponent); } }, PAPER { + @Override public Outcome compete(RoShamBo4 opponent) { return compete(ROCK, opponent); } diff --git a/enumerated/RoShamBo5.java b/enumerated/RoShamBo5.java index b05bcae4..741be9fc 100644 --- a/enumerated/RoShamBo5.java +++ b/enumerated/RoShamBo5.java @@ -7,12 +7,10 @@ import static enumerated.Outcome.*; enum RoShamBo5 implements Competitor { PAPER, SCISSORS, ROCK; static EnumMap> - table = new EnumMap>(RoShamBo5.class); + table = new EnumMap<>(RoShamBo5.class); static { for(RoShamBo5 it : RoShamBo5.values()) - table.put(it, - new EnumMap(RoShamBo5.class)); + table.put(it, new EnumMap<>(RoShamBo5.class)); initRow(PAPER, DRAW, LOSE, WIN); initRow(SCISSORS, WIN, DRAW, LOSE); initRow(ROCK, LOSE, WIN, DRAW); @@ -25,6 +23,7 @@ enum RoShamBo5 implements Competitor { row.put(RoShamBo5.SCISSORS, vSCISSORS); row.put(RoShamBo5.ROCK, vROCK); } + @Override public Outcome compete(RoShamBo5 it) { return table.get(this).get(it); } diff --git a/enumerated/RoShamBo6.java b/enumerated/RoShamBo6.java index 6b9dc0ab..9553f846 100644 --- a/enumerated/RoShamBo6.java +++ b/enumerated/RoShamBo6.java @@ -10,6 +10,7 @@ enum RoShamBo6 implements Competitor { { WIN, DRAW, LOSE }, // SCISSORS { LOSE, WIN, DRAW }, // ROCK }; + @Override public Outcome compete(RoShamBo6 other) { return table[this.ordinal()][other.ordinal()]; } diff --git a/enumerated/SpaceShip.java b/enumerated/SpaceShip.java index 2a89eafa..6e526f3d 100644 --- a/enumerated/SpaceShip.java +++ b/enumerated/SpaceShip.java @@ -1,6 +1,7 @@ //: enumerated/SpaceShip.java public enum SpaceShip { SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP; + @Override public String toString() { String id = name(); String lower = id.substring(1).toLowerCase(); diff --git a/enumerated/TrafficLight.java b/enumerated/TrafficLight.java index dc96dde1..68951e57 100644 --- a/enumerated/TrafficLight.java +++ b/enumerated/TrafficLight.java @@ -19,6 +19,7 @@ public class TrafficLight { break; } } + @Override public String toString() { return "The traffic light is " + color; } diff --git a/enumerated/VendingMachine.java b/enumerated/VendingMachine.java index 3851e1b3..163665bd 100644 --- a/enumerated/VendingMachine.java +++ b/enumerated/VendingMachine.java @@ -14,7 +14,7 @@ enum Category { private Input[] values; Category(Input... types) { values = types; } private static EnumMap categories = - new EnumMap(Input.class); + new EnumMap<>(Input.class); static { for(Category c : Category.class.getEnumConstants()) for(Input type : c.values) @@ -32,6 +32,7 @@ public class VendingMachine { enum StateDuration { TRANSIENT } // Tagging enum enum State { RESTING { + @Override void next(Input input) { switch(Category.categorize(input)) { case MONEY: @@ -45,6 +46,7 @@ public class VendingMachine { } }, ADDING_MONEY { + @Override void next(Input input) { switch(Category.categorize(input)) { case MONEY: @@ -66,6 +68,7 @@ public class VendingMachine { } }, DISPENSING(StateDuration.TRANSIENT) { + @Override void next() { print("here is your " + selection); amount -= selection.amount(); @@ -73,6 +76,7 @@ public class VendingMachine { } }, GIVING_CHANGE(StateDuration.TRANSIENT) { + @Override void next() { if(amount > 0) { print("Your change: " + amount); @@ -81,7 +85,8 @@ public class VendingMachine { state = RESTING; } }, - TERMINAL { void output() { print("Halted"); } }; + TERMINAL {@Override + void output() { print("Halted"); } }; private boolean isTransient = false; State() {} State(StateDuration trans) { isTransient = true; } @@ -113,6 +118,7 @@ public class VendingMachine { // For a basic sanity check: class RandomInputGenerator implements Generator { + @Override public Input next() { return Input.randomSelection(); } } @@ -122,6 +128,7 @@ class FileInputGenerator implements Generator { public FileInputGenerator(String fileName) { input = new TextFile(fileName, ";").iterator(); } + @Override public Input next() { if(!input.hasNext()) return null; @@ -153,4 +160,4 @@ Insufficient money for SODA Your change: 75 0 Halted -*///:~ \ No newline at end of file +*///:~ diff --git a/enumerated/VendingMachineInput.txt b/enumerated/VendingMachineInput.txt index 9a2c79f0..6472db43 100644 --- a/enumerated/VendingMachineInput.txt +++ b/enumerated/VendingMachineInput.txt @@ -1,3 +1,4 @@ +//: enumerated/VendingMachineInput.txt QUARTER; QUARTER; QUARTER; CHIPS; DOLLAR; DOLLAR; TOOTHPASTE; QUARTER; DIME; ABORT_TRANSACTION; @@ -5,3 +6,4 @@ QUARTER; DIME; SODA; QUARTER; DIME; NICKEL; SODA; ABORT_TRANSACTION; STOP; +///:~ diff --git a/enumerated/build.xml b/enumerated/build.xml new file mode 100644 index 00000000..33d164a4 --- /dev/null +++ b/enumerated/build.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/enumerated/cartoons/EnumImplementation.java b/enumerated/cartoons/EnumImplementation.java index abd33686..2ef3fbf2 100644 --- a/enumerated/cartoons/EnumImplementation.java +++ b/enumerated/cartoons/EnumImplementation.java @@ -8,6 +8,7 @@ enum CartoonCharacter implements Generator { SLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB; private Random rand = new Random(47); + @Override public CartoonCharacter next() { return values()[rand.nextInt(values().length)]; } diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index 5cf62688..5a73d49a 100644 --- a/exceptions/DynamicFields.java +++ b/exceptions/DynamicFields.java @@ -12,6 +12,7 @@ public class DynamicFields { for(int i = 0; i < initialSize; i++) fields[i] = new Object[] { null, null }; } + @Override public String toString() { StringBuilder result = new StringBuilder(); for(Object[] obj : fields) { @@ -119,4 +120,4 @@ DynamicFieldsException Caused by: java.lang.NullPointerException at DynamicFields.setField(DynamicFields.java:66) ... 1 more -*///:~ \ No newline at end of file +*///:~ diff --git a/exceptions/ExtraFeatures.java b/exceptions/ExtraFeatures.java index 33055d60..bc42d39e 100644 --- a/exceptions/ExtraFeatures.java +++ b/exceptions/ExtraFeatures.java @@ -11,6 +11,7 @@ class MyException2 extends Exception { this.x = x; } public int val() { return x; } + @Override public String getMessage() { return "Detail Message: "+ x + " "+ super.getMessage(); } diff --git a/exceptions/LostMessage.java b/exceptions/LostMessage.java index cd15df60..93f623ce 100644 --- a/exceptions/LostMessage.java +++ b/exceptions/LostMessage.java @@ -2,12 +2,14 @@ // How an exception can be lost. class VeryImportantException extends Exception { + @Override public String toString() { return "A very important exception!"; } } class HoHumException extends Exception { + @Override public String toString() { return "A trivial exception"; } diff --git a/exceptions/StormyInning.java b/exceptions/StormyInning.java index fa66baba..bb1b0420 100644 --- a/exceptions/StormyInning.java +++ b/exceptions/StormyInning.java @@ -39,11 +39,14 @@ public class StormyInning extends Inning implements Storm { //! public void event() throws RainedOut {} // If the method doesn't already exist in the // base class, the exception is OK: + @Override public void rainHard() throws RainedOut {} // You can choose to not throw any exceptions, // even if the base version does: + @Override public void event() {} // Overridden methods can throw inherited exceptions: + @Override public void atBat() throws PopFoul {} public static void main(String[] args) { try { @@ -73,4 +76,4 @@ public class StormyInning extends Inning implements Storm { System.out.println("Generic baseball exception"); } } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/exceptions/Switch.java b/exceptions/Switch.java index e6f68fa7..085cb2a2 100644 --- a/exceptions/Switch.java +++ b/exceptions/Switch.java @@ -6,5 +6,6 @@ public class Switch { public boolean read() { return state; } public void on() { state = true; print(this); } public void off() { state = false; print(this); } + @Override public String toString() { return state ? "on" : "off"; } } ///:~ diff --git a/exceptions/build.xml b/exceptions/build.xml new file mode 100644 index 00000000..ffc8ee99 --- /dev/null +++ b/exceptions/build.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/generics/Apply.java b/generics/Apply.java index 00c6c013..def46a5a 100644 --- a/generics/Apply.java +++ b/generics/Apply.java @@ -40,25 +40,25 @@ class FilledList extends ArrayList { class ApplyTest { public static void main(String[] args) throws Exception { - List shapes = new ArrayList(); + 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(); + 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), + Apply.apply(new FilledList<>(Shape.class, 10), Shape.class.getMethod("rotate")); - Apply.apply(new FilledList(Square.class, 10), + Apply.apply(new FilledList<>(Square.class, 10), Shape.class.getMethod("rotate")); - SimpleQueue shapeQ = new SimpleQueue(); + SimpleQueue shapeQ = new SimpleQueue<>(); for(int i = 0; i < 5; i++) { shapeQ.add(new Shape()); shapeQ.add(new Square()); diff --git a/generics/ArrayMaker.java b/generics/ArrayMaker.java index 62f23d6b..f17cca29 100644 --- a/generics/ArrayMaker.java +++ b/generics/ArrayMaker.java @@ -11,7 +11,7 @@ public class ArrayMaker { } public static void main(String[] args) { ArrayMaker stringMaker = - new ArrayMaker(String.class); + new ArrayMaker<>(String.class); String[] stringArray = stringMaker.create(9); System.out.println(Arrays.toString(stringArray)); } diff --git a/generics/ArrayOfGeneric.java b/generics/ArrayOfGeneric.java index 68846722..481d244f 100644 --- a/generics/ArrayOfGeneric.java +++ b/generics/ArrayOfGeneric.java @@ -10,7 +10,7 @@ public class ArrayOfGeneric { // Runtime type is the raw (erased) type: gia = (Generic[])new Generic[SIZE]; System.out.println(gia.getClass().getSimpleName()); - gia[0] = new Generic(); + gia[0] = new Generic<>(); //! gia[1] = new Object(); // Compile-time error // Discovers type mismatch at compile time: //! gia[2] = new Generic(); diff --git a/generics/BankTeller.java b/generics/BankTeller.java index 5a9ee2ad..6d121510 100644 --- a/generics/BankTeller.java +++ b/generics/BankTeller.java @@ -7,10 +7,12 @@ 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 Generator objects: public static Generator generator() { return new Generator() { + @Override public Customer next() { return new Customer(); } }; } @@ -20,10 +22,12 @@ class Teller { private static long counter = 1; private final long id = counter++; private Teller() {} + @Override public String toString() { return "Teller " + id; } // A single Generator object: public static Generator generator = new Generator() { + @Override public Teller next() { return new Teller(); } }; } @@ -34,9 +38,9 @@ public class BankTeller { } public static void main(String[] args) { Random rand = new Random(47); - Queue line = new LinkedList(); + Queue line = new LinkedList<>(); Generators.fill(line, Customer.generator(), 15); - List tellers = new ArrayList(); + List tellers = new ArrayList<>(); Generators.fill(tellers, Teller.generator, 4); for(Customer c : line) serve(tellers.get(rand.nextInt(tellers.size())), c); diff --git a/generics/BasicBounds.java b/generics/BasicBounds.java index 5c068abb..4618e328 100644 --- a/generics/BasicBounds.java +++ b/generics/BasicBounds.java @@ -43,14 +43,16 @@ class Solid { class Bounded extends Dimension implements HasColor, Weight { + @Override public java.awt.Color getColor() { return null; } + @Override public int weight() { return 0; } } public class BasicBounds { public static void main(String[] args) { - Solid solid = - new Solid(new Bounded()); + Solid solid = + new Solid<>(new Bounded()); solid.color(); solid.getY(); solid.weight(); diff --git a/generics/ByteSet.java b/generics/ByteSet.java index af499c3f..f9a3bcfd 100644 --- a/generics/ByteSet.java +++ b/generics/ByteSet.java @@ -4,8 +4,8 @@ import java.util.*; public class ByteSet { Byte[] possibles = { 1,2,3,4,5,6,7,8,9 }; Set mySet = - new HashSet(Arrays.asList(possibles)); + new HashSet<>(Arrays.asList(possibles)); // But you can't do this: - // Set mySet2 = new HashSet( + // Set mySet2 = new HashSet<>( // Arrays.asList(1,2,3,4,5,6,7,8,9)); } ///:~ diff --git a/generics/CaptureConversion.java b/generics/CaptureConversion.java index aecea635..f7337f6b 100644 --- a/generics/CaptureConversion.java +++ b/generics/CaptureConversion.java @@ -10,14 +10,14 @@ public class CaptureConversion { } @SuppressWarnings("unchecked") public static void main(String[] args) { - Holder raw = new Holder(1); + Holder raw = new Holder<>(1); // f1(raw); // Produces warnings f2(raw); // No warnings Holder rawBasic = new Holder(); rawBasic.set(new Object()); // Warning f2(rawBasic); // No warnings // Upcast to Holder, still figures it out: - Holder wildcarded = new Holder(1.0); + Holder wildcarded = new Holder<>(1.0); f2(wildcarded); } } /* Output: diff --git a/generics/CheckedList.java b/generics/CheckedList.java index d512837b..85dd5a94 100644 --- a/generics/CheckedList.java +++ b/generics/CheckedList.java @@ -9,10 +9,10 @@ public class CheckedList { probablyDogs.add(new Cat()); } public static void main(String[] args) { - List dogs1 = new ArrayList(); + List dogs1 = new ArrayList<>(); oldStyleMethod(dogs1); // Quietly accepts a Cat List dogs2 = Collections.checkedList( - new ArrayList(), Dog.class); + new ArrayList<>(), Dog.class); try { oldStyleMethod(dogs2); // Throws an exception } catch(Exception e) { @@ -20,10 +20,10 @@ public class CheckedList { } // Derived types work fine: List pets = Collections.checkedList( - new ArrayList(), Pet.class); + new ArrayList<>(), Pet.class); pets.add(new Dog()); pets.add(new Cat()); } } /* Output: Expected: java.lang.ClassCastException: Attempt to insert class typeinfo.pets.Cat element into collection with element type class typeinfo.pets.Dog -*///:~ \ No newline at end of file +*///:~ diff --git a/generics/ClassTypeCapture.java b/generics/ClassTypeCapture.java index 2f709bf0..4481a506 100644 --- a/generics/ClassTypeCapture.java +++ b/generics/ClassTypeCapture.java @@ -13,11 +13,11 @@ public class ClassTypeCapture { } public static void main(String[] args) { ClassTypeCapture ctt1 = - new ClassTypeCapture(Building.class); + new ClassTypeCapture<>(Building.class); System.out.println(ctt1.f(new Building())); System.out.println(ctt1.f(new House())); ClassTypeCapture ctt2 = - new ClassTypeCapture(House.class); + new ClassTypeCapture<>(House.class); System.out.println(ctt2.f(new Building())); System.out.println(ctt2.f(new House())); } diff --git a/generics/ComparablePet.java b/generics/ComparablePet.java index 298b8dff..74cc373b 100644 --- a/generics/ComparablePet.java +++ b/generics/ComparablePet.java @@ -2,5 +2,6 @@ public class ComparablePet implements Comparable { + @Override public int compareTo(ComparablePet arg) { return 0; } } ///:~ diff --git a/generics/CountedObject.java b/generics/CountedObject.java index cb00899b..6443eb0f 100644 --- a/generics/CountedObject.java +++ b/generics/CountedObject.java @@ -4,5 +4,6 @@ public class CountedObject { private static long counter = 0; private final long id = counter++; public long id() { return id; } + @Override public String toString() { return "CountedObject " + id;} } ///:~ diff --git a/generics/CovariantReturnTypes.java b/generics/CovariantReturnTypes.java index 1f74f918..6fa68109 100644 --- a/generics/CovariantReturnTypes.java +++ b/generics/CovariantReturnTypes.java @@ -9,6 +9,7 @@ interface OrdinaryGetter { interface DerivedGetter extends OrdinaryGetter { // Return type of overridden method is allowed to vary: + @Override Derived get(); } diff --git a/generics/CreatorGeneric.java b/generics/CreatorGeneric.java index 372e142e..040f1a9d 100644 --- a/generics/CreatorGeneric.java +++ b/generics/CreatorGeneric.java @@ -9,6 +9,7 @@ abstract class GenericWithCreate { class X {} class Creator extends GenericWithCreate { + @Override X create() { return new X(); } void f() { System.out.println(element.getClass().getSimpleName()); diff --git a/generics/Diamond.java b/generics/Diamond.java new file mode 100644 index 00000000..2a80d8e8 --- /dev/null +++ b/generics/Diamond.java @@ -0,0 +1,15 @@ +//: generics/Diamond.java + +public class Diamond { + private T a; + public Diamond(T a) { this.a = a; } + public void set(T a) { this.a = a; } + public T get() { return a; } + public static void main(String[] args) { + Diamond h3 = + new Diamond<>(new Automobile()); + Automobile a = h3.get(); // No cast needed + // h3.set("Not an Automobile"); // Error + // h3.set(1); // Error + } +} ///:~ diff --git a/generics/DogsAndRobots.java b/generics/DogsAndRobots.java index 9b05bdd0..f2a3c0a9 100644 --- a/generics/DogsAndRobots.java +++ b/generics/DogsAndRobots.java @@ -4,7 +4,9 @@ import typeinfo.pets.*; import static net.mindview.util.Print.*; class PerformingDog extends Dog implements Performs { + @Override public void speak() { print("Woof!"); } + @Override public void sit() { print("Sitting"); } public void reproduce() {} } diff --git a/generics/DogsAndRobots.py b/generics/DogsAndRobots.py new file mode 100644 index 00000000..ddcb48d3 --- /dev/null +++ b/generics/DogsAndRobots.py @@ -0,0 +1,27 @@ +#: generics/DogsAndRobots.py + +class Dog: + def speak(self): + print("Arf!") + def sit(self): + print("Sitting") + def reproduce(self): + pass + +class Robot: + def speak(self): + print("Click!") + def sit(self): + print("Clank!") + def oilChange(self): + pass + +def perform(anything): + anything.speak() + anything.sit() + +a = Dog() +b = Robot() +perform(a) +perform(b) +#:~ diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index b6696f13..99f8b4d7 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -6,8 +6,9 @@ import static net.mindview.util.Tuple.*; class MixinProxy implements InvocationHandler { Map delegatesByMethod; + @SuppressWarnings("unchecked") public MixinProxy(TwoTuple>... pairs) { - delegatesByMethod = new HashMap(); + delegatesByMethod = new HashMap<>(); for(TwoTuple> pair : pairs) { for(Method method : pair.second.getMethods()) { String methodName = method.getName(); @@ -18,6 +19,7 @@ class MixinProxy implements InvocationHandler { } } } + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); diff --git a/generics/EpicBattle.java b/generics/EpicBattle.java index 064773f5..c1d24c8d 100644 --- a/generics/EpicBattle.java +++ b/generics/EpicBattle.java @@ -33,7 +33,9 @@ extends SuperHero { } class SuperHearSmell implements SuperHearing, SuperSmell { + @Override public void hearSubtleNoises() {} + @Override public void trackBySmell() {} } diff --git a/generics/ErasureAndInheritance.java b/generics/ErasureAndInheritance.java index a2f545f1..d487deaa 100644 --- a/generics/ErasureAndInheritance.java +++ b/generics/ErasureAndInheritance.java @@ -22,4 +22,4 @@ public class ErasureAndInheritance { Object obj = d2.get(); d2.set(obj); // Warning here! } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/generics/FactoryConstraint.java b/generics/FactoryConstraint.java index 8d76740a..4df43c6d 100644 --- a/generics/FactoryConstraint.java +++ b/generics/FactoryConstraint.java @@ -13,6 +13,7 @@ class Foo2 { } class IntegerFactory implements FactoryI { + @Override public Integer create() { return new Integer(0); } @@ -20,6 +21,7 @@ class IntegerFactory implements FactoryI { class Widget { public static class Factory implements FactoryI { + @Override public Widget create() { return new Widget(); } @@ -28,7 +30,7 @@ class Widget { public class FactoryConstraint { public static void main(String[] args) { - new Foo2(new IntegerFactory()); - new Foo2(new Widget.Factory()); + new Foo2<>(new IntegerFactory()); + new Foo2<>(new Widget.Factory()); } } ///:~ diff --git a/generics/Fibonacci.java b/generics/Fibonacci.java index 6e9d8df3..012dbada 100644 --- a/generics/Fibonacci.java +++ b/generics/Fibonacci.java @@ -4,6 +4,7 @@ import net.mindview.util.*; public class Fibonacci implements Generator { private int count = 0; + @Override public Integer next() { return fib(count++); } private int fib(int n) { if(n < 2) return 1; diff --git a/generics/Fill.java b/generics/Fill.java index 8f68b7e6..1fca1ba9 100644 --- a/generics/Fill.java +++ b/generics/Fill.java @@ -23,6 +23,7 @@ public class Fill { class Contract { private static long counter = 0; private final long id = counter++; + @Override public String toString() { return getClass().getName() + " " + id; } @@ -32,13 +33,13 @@ class TitleTransfer extends Contract {} class FillTest { public static void main(String[] args) { - List contracts = new ArrayList(); + 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(); + new SimpleQueue<>(); // Won't work. fill() is not generic enough: // Fill.fill(contractQueue, Contract.class, 3); } diff --git a/generics/Fill2.java b/generics/Fill2.java index bdef35f4..cbac1482 100644 --- a/generics/Fill2.java +++ b/generics/Fill2.java @@ -34,6 +34,7 @@ class AddableCollectionAdapter implements Addable { public AddableCollectionAdapter(Collection c) { this.c = c; } + @Override public void add(T item) { c.add(item); } } @@ -41,7 +42,7 @@ class AddableCollectionAdapter implements Addable { class Adapter { public static Addable collectionAdapter(Collection c) { - return new AddableCollectionAdapter(c); + return new AddableCollectionAdapter<>(c); } } @@ -49,15 +50,16 @@ class Adapter { // 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(); + List carrier = new ArrayList<>(); Fill2.fill( - new AddableCollectionAdapter(carrier), + new AddableCollectionAdapter<>(carrier), Coffee.class, 3); // Helper method captures the type: Fill2.fill(Adapter.collectionAdapter(carrier), @@ -67,7 +69,7 @@ class Fill2Test { print("----------------------"); // Use an adapted class: AddableSimpleQueue coffeeQueue = - new AddableSimpleQueue(); + new AddableSimpleQueue<>(); Fill2.fill(coffeeQueue, Mocha.class, 4); Fill2.fill(coffeeQueue, Latte.class, 1); for(Coffee c: coffeeQueue) diff --git a/generics/FilledListMaker.java b/generics/FilledListMaker.java index 89aab9eb..469675c6 100644 --- a/generics/FilledListMaker.java +++ b/generics/FilledListMaker.java @@ -3,14 +3,14 @@ import java.util.*; public class FilledListMaker { List create(T t, int n) { - List result = new ArrayList(); + List result = new ArrayList<>(); for(int i = 0; i < n; i++) result.add(t); return result; } public static void main(String[] args) { FilledListMaker stringMaker = - new FilledListMaker(); + new FilledListMaker<>(); List list = stringMaker.create("Hello", 4); System.out.println(list); } diff --git a/generics/Functional.java b/generics/Functional.java index be84f7fb..6dac0a5e 100644 --- a/generics/Functional.java +++ b/generics/Functional.java @@ -41,7 +41,7 @@ public class Functional { // function object for each object in the list: public static List transform(Iterable seq, UnaryFunction func) { - List result = new ArrayList(); + List result = new ArrayList<>(); for(T t : seq) result.add(func.function(t)); return result; @@ -50,7 +50,7 @@ public class Functional { // and returns a list of items that produced "true": public static List filter(Iterable seq, UnaryPredicate pred) { - List result = new ArrayList(); + List result = new ArrayList<>(); for(T t : seq) if(pred.test(t)) result.add(t); @@ -59,30 +59,35 @@ public class Functional { // 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())); @@ -92,6 +97,7 @@ public class Functional { // (Units in the last place): static class BigDecimalUlp implements UnaryFunction { + @Override public BigDecimal function(BigDecimal x) { return x.ulp(); } @@ -100,6 +106,7 @@ public class Functional { implements UnaryPredicate { private T bound; public GreaterThan(T bound) { this.bound = bound; } + @Override public boolean test(T x) { return x.compareTo(bound) > 0; } @@ -107,10 +114,12 @@ public class Functional { 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) { @@ -122,12 +131,12 @@ public class Functional { result = reduce(li, new IntegerSubtracter()); print(result); - print(filter(li, new GreaterThan(4))); + print(filter(li, new GreaterThan<>(4))); print(forEach(li, new MultiplyingIntegerCollector()).result()); - print(forEach(filter(li, new GreaterThan(4)), + print(forEach(filter(li, new GreaterThan<>(4)), new MultiplyingIntegerCollector()).result()); MathContext mc = new MathContext(7); @@ -138,10 +147,10 @@ public class Functional { print(rbd); print(filter(lbd, - new GreaterThan(new BigDecimal(3)))); + new GreaterThan<>(new BigDecimal(3)))); // Use the prime-generation facility of BigInteger: - List lbi = new ArrayList(); + List lbi = new ArrayList<>(); BigInteger bi = BigInteger.valueOf(11); for(int i = 0; i < 11; i++) { lbi.add(bi); @@ -175,4 +184,4 @@ public class Functional { true 265 [0.000001, 0.000001, 0.000001, 0.000001] -*///:~ \ No newline at end of file +*///:~ diff --git a/generics/Generators.java b/generics/Generators.java index 164e0f67..ac1238d8 100644 --- a/generics/Generators.java +++ b/generics/Generators.java @@ -13,11 +13,11 @@ public class Generators { } public static void main(String[] args) { Collection coffee = fill( - new ArrayList(), new CoffeeGenerator(), 4); + new ArrayList<>(), new CoffeeGenerator(), 4); for(Coffee c : coffee) System.out.println(c); Collection fnumbers = fill( - new ArrayList(), new Fibonacci(), 12); + new ArrayList<>(), new Fibonacci(), 12); for(int i : fnumbers) System.out.print(i + ", "); } diff --git a/generics/GenericArray.java b/generics/GenericArray.java index 12348f29..7d2090a9 100644 --- a/generics/GenericArray.java +++ b/generics/GenericArray.java @@ -13,8 +13,7 @@ public class GenericArray { // Method that exposes the underlying representation: public T[] rep() { return array; } public static void main(String[] args) { - GenericArray gai = - new GenericArray(10); + GenericArray gai = new GenericArray<>(10); // This causes a ClassCastException: //! Integer[] ia = gai.rep(); // This is OK: diff --git a/generics/GenericArray2.java b/generics/GenericArray2.java index 18bb2307..b88afaf8 100644 --- a/generics/GenericArray2.java +++ b/generics/GenericArray2.java @@ -15,8 +15,8 @@ public class GenericArray2 { return (T[])array; // Warning: unchecked cast } public static void main(String[] args) { - GenericArray2 gai = - new GenericArray2(10); + GenericArray2 gai = + new GenericArray2<>(10); for(int i = 0; i < 10; i ++) gai.put(i, i); for(int i = 0; i < 10; i ++) diff --git a/generics/GenericArrayWithTypeToken.java b/generics/GenericArrayWithTypeToken.java index 10f52213..1ad5d0e2 100644 --- a/generics/GenericArrayWithTypeToken.java +++ b/generics/GenericArrayWithTypeToken.java @@ -15,7 +15,7 @@ public class GenericArrayWithTypeToken { public T[] rep() { return array; } public static void main(String[] args) { GenericArrayWithTypeToken gai = - new GenericArrayWithTypeToken( + new GenericArrayWithTypeToken<>( Integer.class, 10); // This now works: Integer[] ia = gai.rep(); diff --git a/generics/GenericCast.java b/generics/GenericCast.java index 6266d091..9c5b711f 100644 --- a/generics/GenericCast.java +++ b/generics/GenericCast.java @@ -15,7 +15,7 @@ public class GenericCast { public static final int SIZE = 10; public static void main(String[] args) { FixedSizeStack strings = - new FixedSizeStack(SIZE); + 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++) { diff --git a/generics/GenericHolder.java b/generics/GenericHolder.java index 1de764b8..d95062bd 100644 --- a/generics/GenericHolder.java +++ b/generics/GenericHolder.java @@ -6,7 +6,7 @@ public class GenericHolder { public T get() { return obj; } public static void main(String[] args) { GenericHolder holder = - new GenericHolder(); + new GenericHolder<>(); holder.set("Item"); String s = holder.get(); } diff --git a/generics/GenericReading.java b/generics/GenericReading.java index 44a969d6..65fd0c51 100644 --- a/generics/GenericReading.java +++ b/generics/GenericReading.java @@ -19,7 +19,7 @@ public class GenericReading { T readExact(List list) { return list.get(0); } } static void f2() { - Reader fruitReader = new Reader(); + Reader fruitReader = new Reader<>(); Fruit f = fruitReader.readExact(fruit); // Fruit a = fruitReader.readExact(apples); // Error: // readExact(List) cannot be @@ -32,7 +32,7 @@ public class GenericReading { } static void f3() { CovariantReader fruitReader = - new CovariantReader(); + new CovariantReader<>(); Fruit f = fruitReader.readCovariant(fruit); Fruit a = fruitReader.readCovariant(apples); } diff --git a/generics/GenericVarargs.java b/generics/GenericVarargs.java index 34ea4e39..5df386c8 100644 --- a/generics/GenericVarargs.java +++ b/generics/GenericVarargs.java @@ -3,7 +3,7 @@ import java.util.*; public class GenericVarargs { public static List makeList(T... args) { - List result = new ArrayList(); + List result = new ArrayList<>(); for(T item : args) result.add(item); return result; diff --git a/generics/GenericWriting.java b/generics/GenericWriting.java index 59f7ae08..ba315e99 100644 --- a/generics/GenericWriting.java +++ b/generics/GenericWriting.java @@ -5,8 +5,8 @@ public class GenericWriting { static void writeExact(List list, T item) { list.add(item); } - static List apples = new ArrayList(); - static List fruit = new ArrayList(); + static List apples = new ArrayList<>(); + static List fruit = new ArrayList<>(); static void f1() { writeExact(apples, new Apple()); writeExact(fruit, new Apple()); @@ -20,4 +20,4 @@ public class GenericWriting { writeWithWildcard(fruit, new Apple()); } public static void main(String[] args) { f1(); f2(); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/generics/GenericsAndCovariance.java b/generics/GenericsAndCovariance.java index 8cc66146..df3c04d8 100644 --- a/generics/GenericsAndCovariance.java +++ b/generics/GenericsAndCovariance.java @@ -4,7 +4,7 @@ import java.util.*; public class GenericsAndCovariance { public static void main(String[] args) { // Wildcards allow covariance: - List flist = new ArrayList(); + List flist = new ArrayList<>(); // Compile Error: can't add any type of object: // flist.add(new Apple()); // flist.add(new Fruit()); diff --git a/generics/Holder.java b/generics/Holder.java index 40396441..2debd712 100644 --- a/generics/Holder.java +++ b/generics/Holder.java @@ -6,11 +6,12 @@ public class Holder { public Holder(T val) { value = val; } public void set(T val) { value = val; } public T get() { return value; } + @Override public boolean equals(Object obj) { return value.equals(obj); } public static void main(String[] args) { - Holder Apple = new Holder(new Apple()); + Holder Apple = new Holder<>(new Apple()); Apple d = Apple.get(); Apple.set(d); // Holder Fruit = Apple; // Cannot upcast diff --git a/generics/Holder3.java b/generics/Holder3.java index 3753f21a..74c9704d 100644 --- a/generics/Holder3.java +++ b/generics/Holder3.java @@ -7,7 +7,7 @@ public class Holder3 { public T get() { return a; } public static void main(String[] args) { Holder3 h3 = - new Holder3(new Automobile()); + new Holder3<>(new Automobile()); Automobile a = h3.get(); // No cast needed // h3.set("Not an Automobile"); // Error // h3.set(1); // Error diff --git a/generics/InheritBounds.java b/generics/InheritBounds.java index 53f40f9c..d94da6b2 100644 --- a/generics/InheritBounds.java +++ b/generics/InheritBounds.java @@ -28,7 +28,7 @@ extends ColoredDimension2 { public class InheritBounds { public static void main(String[] args) { Solid2 solid2 = - new Solid2(new Bounded()); + new Solid2<>(new Bounded()); solid2.color(); solid2.getY(); solid2.weight(); diff --git a/generics/InstantiateGenericType.java b/generics/InstantiateGenericType.java index 32672a18..c00daf5e 100644 --- a/generics/InstantiateGenericType.java +++ b/generics/InstantiateGenericType.java @@ -17,11 +17,11 @@ class Employee {} public class InstantiateGenericType { public static void main(String[] args) { ClassAsFactory fe = - new ClassAsFactory(Employee.class); + new ClassAsFactory<>(Employee.class); print("ClassAsFactory succeeded"); try { ClassAsFactory fi = - new ClassAsFactory(Integer.class); + new ClassAsFactory<>(Integer.class); } catch(Exception e) { print("ClassAsFactory failed"); } diff --git a/generics/IterableFibonacci.java b/generics/IterableFibonacci.java index 54d98a65..26ea9af5 100644 --- a/generics/IterableFibonacci.java +++ b/generics/IterableFibonacci.java @@ -6,13 +6,17 @@ public class IterableFibonacci extends Fibonacci implements Iterable { private int n; public IterableFibonacci(int count) { n = count; } + @Override public Iterator iterator() { return new Iterator() { + @Override public boolean hasNext() { return n > 0; } + @Override public Integer next() { n--; return IterableFibonacci.this.next(); } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } diff --git a/generics/LatentReflection.java b/generics/LatentReflection.java index 642fc3af..3586702e 100644 --- a/generics/LatentReflection.java +++ b/generics/LatentReflection.java @@ -8,6 +8,7 @@ class Mime { public void walkAgainstTheWind() {} public void sit() { print("Pretending to sit"); } public void pushInvisibleWalls() {} + @Override public String toString() { return "Mime"; } } diff --git a/generics/LinkedStack.java b/generics/LinkedStack.java index 174cb964..c18c758c 100644 --- a/generics/LinkedStack.java +++ b/generics/LinkedStack.java @@ -12,9 +12,9 @@ public class LinkedStack { } boolean end() { return item == null && next == null; } } - private Node top = new Node(); // End sentinel + private Node top = new Node<>(); // End sentinel public void push(T item) { - top = new Node(item, top); + top = new Node<>(item, top); } public T pop() { T result = top.item; @@ -23,7 +23,7 @@ public class LinkedStack { return result; } public static void main(String[] args) { - LinkedStack lss = new LinkedStack(); + LinkedStack lss = new LinkedStack<>(); for(String s : "Phasers on stun!".split(" ")) lss.push(s); String s; diff --git a/generics/ListMaker.java b/generics/ListMaker.java index 2f75a24f..1034aada 100644 --- a/generics/ListMaker.java +++ b/generics/ListMaker.java @@ -2,9 +2,9 @@ import java.util.*; public class ListMaker { - List create() { return new ArrayList(); } + 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/ListOfGenerics.java b/generics/ListOfGenerics.java index ba803263..52c51d2d 100644 --- a/generics/ListOfGenerics.java +++ b/generics/ListOfGenerics.java @@ -2,7 +2,7 @@ import java.util.*; public class ListOfGenerics { - private List array = new ArrayList(); + private List array = new ArrayList<>(); public void add(T item) { array.add(item); } public T get(int index) { return array.get(index); } } ///:~ diff --git a/generics/ListOfInt.java b/generics/ListOfInt.java index 7d73184f..554696bb 100644 --- a/generics/ListOfInt.java +++ b/generics/ListOfInt.java @@ -5,7 +5,7 @@ import java.util.*; public class ListOfInt { public static void main(String[] args) { - List li = new ArrayList(); + List li = new ArrayList<>(); for(int i = 0; i < 5; i++) li.add(i); for(int i : li) diff --git a/generics/LostInformation.java b/generics/LostInformation.java index 960ad2ff..30631875 100644 --- a/generics/LostInformation.java +++ b/generics/LostInformation.java @@ -8,10 +8,10 @@ class Particle {} public class LostInformation { public static void main(String[] args) { - List list = new ArrayList(); - Map map = new HashMap(); - Quark quark = new Quark(); - Particle p = new Particle(); + List list = new ArrayList<>(); + Map map = new HashMap<>(); + Quark quark = new Quark<>(); + Particle p = new Particle<>(); System.out.println(Arrays.toString( list.getClass().getTypeParameters())); System.out.println(Arrays.toString( diff --git a/generics/Manipulation.java b/generics/Manipulation.java index b8f05564..ee5621c2 100644 --- a/generics/Manipulation.java +++ b/generics/Manipulation.java @@ -12,7 +12,7 @@ public class Manipulation { public static void main(String[] args) { HasF hf = new HasF(); Manipulator manipulator = - new Manipulator(hf); + new Manipulator<>(hf); manipulator.manipulate(); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/generics/Mixins.java b/generics/Mixins.java index d4e3800f..81028370 100644 --- a/generics/Mixins.java +++ b/generics/Mixins.java @@ -8,6 +8,7 @@ class TimeStampedImp implements TimeStamped { public TimeStampedImp() { timeStamp = new Date().getTime(); } + @Override public long getStamp() { return timeStamp; } } @@ -16,6 +17,7 @@ interface SerialNumbered { long getSerialNumber(); } class SerialNumberedImp implements SerialNumbered { private static long counter = 1; private final long serialNumber = counter++; + @Override public long getSerialNumber() { return serialNumber; } } @@ -26,7 +28,9 @@ interface Basic { class BasicImp implements Basic { private String value; + @Override public void set(String val) { value = val; } + @Override public String get() { return value; } } @@ -35,7 +39,9 @@ implements TimeStamped, SerialNumbered { private TimeStamped timeStamp = new TimeStampedImp(); private SerialNumbered serialNumber = new SerialNumberedImp(); + @Override public long getStamp() { return timeStamp.getStamp(); } + @Override public long getSerialNumber() { return serialNumber.getSerialNumber(); } diff --git a/generics/NonCovariantGenerics.java b/generics/NonCovariantGenerics.java index 536d16d8..55638155 100644 --- a/generics/NonCovariantGenerics.java +++ b/generics/NonCovariantGenerics.java @@ -4,5 +4,5 @@ import java.util.*; public class NonCovariantGenerics { // Compile Error: incompatible types: - List flist = new ArrayList(); + List flist = new ArrayList<>(); } ///:~ diff --git a/generics/RandomList.java b/generics/RandomList.java index 20362f90..d06c912f 100644 --- a/generics/RandomList.java +++ b/generics/RandomList.java @@ -2,14 +2,14 @@ import java.util.*; public class RandomList { - private ArrayList storage = new ArrayList(); + private ArrayList storage = new ArrayList<>(); private Random rand = new Random(47); public void add(T item) { storage.add(item); } public T select() { return storage.get(rand.nextInt(storage.size())); } public static void main(String[] args) { - RandomList rs = new RandomList(); + RandomList rs = new RandomList<>(); for(String s: ("The quick brown fox jumped over " + "the lazy brown dog").split(" ")) rs.add(s); diff --git a/generics/SelfBounding.java b/generics/SelfBounding.java index 606b675e..db26fd5a 100644 --- a/generics/SelfBounding.java +++ b/generics/SelfBounding.java @@ -33,4 +33,4 @@ public class SelfBounding { C c = new C(); c = c.setAndGet(new C()); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/generics/SimpleQueue.java b/generics/SimpleQueue.java index f8419cf2..b7b65ae9 100644 --- a/generics/SimpleQueue.java +++ b/generics/SimpleQueue.java @@ -3,9 +3,10 @@ import java.util.*; public class SimpleQueue implements Iterable { - private LinkedList storage = new LinkedList(); + private LinkedList storage = new LinkedList<>(); public void add(T t) { storage.offer(t); } public T get() { return storage.poll(); } + @Override public Iterator iterator() { return storage.iterator(); } diff --git a/generics/Store.java b/generics/Store.java index 51662d98..c922eb84 100644 --- a/generics/Store.java +++ b/generics/Store.java @@ -13,6 +13,7 @@ class Product { this.price = price; System.out.println(toString()); } + @Override public String toString() { return id + ": " + description + ", price: $" + price; } @@ -22,6 +23,7 @@ class Product { public static Generator generator = new Generator() { private Random rand = new Random(47); + @Override public Product next() { return new Product(rand.nextInt(1000), "Test", Math.round(rand.nextDouble() * 1000.0) + 0.99); @@ -47,12 +49,13 @@ class Office {} public class Store extends ArrayList { private ArrayList checkouts = - new ArrayList(); + new ArrayList<>(); private Office office = new Office(); public Store(int nAisles, int nShelves, int nProducts) { for(int i = 0; i < nAisles; i++) add(new Aisle(nShelves, nProducts)); } + @Override public String toString() { StringBuilder result = new StringBuilder(); for(Aisle a : this) diff --git a/generics/ThrowGenericException.java b/generics/ThrowGenericException.java index 48810c8b..f8edbcff 100644 --- a/generics/ThrowGenericException.java +++ b/generics/ThrowGenericException.java @@ -8,7 +8,7 @@ interface Processor { class ProcessRunner extends ArrayList> { List processAll() throws E { - List resultCollector = new ArrayList(); + List resultCollector = new ArrayList<>(); for(Processor processor : this) processor.process(resultCollector); return resultCollector; @@ -19,6 +19,7 @@ class Failure1 extends Exception {} class Processor1 implements Processor { static int count = 3; + @Override public void process(List resultCollector) throws Failure1 { if(count-- > 1) @@ -34,6 +35,7 @@ class Failure2 extends Exception {} class Processor2 implements Processor { static int count = 2; + @Override public void process(List resultCollector) throws Failure2 { if(count-- == 0) @@ -49,7 +51,7 @@ class Processor2 implements Processor { public class ThrowGenericException { public static void main(String[] args) { ProcessRunner runner = - new ProcessRunner(); + new ProcessRunner<>(); for(int i = 0; i < 3; i++) runner.add(new Processor1()); try { @@ -59,7 +61,7 @@ public class ThrowGenericException { } ProcessRunner runner2 = - new ProcessRunner(); + new ProcessRunner<>(); for(int i = 0; i < 3; i++) runner2.add(new Processor2()); try { diff --git a/generics/TupleList.java b/generics/TupleList.java index 260adb5b..9513bb5c 100644 --- a/generics/TupleList.java +++ b/generics/TupleList.java @@ -7,7 +7,7 @@ public class TupleList extends ArrayList> { public static void main(String[] args) { TupleList tl = - new TupleList(); + new TupleList<>(); tl.add(TupleTest.h()); tl.add(TupleTest.h()); for(FourTuple i: tl) diff --git a/generics/TupleTest.java b/generics/TupleTest.java index 302cb1c0..cb9e0f58 100644 --- a/generics/TupleTest.java +++ b/generics/TupleTest.java @@ -7,22 +7,21 @@ class Vehicle {} public class TupleTest { static TwoTuple f() { // Autoboxing converts the int to Integer: - return new TwoTuple("hi", 47); + return new TwoTuple<>("hi", 47); } static ThreeTuple g() { - return new ThreeTuple( - new Amphibian(), "hi", 47); + return new ThreeTuple<>(new Amphibian(), "hi", 47); } static FourTuple h() { return - new FourTuple( + new FourTuple<>( new Vehicle(), new Amphibian(), "hi", 47); } static FiveTuple k() { return new - FiveTuple( + FiveTuple<>( new Vehicle(), new Amphibian(), "hi", 47, 11.1); } public static void main(String[] args) { diff --git a/generics/UnboundedWildcards1.java b/generics/UnboundedWildcards1.java index 3e7fc5a8..8cbad8a4 100644 --- a/generics/UnboundedWildcards1.java +++ b/generics/UnboundedWildcards1.java @@ -27,12 +27,12 @@ public class UnboundedWildcards1 { // assign3(new ArrayList()); // Warning: // Unchecked conversion. Found: ArrayList // Required: List - assign1(new ArrayList()); - assign2(new ArrayList()); - assign3(new ArrayList()); + assign1(new ArrayList<>()); + assign2(new ArrayList<>()); + assign3(new ArrayList<>()); // Both forms are acceptable as List: List wildList = new ArrayList(); - wildList = new ArrayList(); + wildList = new ArrayList<>(); assign1(wildList); assign2(wildList); assign3(wildList); diff --git a/generics/UnboundedWildcards2.java b/generics/UnboundedWildcards2.java index 287774c3..a2ffe625 100644 --- a/generics/UnboundedWildcards2.java +++ b/generics/UnboundedWildcards2.java @@ -14,8 +14,8 @@ public class UnboundedWildcards2 { // assign3(new HashMap()); // Warning: // Unchecked conversion. Found: HashMap // Required: Map - assign1(new HashMap()); - assign2(new HashMap()); - assign3(new HashMap()); + assign1(new HashMap<>()); + assign2(new HashMap<>()); + assign3(new HashMap<>()); } } ///:~ diff --git a/generics/UseList.java b/generics/UseList.java index 4f78689e..fe8a9bf2 100644 --- a/generics/UseList.java +++ b/generics/UseList.java @@ -5,4 +5,4 @@ import java.util.*; public class UseList { void f(List v) {} void f(List v) {} -} ///:~ \ No newline at end of file +} ///:~ diff --git a/generics/Wildcards.java b/generics/Wildcards.java index c210ae7a..5ac10941 100644 --- a/generics/Wildcards.java +++ b/generics/Wildcards.java @@ -56,12 +56,12 @@ public class Wildcards { Object obj = holder.get(); } public static void main(String[] args) { - Holder raw = new Holder(); + Holder raw = new Holder<>(); // Or: raw = new Holder(); - Holder qualified = new Holder(); - Holder unbounded = new Holder(); - Holder bounded = new Holder(); + Holder qualified = new Holder<>(); + Holder unbounded = new Holder<>(); + Holder bounded = new Holder<>(); Long lng = 1L; rawArgs(raw, lng); @@ -119,4 +119,4 @@ public class Wildcards { // wildSupertype(Holder,T) cannot be // applied to (Holder,Long) } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/generics/build.xml b/generics/build.xml new file mode 100644 index 00000000..28b9a737 --- /dev/null +++ b/generics/build.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/generics/coffee/Coffee.java b/generics/coffee/Coffee.java index 3d34b659..4990e025 100644 --- a/generics/coffee/Coffee.java +++ b/generics/coffee/Coffee.java @@ -4,6 +4,7 @@ package generics.coffee; public class Coffee { private static long counter = 0; private final long id = counter++; + @Override public String toString() { return getClass().getSimpleName() + " " + id; } diff --git a/generics/coffee/CoffeeGenerator.java b/generics/coffee/CoffeeGenerator.java index a54d8a11..43869c1a 100644 --- a/generics/coffee/CoffeeGenerator.java +++ b/generics/coffee/CoffeeGenerator.java @@ -13,6 +13,7 @@ implements Generator, Iterable { // For iteration: private int size = 0; public CoffeeGenerator(int sz) { size = sz; } + @Override public Coffee next() { try { return (Coffee) @@ -24,15 +25,19 @@ implements Generator, Iterable { } class CoffeeIterator implements Iterator { int count = size; + @Override public boolean hasNext() { return count > 0; } + @Override public Coffee next() { count--; return CoffeeGenerator.this.next(); } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } }; + @Override public Iterator iterator() { return new CoffeeIterator(); } @@ -54,4 +59,4 @@ Americano 6 Latte 7 Cappuccino 8 Cappuccino 9 -*///:~ \ No newline at end of file +*///:~ diff --git a/generics/decorator/Decoration.java b/generics/decorator/Decoration.java index 916e0080..10e7bcd4 100644 --- a/generics/decorator/Decoration.java +++ b/generics/decorator/Decoration.java @@ -11,7 +11,9 @@ class Basic { class Decorator extends Basic { protected Basic basic; public Decorator(Basic basic) { this.basic = basic; } + @Override public void set(String val) { basic.set(val); } + @Override public String get() { return basic.get(); } } diff --git a/gui/Button2.java b/gui/Button2.java index 7a6f02bf..f855c2a5 100644 --- a/gui/Button2.java +++ b/gui/Button2.java @@ -11,6 +11,7 @@ public class Button2 extends JFrame { b2 = new JButton("Button 2"); private JTextField txt = new JTextField(10); class ButtonListener implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { String name = ((JButton)e.getSource()).getText(); txt.setText(name); diff --git a/gui/Button2b.java b/gui/Button2b.java index 2c7cb00b..6f26390c 100644 --- a/gui/Button2b.java +++ b/gui/Button2b.java @@ -11,6 +11,7 @@ public class Button2b extends JFrame { b2 = new JButton("Button 2"); private JTextField txt = new JTextField(10); private ActionListener bl = new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { String name = ((JButton)e.getSource()).getText(); txt.setText(name); diff --git a/gui/CheckBoxes.java b/gui/CheckBoxes.java index 1824e965..dc4b9637 100644 --- a/gui/CheckBoxes.java +++ b/gui/CheckBoxes.java @@ -13,16 +13,19 @@ public class CheckBoxes extends JFrame { cb3 = new JCheckBox("Check Box 3"); public CheckBoxes() { cb1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { trace("1", cb1); } }); cb2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { trace("2", cb2); } }); cb3.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { trace("3", cb3); } diff --git a/gui/ColorBoxes.java b/gui/ColorBoxes.java index 6744d68a..81d08f01 100644 --- a/gui/ColorBoxes.java +++ b/gui/ColorBoxes.java @@ -51,4 +51,4 @@ public class ColorBoxes extends JFrame { boxes.setUp(); run(boxes, 500, 400); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/gui/ComboBoxes.java b/gui/ComboBoxes.java index 82e9caca..03c4db15 100644 --- a/gui/ComboBoxes.java +++ b/gui/ComboBoxes.java @@ -19,12 +19,14 @@ public class ComboBoxes extends JFrame { c.addItem(description[count++]); t.setEditable(false); b.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { if(count < description.length) c.addItem(description[count++]); } }); c.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { t.setText("index: "+ c.getSelectedIndex() + " " + ((JComboBox)e.getSource()).getSelectedItem()); diff --git a/gui/Dialogs.java b/gui/Dialogs.java index 96498103..cab96fed 100644 --- a/gui/Dialogs.java +++ b/gui/Dialogs.java @@ -12,6 +12,7 @@ class MyDialog extends JDialog { add(new JLabel("Here is my dialog")); JButton ok = new JButton("OK"); ok.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { dispose(); // Closes the dialog } @@ -26,6 +27,7 @@ public class Dialogs extends JFrame { private MyDialog dlg = new MyDialog(null); public Dialogs() { b1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { dlg.setVisible(true); } diff --git a/gui/Faces.java b/gui/Faces.java index d2f9c37b..6cb65f24 100644 --- a/gui/Faces.java +++ b/gui/Faces.java @@ -20,6 +20,7 @@ public class Faces extends JFrame { jb = new JButton("JButton", faces[3]); setLayout(new FlowLayout()); jb.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { if(mad) { jb.setIcon(faces[3]); @@ -39,6 +40,7 @@ public class Faces extends JFrame { jb.setToolTipText("Yow!"); add(jb); jb2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { if(jb.isEnabled()) { jb.setEnabled(false); diff --git a/gui/FileChooserTest.java b/gui/FileChooserTest.java index 0ab55534..6a52033a 100644 --- a/gui/FileChooserTest.java +++ b/gui/FileChooserTest.java @@ -28,6 +28,7 @@ public class FileChooserTest extends JFrame { add(p, BorderLayout.NORTH); } class OpenL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { JFileChooser c = new JFileChooser(); // Demonstrate "Open" dialog: @@ -43,6 +44,7 @@ public class FileChooserTest extends JFrame { } } class SaveL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { JFileChooser c = new JFileChooser(); // Demonstrate "Save" dialog: diff --git a/gui/HTMLButton.java b/gui/HTMLButton.java index c676753b..2ea7c1b4 100644 --- a/gui/HTMLButton.java +++ b/gui/HTMLButton.java @@ -11,6 +11,7 @@ public class HTMLButton extends JFrame { "
Hello!
Press me now!"); public HTMLButton() { b.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { add(new JLabel("" + "Kapow!")); diff --git a/gui/InterruptableLongRunningCallable.java b/gui/InterruptableLongRunningCallable.java index 6acf14e8..3d5f5d74 100644 --- a/gui/InterruptableLongRunningCallable.java +++ b/gui/InterruptableLongRunningCallable.java @@ -9,6 +9,7 @@ import static net.mindview.util.SwingConsole.*; class CallableTask extends Task implements Callable { + @Override public String call() { run(); return "Return value of " + this; @@ -22,9 +23,10 @@ InterruptableLongRunningCallable extends JFrame { b2 = new JButton("End Long Running Task"), b3 = new JButton("Get results"); private TaskManager manager = - new TaskManager(); + new TaskManager<>(); public InterruptableLongRunningCallable() { b1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { CallableTask task = new CallableTask(); manager.add(task); @@ -32,12 +34,14 @@ InterruptableLongRunningCallable extends JFrame { } }); b2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { for(String result : manager.purge()) System.out.println(result); } }); b3.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { // Sample call to a Task method: for(TaskItem tt : diff --git a/gui/InterruptableLongRunningTask.java b/gui/InterruptableLongRunningTask.java index 0c888230..f8d13871 100644 --- a/gui/InterruptableLongRunningTask.java +++ b/gui/InterruptableLongRunningTask.java @@ -9,6 +9,7 @@ import static net.mindview.util.SwingConsole.*; class Task implements Runnable { private static int counter = 0; private final int id = counter++; + @Override public void run() { System.out.println(this + " started"); try { @@ -19,6 +20,7 @@ class Task implements Runnable { } System.out.println(this + " completed"); } + @Override public String toString() { return "Task " + id; } public long id() { return id; } }; @@ -31,6 +33,7 @@ public class InterruptableLongRunningTask extends JFrame { Executors.newSingleThreadExecutor(); public InterruptableLongRunningTask() { b1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { Task task = new Task(); executor.execute(task); @@ -38,6 +41,7 @@ public class InterruptableLongRunningTask extends JFrame { } }); b2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { executor.shutdownNow(); // Heavy-handed } diff --git a/gui/List.java b/gui/List.java index cb5e7f04..2c16a3e3 100644 --- a/gui/List.java +++ b/gui/List.java @@ -12,12 +12,14 @@ public class List extends JFrame { "Mint Chip", "Mocha Almond Fudge", "Rum Raisin", "Praline Cream", "Mud Pie" }; + private int count = 0; private DefaultListModel lItems = new DefaultListModel(); private JList lst = new JList(lItems); private JTextArea t = new JTextArea(flavors.length, 20); private JButton b = new JButton("Add Item"); private ActionListener bl = new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { if(count < flavors.length) { lItems.add(0, flavors[count++]); @@ -30,6 +32,7 @@ public class List extends JFrame { }; private ListSelectionListener ll = new ListSelectionListener() { + @Override public void valueChanged(ListSelectionEvent e) { if(e.getValueIsAdjusting()) return; t.setText(""); @@ -37,7 +40,6 @@ public class List extends JFrame { t.append(item + "\n"); } }; - private int count = 0; public List() { t.setEditable(false); setLayout(new FlowLayout()); diff --git a/gui/LongRunningTask.java b/gui/LongRunningTask.java index e3c1bf43..25e69297 100644 --- a/gui/LongRunningTask.java +++ b/gui/LongRunningTask.java @@ -12,6 +12,7 @@ public class LongRunningTask extends JFrame { b2 = new JButton("End Long Running Task"); public LongRunningTask() { b1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent evt) { try { TimeUnit.SECONDS.sleep(3); @@ -23,6 +24,7 @@ public class LongRunningTask extends JFrame { } }); b2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent evt) { // Interrupt yourself? Thread.currentThread().interrupt(); diff --git a/gui/LookAndFeel.java b/gui/LookAndFeel.java index 67705f7e..e4f93e0a 100644 --- a/gui/LookAndFeel.java +++ b/gui/LookAndFeel.java @@ -30,28 +30,34 @@ public class LookAndFeel extends JFrame { } public static void main(String[] args) { if(args.length == 0) usageError(); - if(args[0].equals("cross")) { - try { - UIManager.setLookAndFeel(UIManager. - getCrossPlatformLookAndFeelClassName()); - } catch(Exception e) { - e.printStackTrace(); - } - } else if(args[0].equals("system")) { - try { - UIManager.setLookAndFeel(UIManager. - getSystemLookAndFeelClassName()); - } catch(Exception e) { - e.printStackTrace(); - } - } else if(args[0].equals("motif")) { - try { - UIManager.setLookAndFeel("com.sun.java."+ - "swing.plaf.motif.MotifLookAndFeel"); - } catch(Exception e) { - e.printStackTrace(); - } - } else usageError(); + switch(args[0]) { + case "cross": + try { + UIManager.setLookAndFeel(UIManager. + getCrossPlatformLookAndFeelClassName()); + } catch(Exception e) { + e.printStackTrace(); + } + break; + case "system": + try { + UIManager.setLookAndFeel(UIManager. + getSystemLookAndFeelClassName()); + } catch(Exception e) { + e.printStackTrace(); + } + break; + case "motif": + try { + UIManager.setLookAndFeel("com.sun.java."+ + "swing.plaf.motif.MotifLookAndFeel"); + } catch(Exception e) { + e.printStackTrace(); + } + break; + default: + usageError(); + } // Note the look & feel must be set before // any components are created. run(new LookAndFeel(), 300, 300); diff --git a/gui/Menus.java b/gui/Menus.java index d5d43bee..5126679c 100644 --- a/gui/Menus.java +++ b/gui/Menus.java @@ -38,6 +38,7 @@ public class Menus extends JFrame { }; private JButton b = new JButton("Swap Menus"); class BL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { JMenuBar m = getJMenuBar(); setJMenuBar(m == mb1 ? mb2 : mb1); @@ -45,6 +46,7 @@ public class Menus extends JFrame { } } class ML implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { JMenuItem target = (JMenuItem)e.getSource(); String actionCommand = target.getActionCommand(); @@ -62,6 +64,7 @@ public class Menus extends JFrame { } } class FL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { JMenuItem target = (JMenuItem)e.getSource(); t.setText(target.getText()); @@ -71,31 +74,39 @@ public class Menus extends JFrame { // class for each different MenuItem. Then you // don't have to figure out which one it is: class FooL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { t.setText("Foo selected"); } } class BarL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { t.setText("Bar selected"); } } class BazL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { t.setText("Baz selected"); } } class CMIL implements ItemListener { + @Override public void itemStateChanged(ItemEvent e) { JCheckBoxMenuItem target = (JCheckBoxMenuItem)e.getSource(); String actionCommand = target.getActionCommand(); - if(actionCommand.equals("Guard")) - t.setText("Guard the Ice Cream! " + - "Guarding is " + target.getState()); - else if(actionCommand.equals("Hide")) - t.setText("Hide the Ice Cream! " + - "Is it hidden? " + target.getState()); + switch (actionCommand) { + case "Guard": + t.setText("Guard the Ice Cream! " + + "Guarding is " + target.getState()); + break; + case "Hide": + t.setText("Hide the Ice Cream! " + + "Is it hidden? " + target.getState()); + break; + } } } public Menus() { @@ -125,9 +136,9 @@ public class Menus extends JFrame { s.setMnemonic(KeyEvent.VK_A); f.add(s); f.setMnemonic(KeyEvent.VK_F); - for(int i = 0; i < file.length; i++) { - file[i].addActionListener(ml); - f.add(file[i]); + for (JMenuItem file1 : file) { + file1.addActionListener(ml); + f.add(file1); } mb1.add(f); mb1.add(m); diff --git a/gui/MessageBoxes.java b/gui/MessageBoxes.java index 513d93b1..8b64108b 100644 --- a/gui/MessageBoxes.java +++ b/gui/MessageBoxes.java @@ -12,18 +12,20 @@ public class MessageBoxes extends JFrame { new JButton("3 Vals") }; private JTextField txt = new JTextField(15); - private ActionListener al = new ActionListener() { - public void actionPerformed(ActionEvent e) { - String id = ((JButton)e.getSource()).getText(); - if(id.equals("Alert")) + private ActionListener al = (ActionEvent e) -> { + String id = ((JButton)e.getSource()).getText(); + switch (id) { + case "Alert": JOptionPane.showMessageDialog(null, "There's a bug on you!", "Hey!", JOptionPane.ERROR_MESSAGE); - else if(id.equals("Yes/No")) + break; + case "Yes/No": JOptionPane.showConfirmDialog(null, "or no", "choose yes", JOptionPane.YES_NO_OPTION); - else if(id.equals("Color")) { + break; + case "Color": Object[] options = { "Red", "Green" }; int sel = JOptionPane.showOptionDialog( null, "Choose a Color!", "Warning", @@ -32,11 +34,14 @@ public class MessageBoxes extends JFrame { options, options[0]); if(sel != JOptionPane.CLOSED_OPTION) txt.setText("Color Selected: " + options[sel]); - } else if(id.equals("Input")) { + break; + case "Input": { String val = JOptionPane.showInputDialog( - "How many fingers do you see?"); + "How many fingers do you see?"); txt.setText(val); - } else if(id.equals("3 Vals")) { + break; + } + case "3 Vals": { Object[] selections = {"First", "Second", "Third"}; Object val = JOptionPane.showInputDialog( null, "Choose one", "Input", @@ -44,6 +49,7 @@ public class MessageBoxes extends JFrame { null, selections, selections[0]); if(val != null) txt.setText(val.toString()); + break; } } }; diff --git a/gui/MonitoredLongRunningCallable.java b/gui/MonitoredLongRunningCallable.java index 730140dd..51679ab6 100644 --- a/gui/MonitoredLongRunningCallable.java +++ b/gui/MonitoredLongRunningCallable.java @@ -18,6 +18,7 @@ class MonitoredCallable implements Callable { monitor.setMaximum(MAX - 1); monitor.setMillisToPopup(500); } + @Override public String call() { System.out.println(this + " started"); try { @@ -26,8 +27,8 @@ class MonitoredCallable implements Callable { if(monitor.isCanceled()) Thread.currentThread().interrupt(); final int progress = i; - SwingUtilities.invokeLater( - new Runnable() { + SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { monitor.setProgress(progress); } @@ -42,6 +43,7 @@ class MonitoredCallable implements Callable { System.out.println(this + " completed"); return "Result: " + this + " completed"; } + @Override public String toString() { return "Task " + id; } }; @@ -51,9 +53,10 @@ public class MonitoredLongRunningCallable extends JFrame { b2 = new JButton("End Long Running Task"), b3 = new JButton("Get results"); private TaskManager manager = - new TaskManager(); + new TaskManager<>(); public MonitoredLongRunningCallable() { b1.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { MonitoredCallable task = new MonitoredCallable( new ProgressMonitor( @@ -65,12 +68,14 @@ public class MonitoredLongRunningCallable extends JFrame { } }); b2.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { for(String result : manager.purge()) System.out.println(result); } }); b3.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { for(String result : manager.getResults()) System.out.println(result); diff --git a/gui/Popup.java b/gui/Popup.java index b0ed7658..b5009582 100644 --- a/gui/Popup.java +++ b/gui/Popup.java @@ -12,6 +12,7 @@ public class Popup extends JFrame { setLayout(new FlowLayout()); add(t); ActionListener al = new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { t.setText(((JMenuItem)e.getSource()).getText()); } @@ -34,9 +35,11 @@ public class Popup extends JFrame { t.addMouseListener(pl); } class PopupListener extends MouseAdapter { + @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } + @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } diff --git a/gui/Progress.java b/gui/Progress.java index 52a9307c..f96bf988 100644 --- a/gui/Progress.java +++ b/gui/Progress.java @@ -25,6 +25,7 @@ public class Progress extends JFrame { pb.setModel(sb.getModel()); // Share model add(sb); sb.addChangeListener(new ChangeListener() { + @Override public void stateChanged(ChangeEvent e) { pm.setProgress(sb.getValue()); } diff --git a/gui/RadioButtons.java b/gui/RadioButtons.java index 360e4e2d..d1a79c1a 100644 --- a/gui/RadioButtons.java +++ b/gui/RadioButtons.java @@ -13,6 +13,7 @@ public class RadioButtons extends JFrame { rb2 = new JRadioButton("two", false), rb3 = new JRadioButton("three", false); private ActionListener al = new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { t.setText("Radio button " + ((JRadioButton)e.getSource()).getText()); diff --git a/gui/ShowAddListeners.java b/gui/ShowAddListeners.java index 2a73fc4d..6e215fe5 100644 --- a/gui/ShowAddListeners.java +++ b/gui/ShowAddListeners.java @@ -15,6 +15,7 @@ public class ShowAddListeners extends JFrame { private static Pattern qualifier = Pattern.compile("\\w+\\."); class NameL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { String nm = name.getText().trim(); if(nm.length() == 0) { diff --git a/gui/SimpleMenus.java b/gui/SimpleMenus.java index 7d63e436..1b99beb5 100644 --- a/gui/SimpleMenus.java +++ b/gui/SimpleMenus.java @@ -7,6 +7,7 @@ import static net.mindview.util.SwingConsole.*; public class SimpleMenus extends JFrame { private JTextField t = new JTextField(15); private ActionListener al = new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { t.setText(((JMenuItem)e.getSource()).getText()); } diff --git a/gui/SubmitLabelManipulationTask.java b/gui/SubmitLabelManipulationTask.java index f9f2f638..483878f7 100644 --- a/gui/SubmitLabelManipulationTask.java +++ b/gui/SubmitLabelManipulationTask.java @@ -12,6 +12,7 @@ public class SubmitLabelManipulationTask { frame.setVisible(true); TimeUnit.SECONDS.sleep(1); SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { label.setText("Hey! This is Different!"); } diff --git a/gui/SubmitSwingProgram.java b/gui/SubmitSwingProgram.java index 23ae7826..a02f6364 100644 --- a/gui/SubmitSwingProgram.java +++ b/gui/SubmitSwingProgram.java @@ -15,10 +15,12 @@ public class SubmitSwingProgram extends JFrame { static SubmitSwingProgram ssp; public static void main(String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { ssp = new SubmitSwingProgram(); } }); TimeUnit.SECONDS.sleep(1); SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { ssp.label.setText("Hey! This is Different!"); } diff --git a/gui/TabbedPane1.java b/gui/TabbedPane1.java index e0b6484d..2302dc81 100644 --- a/gui/TabbedPane1.java +++ b/gui/TabbedPane1.java @@ -19,6 +19,7 @@ public class TabbedPane1 extends JFrame { tabs.addTab(flavors[i], new JButton("Tabbed pane " + i++)); tabs.addChangeListener(new ChangeListener() { + @Override public void stateChanged(ChangeEvent e) { txt.setText("Tab selected: " + tabs.getSelectedIndex()); diff --git a/gui/TextArea.java b/gui/TextArea.java index 610eecfe..bc5b465c 100644 --- a/gui/TextArea.java +++ b/gui/TextArea.java @@ -12,18 +12,19 @@ public class TextArea extends JFrame { b = new JButton("Add Data"), c = new JButton("Clear Data"); private JTextArea t = new JTextArea(20, 40); - private Map m = - new HashMap(); + private Map m = new HashMap<>(); public TextArea() { // Use up all the data: m.putAll(Countries.capitals()); b.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { for(Map.Entry me : m.entrySet()) t.append(me.getKey() + ": "+ me.getValue()+"\n"); } }); c.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { t.setText(""); } diff --git a/gui/TextFields.java b/gui/TextFields.java index afa30974..08b586d4 100644 --- a/gui/TextFields.java +++ b/gui/TextFields.java @@ -31,22 +31,27 @@ public class TextFields extends JFrame { add(t3); } class T1 implements DocumentListener { + @Override public void changedUpdate(DocumentEvent e) {} + @Override public void insertUpdate(DocumentEvent e) { t2.setText(t1.getText()); t3.setText("Text: "+ t1.getText()); } + @Override public void removeUpdate(DocumentEvent e) { t2.setText(t1.getText()); } } class T1A implements ActionListener { private int count = 0; + @Override public void actionPerformed(ActionEvent e) { t3.setText("t1 Action Event " + count++); } } class B1 implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { if(t1.getSelectedText() == null) s = t1.getText(); @@ -56,6 +61,7 @@ public class TextFields extends JFrame { } } class B2 implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { ucd.setUpperCase(false); t1.setText("Inserted by Button 2: " + s); @@ -73,6 +79,7 @@ class UpperCaseDocument extends PlainDocument { public void setUpperCase(boolean flag) { upperCase = flag; } + @Override public void insertString(int offset, String str, AttributeSet attSet) throws BadLocationException { diff --git a/gui/TextPane.java b/gui/TextPane.java index a38c1871..f6c858a5 100644 --- a/gui/TextPane.java +++ b/gui/TextPane.java @@ -13,6 +13,7 @@ public class TextPane extends JFrame { new RandomGenerator.String(7); public TextPane() { b.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { for(int i = 1; i < 10; i++) tp.setText(tp.getText() + sg.next() + "\n"); diff --git a/gui/TicTacToe.java b/gui/TicTacToe.java index 2a915feb..2c2ef3f4 100644 --- a/gui/TicTacToe.java +++ b/gui/TicTacToe.java @@ -23,6 +23,7 @@ public class TicTacToe extends JFrame { class ToeButton extends JPanel { private State state = State.BLANK; public ToeButton() { addMouseListener(new ML()); } + @Override public void paintComponent(Graphics g) { super.paintComponent(g); int @@ -41,6 +42,7 @@ public class TicTacToe extends JFrame { g.drawOval(x1, y1, x1 + wide/2, y1 + high/2); } class ML extends MouseAdapter { + @Override public void mousePressed(MouseEvent e) { if(state == State.BLANK) { state = turn; @@ -56,6 +58,7 @@ public class TicTacToe extends JFrame { } } class BL implements ActionListener { + @Override public void actionPerformed(ActionEvent e) { JDialog d = new ToeDialog( new Integer(rows.getText()), diff --git a/gui/TrackEvent.java b/gui/TrackEvent.java index 696d324e..9f55e2d5 100644 --- a/gui/TrackEvent.java +++ b/gui/TrackEvent.java @@ -8,7 +8,7 @@ import static net.mindview.util.SwingConsole.*; public class TrackEvent extends JFrame { private HashMap h = - new HashMap(); + new HashMap<>(); private String[] event = { "focusGained", "focusLost", "keyPressed", "keyReleased", "keyTyped", "mouseClicked", @@ -23,45 +23,57 @@ public class TrackEvent extends JFrame { h.get(field).setText(msg); } FocusListener fl = new FocusListener() { + @Override public void focusGained(FocusEvent e) { report("focusGained", e.paramString()); } + @Override public void focusLost(FocusEvent e) { report("focusLost", e.paramString()); } }; KeyListener kl = new KeyListener() { + @Override public void keyPressed(KeyEvent e) { report("keyPressed", e.paramString()); } + @Override public void keyReleased(KeyEvent e) { report("keyReleased", e.paramString()); } + @Override public void keyTyped(KeyEvent e) { report("keyTyped", e.paramString()); } }; MouseListener ml = new MouseListener() { + @Override public void mouseClicked(MouseEvent e) { report("mouseClicked", e.paramString()); } + @Override public void mouseEntered(MouseEvent e) { report("mouseEntered", e.paramString()); } + @Override public void mouseExited(MouseEvent e) { report("mouseExited", e.paramString()); } + @Override public void mousePressed(MouseEvent e) { report("mousePressed", e.paramString()); } + @Override public void mouseReleased(MouseEvent e) { report("mouseReleased", e.paramString()); } }; MouseMotionListener mml = new MouseMotionListener() { + @Override public void mouseDragged(MouseEvent e) { report("mouseDragged", e.paramString()); } + @Override public void mouseMoved(MouseEvent e) { report("mouseMoved", e.paramString()); } diff --git a/gui/build.xml b/gui/build.xml new file mode 100644 index 00000000..02cc5678 --- /dev/null +++ b/gui/build.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/holding/AdapterMethodIdiom.java b/holding/AdapterMethodIdiom.java index bdce8c16..e7fc366c 100644 --- a/holding/AdapterMethodIdiom.java +++ b/holding/AdapterMethodIdiom.java @@ -7,11 +7,15 @@ class ReversibleArrayList extends ArrayList { public ReversibleArrayList(Collection c) { super(c); } public Iterable reversed() { return new Iterable() { + @Override public Iterator iterator() { return new Iterator() { int current = size() - 1; + @Override public boolean hasNext() { return current > -1; } + @Override public T next() { return get(current--); } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } @@ -24,7 +28,7 @@ class ReversibleArrayList extends ArrayList { public class AdapterMethodIdiom { public static void main(String[] args) { ReversibleArrayList ral = - new ReversibleArrayList( + new ReversibleArrayList<>( Arrays.asList("To be or not to be".split(" "))); // Grabs the ordinary iterator via iterator(): for(String s : ral) @@ -37,4 +41,4 @@ public class AdapterMethodIdiom { } /* Output: To be or not to be be to not or be To -*///:~ \ No newline at end of file +*///:~ diff --git a/holding/AddingGroups.java b/holding/AddingGroups.java index b6dbc4c2..fff940b9 100644 --- a/holding/AddingGroups.java +++ b/holding/AddingGroups.java @@ -5,7 +5,7 @@ import java.util.*; public class AddingGroups { public static void main(String[] args) { Collection collection = - new ArrayList(Arrays.asList(1, 2, 3, 4, 5)); + new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); Integer[] moreInts = { 6, 7, 8, 9, 10 }; collection.addAll(Arrays.asList(moreInts)); // Runs significantly faster, but you can't diff --git a/holding/ApplesAndOrangesWithGenerics.java b/holding/ApplesAndOrangesWithGenerics.java index d1ed5f7a..76ab486e 100644 --- a/holding/ApplesAndOrangesWithGenerics.java +++ b/holding/ApplesAndOrangesWithGenerics.java @@ -3,7 +3,7 @@ import java.util.*; public class ApplesAndOrangesWithGenerics { public static void main(String[] args) { - ArrayList apples = new ArrayList(); + ArrayList apples = new ArrayList<>(); for(int i = 0; i < 3; i++) apples.add(new Apple()); // Compile-time error: diff --git a/holding/AsListInference.java b/holding/AsListInference.java index 2383c206..77b7378c 100644 --- a/holding/AsListInference.java +++ b/holding/AsListInference.java @@ -22,7 +22,7 @@ public class AsListInference { // required: java.util.List // Collections.addAll() doesn't get confused: - List snow3 = new ArrayList(); + List snow3 = new ArrayList<>(); Collections.addAll(snow3, new Light(), new Heavy()); // Give a hint using an diff --git a/holding/CollectionSequence.java b/holding/CollectionSequence.java index a0cb3168..d1b87766 100644 --- a/holding/CollectionSequence.java +++ b/holding/CollectionSequence.java @@ -5,14 +5,19 @@ import java.util.*; public class CollectionSequence extends AbstractCollection { private Pet[] pets = Pets.createArray(8); + @Override public int size() { return pets.length; } + @Override public Iterator iterator() { return new Iterator() { private int index = 0; + @Override public boolean hasNext() { return index < pets.length; } + @Override public Pet next() { return pets[index++]; } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } diff --git a/holding/CrossContainerIteration.java b/holding/CrossContainerIteration.java index bcfa5dbe..88a750e3 100644 --- a/holding/CrossContainerIteration.java +++ b/holding/CrossContainerIteration.java @@ -12,9 +12,9 @@ public class CrossContainerIteration { } public static void main(String[] args) { ArrayList pets = Pets.arrayList(8); - LinkedList petsLL = new LinkedList(pets); - HashSet petsHS = new HashSet(pets); - TreeSet petsTS = new TreeSet(pets); + LinkedList petsLL = new LinkedList<>(pets); + HashSet petsHS = new HashSet<>(pets); + TreeSet petsTS = new TreeSet<>(pets); display(pets.iterator()); display(petsLL.iterator()); display(petsHS.iterator()); @@ -23,6 +23,6 @@ public class CrossContainerIteration { } /* 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 -4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat +2:Cymric 1:Manx 0:Rat 6:Pug 5:Cymric 4:Pug 3:Mutt 7:Manx 5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat *///:~ diff --git a/holding/ForEachCollections.java b/holding/ForEachCollections.java index e1c3fe7c..3b235b28 100644 --- a/holding/ForEachCollections.java +++ b/holding/ForEachCollections.java @@ -4,7 +4,7 @@ import java.util.*; public class ForEachCollections { public static void main(String[] args) { - Collection cs = new LinkedList(); + Collection cs = new LinkedList<>(); Collections.addAll(cs, "Take the long way home".split(" ")); for(String s : cs) diff --git a/holding/GenericsAndUpcasting.java b/holding/GenericsAndUpcasting.java index 7eb4baa5..98bd2470 100644 --- a/holding/GenericsAndUpcasting.java +++ b/holding/GenericsAndUpcasting.java @@ -8,7 +8,7 @@ class Braeburn extends Apple {} public class GenericsAndUpcasting { public static void main(String[] args) { - ArrayList apples = new ArrayList(); + ArrayList apples = new ArrayList<>(); apples.add(new GrannySmith()); apples.add(new Gala()); apples.add(new Fuji()); diff --git a/holding/InterfaceVsIterator.java b/holding/InterfaceVsIterator.java index d3020cd5..0b9430cb 100644 --- a/holding/InterfaceVsIterator.java +++ b/holding/InterfaceVsIterator.java @@ -17,9 +17,8 @@ public class InterfaceVsIterator { } public static void main(String[] args) { List petList = Pets.arrayList(8); - Set petSet = new HashSet(petList); - Map petMap = - new LinkedHashMap(); + Set petSet = new HashSet<>(petList); + Map petMap = new LinkedHashMap<>(); String[] names = ("Ralph, Eric, Robin, Lacey, " + "Britney, Sam, Spot, Fluffy").split(", "); for(int i = 0; i < names.length; i++) @@ -35,9 +34,9 @@ public class InterfaceVsIterator { } } /* Output: 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat +2:Cymric 1:Manx 0:Rat 6:Pug 5:Cymric 4:Pug 3:Mutt 7:Manx 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx -4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat +2:Cymric 1:Manx 0:Rat 6:Pug 5:Cymric 4:Pug 3:Mutt 7:Manx {Ralph=Rat, Eric=Manx, Robin=Cymric, Lacey=Mutt, Britney=Pug, Sam=Cymric, Spot=Pug, Fluffy=Manx} [Ralph, Eric, Robin, Lacey, Britney, Sam, Spot, Fluffy] 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx diff --git a/holding/IterableClass.java b/holding/IterableClass.java index e580a434..72666127 100644 --- a/holding/IterableClass.java +++ b/holding/IterableClass.java @@ -5,13 +5,17 @@ import java.util.*; public class IterableClass implements Iterable { protected String[] words = ("And that is how " + "we know the Earth to be banana-shaped.").split(" "); + @Override public Iterator iterator() { return new Iterator() { private int index = 0; + @Override public boolean hasNext() { return index < words.length; } + @Override public String next() { return words[index++]; } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } diff --git a/holding/LinkedListFeatures.java b/holding/LinkedListFeatures.java index c45bea96..264046aa 100644 --- a/holding/LinkedListFeatures.java +++ b/holding/LinkedListFeatures.java @@ -6,7 +6,7 @@ import static net.mindview.util.Print.*; public class LinkedListFeatures { public static void main(String[] args) { LinkedList pets = - new LinkedList(Pets.arrayList(5)); + new LinkedList<>(Pets.arrayList(5)); print(pets); // Identical: print("pets.getFirst(): " + pets.getFirst()); diff --git a/holding/ListFeatures.java b/holding/ListFeatures.java index c6a8bebb..e5c8ccb0 100644 --- a/holding/ListFeatures.java +++ b/holding/ListFeatures.java @@ -33,12 +33,12 @@ public class ListFeatures { Collections.shuffle(sub, rand); // Mix it up print("shuffled subList: " + sub); print("12: " + pets.containsAll(sub)); - List copy = new ArrayList(pets); + List copy = new ArrayList<>(pets); sub = Arrays.asList(pets.get(1), pets.get(4)); print("sub: " + sub); copy.retainAll(sub); print("13: " + copy); - copy = new ArrayList(pets); // Get a fresh copy + copy = new ArrayList<>(pets); // Get a fresh copy copy.remove(2); // Remove by index print("14: " + copy); copy.removeAll(sub); // Only removes exact objects diff --git a/holding/MapOfList.java b/holding/MapOfList.java index 153ea132..c60ac649 100644 --- a/holding/MapOfList.java +++ b/holding/MapOfList.java @@ -6,7 +6,7 @@ import static net.mindview.util.Print.*; public class MapOfList { public static Map> - petPeople = new HashMap>(); + petPeople = new HashMap<>(); static { petPeople.put(new Person("Dawn"), Arrays.asList(new Cymric("Molly"),new Mutt("Spot"))); @@ -33,22 +33,22 @@ public class MapOfList { } } } /* Output: -People: [Person Luke, Person Marilyn, Person Isaac, Person Dawn, Person Kate] -Pets: [[Rat Fuzzy, Rat Fizzy], [Pug Louie aka Louis Snorkelstein Dupree, Cat Stanford aka Stinky el Negro, Cat Pinkola], [Rat Freckly], [Cymric Molly, Mutt Spot], [Cat Shackleton, Cat Elsie May, Dog Margrett]] -Person Luke has: - Rat Fuzzy - Rat Fizzy +People: [Person Marilyn, Person Luke, Person Isaac, Person Kate, Person Dawn] +Pets: [[Pug Louie aka Louis Snorkelstein Dupree, Cat Stanford aka Stinky el Negro, Cat Pinkola], [Rat Fuzzy, Rat Fizzy], [Rat Freckly], [Cat Shackleton, Cat Elsie May, Dog Margrett], [Cymric Molly, Mutt Spot]] Person Marilyn has: Pug Louie aka Louis Snorkelstein Dupree Cat Stanford aka Stinky el Negro Cat Pinkola +Person Luke has: + Rat Fuzzy + Rat Fizzy Person Isaac has: Rat Freckly -Person Dawn has: - Cymric Molly - Mutt Spot Person Kate has: Cat Shackleton Cat Elsie May Dog Margrett +Person Dawn has: + Cymric Molly + Mutt Spot *///:~ diff --git a/holding/ModifyingArraysAsList.java b/holding/ModifyingArraysAsList.java index 19174d13..3f57d4d1 100644 --- a/holding/ModifyingArraysAsList.java +++ b/holding/ModifyingArraysAsList.java @@ -6,7 +6,7 @@ public class ModifyingArraysAsList { Random rand = new Random(47); Integer[] ia = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; List list1 = - new ArrayList(Arrays.asList(ia)); + new ArrayList<>(Arrays.asList(ia)); System.out.println("Before shuffling: " + list1); Collections.shuffle(list1, rand); System.out.println("After shuffling: " + list1); diff --git a/holding/MultiIterableClass.java b/holding/MultiIterableClass.java index e3192695..8fe56c21 100644 --- a/holding/MultiIterableClass.java +++ b/holding/MultiIterableClass.java @@ -5,11 +5,15 @@ import java.util.*; public class MultiIterableClass extends IterableClass { public Iterable reversed() { return new Iterable() { + @Override public Iterator iterator() { return new Iterator() { int current = words.length - 1; + @Override public boolean hasNext() { return current > -1; } + @Override public String next() { return words[current--]; } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } @@ -19,9 +23,10 @@ public class MultiIterableClass extends IterableClass { } public Iterable randomized() { return new Iterable() { + @Override public Iterator iterator() { List shuffled = - new ArrayList(Arrays.asList(words)); + new ArrayList<>(Arrays.asList(words)); Collections.shuffle(shuffled, new Random(47)); return shuffled.iterator(); } diff --git a/holding/NonCollectionSequence.java b/holding/NonCollectionSequence.java index ed12bb7f..ec404894 100644 --- a/holding/NonCollectionSequence.java +++ b/holding/NonCollectionSequence.java @@ -10,10 +10,13 @@ public class NonCollectionSequence extends PetSequence { public Iterator iterator() { return new Iterator() { private int index = 0; + @Override public boolean hasNext() { return index < pets.length; } + @Override public Pet next() { return pets[index++]; } + @Override public void remove() { // Not implemented throw new UnsupportedOperationException(); } diff --git a/holding/PetMap.java b/holding/PetMap.java index 3806d34c..9ee13d71 100644 --- a/holding/PetMap.java +++ b/holding/PetMap.java @@ -5,7 +5,7 @@ import static net.mindview.util.Print.*; public class PetMap { public static void main(String[] args) { - Map petMap = new HashMap(); + Map petMap = new HashMap<>(); petMap.put("My Cat", new Cat("Molly")); petMap.put("My Dog", new Dog("Ginger")); petMap.put("My Hamster", new Hamster("Bosco")); @@ -16,7 +16,7 @@ public class PetMap { print(petMap.containsValue(dog)); } } /* Output: -{My Cat=Cat Molly, My Hamster=Hamster Bosco, My Dog=Dog Ginger} +{My Cat=Cat Molly, My Dog=Dog Ginger, My Hamster=Hamster Bosco} Dog Ginger true true diff --git a/holding/PrintingContainers.java b/holding/PrintingContainers.java index d77d94c1..1f5feb87 100644 --- a/holding/PrintingContainers.java +++ b/holding/PrintingContainers.java @@ -19,22 +19,22 @@ public class PrintingContainers { return map; } public static void main(String[] args) { - print(fill(new ArrayList())); - print(fill(new LinkedList())); - print(fill(new HashSet())); - print(fill(new TreeSet())); - print(fill(new LinkedHashSet())); - print(fill(new HashMap())); - print(fill(new TreeMap())); - print(fill(new LinkedHashMap())); + print(fill(new ArrayList<>())); + print(fill(new LinkedList<>())); + print(fill(new HashSet<>())); + print(fill(new TreeSet<>())); + print(fill(new LinkedHashSet<>())); + print(fill(new HashMap<>())); + print(fill(new TreeMap<>())); + print(fill(new LinkedHashMap<>())); } } /* Output: [rat, cat, dog, dog] [rat, cat, dog, dog] -[dog, cat, rat] +[cat, dog, rat] [cat, dog, rat] [rat, cat, dog] -{dog=Spot, cat=Rags, rat=Fuzzy} +{cat=Rags, dog=Spot, rat=Fuzzy} {cat=Rags, dog=Spot, rat=Fuzzy} {rat=Fuzzy, cat=Rags, dog=Spot} *///:~ diff --git a/holding/PriorityQueueDemo.java b/holding/PriorityQueueDemo.java index 79fe1a64..61906220 100644 --- a/holding/PriorityQueueDemo.java +++ b/holding/PriorityQueueDemo.java @@ -4,7 +4,7 @@ import java.util.*; public class PriorityQueueDemo { public static void main(String[] args) { PriorityQueue priorityQueue = - new PriorityQueue(); + new PriorityQueue<>(); Random rand = new Random(47); for(int i = 0; i < 10; i++) priorityQueue.offer(rand.nextInt(i + 10)); @@ -12,9 +12,9 @@ public class PriorityQueueDemo { List ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25); - priorityQueue = new PriorityQueue(ints); + priorityQueue = new PriorityQueue<>(ints); QueueDemo.printQ(priorityQueue); - priorityQueue = new PriorityQueue( + priorityQueue = new PriorityQueue<>( ints.size(), Collections.reverseOrder()); priorityQueue.addAll(ints); QueueDemo.printQ(priorityQueue); @@ -22,18 +22,18 @@ public class PriorityQueueDemo { String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION"; List strings = Arrays.asList(fact.split("")); PriorityQueue stringPQ = - new PriorityQueue(strings); + new PriorityQueue<>(strings); QueueDemo.printQ(stringPQ); - stringPQ = new PriorityQueue( + stringPQ = new PriorityQueue<>( strings.size(), Collections.reverseOrder()); stringPQ.addAll(strings); QueueDemo.printQ(stringPQ); - Set charSet = new HashSet(); + Set charSet = new HashSet<>(); for(char c : fact.toCharArray()) charSet.add(c); // Autoboxing PriorityQueue characterPQ = - new PriorityQueue(charSet); + new PriorityQueue<>(charSet); QueueDemo.printQ(characterPQ); } } /* Output: diff --git a/holding/QueueDemo.java b/holding/QueueDemo.java index e2937cd9..1995fdf6 100644 --- a/holding/QueueDemo.java +++ b/holding/QueueDemo.java @@ -9,12 +9,12 @@ public class QueueDemo { System.out.println(); } public static void main(String[] args) { - Queue queue = new LinkedList(); + Queue queue = new LinkedList<>(); Random rand = new Random(47); for(int i = 0; i < 10; i++) queue.offer(rand.nextInt(i + 10)); printQ(queue); - Queue qc = new LinkedList(); + Queue qc = new LinkedList<>(); for(char c : "Brontosaurus".toCharArray()) qc.offer(c); printQ(qc); diff --git a/holding/SetOfInteger.java b/holding/SetOfInteger.java index e650724c..c2e089f2 100644 --- a/holding/SetOfInteger.java +++ b/holding/SetOfInteger.java @@ -4,11 +4,11 @@ import java.util.*; public class SetOfInteger { public static void main(String[] args) { Random rand = new Random(47); - Set intset = new HashSet(); + Set intset = new HashSet<>(); for(int i = 0; i < 10000; i++) intset.add(rand.nextInt(30)); System.out.println(intset); } } /* Output: -[15, 8, 23, 16, 7, 22, 9, 21, 6, 1, 29, 14, 24, 4, 19, 26, 11, 18, 3, 12, 27, 17, 2, 13, 28, 20, 25, 10, 5, 0] +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28] *///:~ diff --git a/holding/SetOperations.java b/holding/SetOperations.java index ae591fd9..626dcb05 100644 --- a/holding/SetOperations.java +++ b/holding/SetOperations.java @@ -4,13 +4,13 @@ import static net.mindview.util.Print.*; public class SetOperations { public static void main(String[] args) { - Set set1 = new HashSet(); + Set set1 = new HashSet<>(); Collections.addAll(set1, "A B C D E F G H I J K L".split(" ")); set1.add("M"); print("H: " + set1.contains("H")); print("N: " + set1.contains("N")); - Set set2 = new HashSet(); + Set set2 = new HashSet<>(); Collections.addAll(set2, "H I J K L".split(" ")); print("set2 in set1: " + set1.containsAll(set2)); set1.remove("H"); @@ -25,8 +25,8 @@ public class SetOperations { H: true N: false set2 in set1: true -set1: [D, K, C, B, L, G, I, M, A, F, J, E] +set1: [D, E, F, G, A, B, C, L, M, I, J, K] set2 in set1: false -set2 removed from set1: [D, C, B, G, M, A, F, E] -'X Y Z' added to set1: [Z, D, C, B, G, M, A, F, Y, X, E] +set2 removed from set1: [D, E, F, G, A, B, C, M] +'X Y Z' added to set1: [D, E, F, G, A, B, C, M, Y, X, Z] *///:~ diff --git a/holding/SimpleCollection.java b/holding/SimpleCollection.java index bd0c9547..d4c11188 100644 --- a/holding/SimpleCollection.java +++ b/holding/SimpleCollection.java @@ -3,7 +3,7 @@ import java.util.*; public class SimpleCollection { public static void main(String[] args) { - Collection c = new ArrayList(); + Collection c = new ArrayList<>(); for(int i = 0; i < 10; i++) c.add(i); // Autoboxing for(Integer i : c) diff --git a/holding/SortedSetOfInteger.java b/holding/SortedSetOfInteger.java index 60d562f3..e7074855 100644 --- a/holding/SortedSetOfInteger.java +++ b/holding/SortedSetOfInteger.java @@ -4,7 +4,7 @@ import java.util.*; public class SortedSetOfInteger { public static void main(String[] args) { Random rand = new Random(47); - SortedSet intset = new TreeSet(); + SortedSet intset = new TreeSet<>(); for(int i = 0; i < 10000; i++) intset.add(rand.nextInt(30)); System.out.println(intset); diff --git a/holding/StackCollision.java b/holding/StackCollision.java index eea72799..f344b3a9 100644 --- a/holding/StackCollision.java +++ b/holding/StackCollision.java @@ -3,14 +3,14 @@ public class StackCollision { public static void main(String[] args) { net.mindview.util.Stack stack = - new net.mindview.util.Stack(); + new net.mindview.util.Stack<>(); for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.empty()) System.out.print(stack.pop() + " "); System.out.println(); java.util.Stack stack2 = - new java.util.Stack(); + new java.util.Stack<>(); for(String s : "My dog has fleas".split(" ")) stack2.push(s); while(!stack2.empty()) @@ -19,4 +19,4 @@ public class StackCollision { } /* Output: fleas has dog My fleas has dog My -*///:~ \ No newline at end of file +*///:~ diff --git a/holding/StackTest.java b/holding/StackTest.java index 7b00d04c..3c25446e 100644 --- a/holding/StackTest.java +++ b/holding/StackTest.java @@ -3,7 +3,7 @@ import net.mindview.util.*; public class StackTest { public static void main(String[] args) { - Stack stack = new Stack(); + Stack stack = new Stack<>(); for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.empty()) diff --git a/holding/Statistics.java b/holding/Statistics.java index 19b6d18c..134e9069 100644 --- a/holding/Statistics.java +++ b/holding/Statistics.java @@ -5,8 +5,7 @@ import java.util.*; public class Statistics { public static void main(String[] args) { Random rand = new Random(47); - Map m = - new HashMap(); + Map m = new HashMap<>(); for(int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: int r = rand.nextInt(20); @@ -16,5 +15,5 @@ public class Statistics { System.out.println(m); } } /* Output: -{15=497, 4=481, 19=464, 8=468, 11=531, 16=533, 18=478, 3=508, 7=471, 12=521, 17=509, 2=489, 13=506, 9=549, 6=519, 1=502, 14=477, 10=513, 5=503, 0=481} +{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, 7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506, 14=477, 15=497, 17=509, 16=533, 19=464, 18=478} *///:~ diff --git a/holding/UniqueWords.java b/holding/UniqueWords.java index 63182dec..295eaf06 100644 --- a/holding/UniqueWords.java +++ b/holding/UniqueWords.java @@ -4,7 +4,7 @@ import net.mindview.util.*; public class UniqueWords { public static void main(String[] args) { - Set words = new TreeSet( + Set words = new TreeSet<>( new TextFile("SetOperations.java", "\\W+")); System.out.println(words); } diff --git a/holding/UniqueWordsAlphabetic.java b/holding/UniqueWordsAlphabetic.java index de1a5c4f..57930166 100644 --- a/holding/UniqueWordsAlphabetic.java +++ b/holding/UniqueWordsAlphabetic.java @@ -6,7 +6,7 @@ import net.mindview.util.*; public class UniqueWordsAlphabetic { public static void main(String[] args) { Set words = - new TreeSet(String.CASE_INSENSITIVE_ORDER); + new TreeSet<>(String.CASE_INSENSITIVE_ORDER); words.addAll( new TextFile("SetOperations.java", "\\W+")); System.out.println(words); diff --git a/holding/build.xml b/holding/build.xml new file mode 100644 index 00000000..f5727e4a --- /dev/null +++ b/holding/build.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/initialization/TerminationCondition.java b/initialization/TerminationCondition.java index 7660e17c..4fa2935d 100644 --- a/initialization/TerminationCondition.java +++ b/initialization/TerminationCondition.java @@ -10,6 +10,7 @@ class Book { void checkIn() { checkedOut = false; } + @Override protected void finalize() { if(checkedOut) System.out.println("Error: checked out"); diff --git a/initialization/build.xml b/initialization/build.xml new file mode 100644 index 00000000..ff9eff1a --- /dev/null +++ b/initialization/build.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/innerclasses/AnonymousConstructor.java b/innerclasses/AnonymousConstructor.java index 1241a353..468fe63c 100644 --- a/innerclasses/AnonymousConstructor.java +++ b/innerclasses/AnonymousConstructor.java @@ -13,6 +13,7 @@ public class AnonymousConstructor { public static Base getBase(int i) { return new Base(i) { { print("Inside instance initializer"); } + @Override public void f() { print("In anonymous f()"); } diff --git a/innerclasses/BigEgg2.java b/innerclasses/BigEgg2.java index 0017732a..5bd84e1f 100644 --- a/innerclasses/BigEgg2.java +++ b/innerclasses/BigEgg2.java @@ -16,6 +16,7 @@ class Egg2 { public class BigEgg2 extends Egg2 { public class Yolk extends Egg2.Yolk { public Yolk() { print("BigEgg2.Yolk()"); } + @Override public void f() { print("BigEgg2.Yolk.f()"); } } public BigEgg2() { insertYolk(new Yolk()); } diff --git a/innerclasses/Callbacks.java b/innerclasses/Callbacks.java index b982cd5a..1e4dde72 100644 --- a/innerclasses/Callbacks.java +++ b/innerclasses/Callbacks.java @@ -10,6 +10,7 @@ interface Incrementable { // Very simple to just implement the interface: class Callee1 implements Incrementable { private int i = 0; + @Override public void increment() { i++; print(i); @@ -25,12 +26,14 @@ class MyIncrement { // some other way, you must use an inner class: class Callee2 extends MyIncrement { private int i = 0; + @Override public void increment() { super.increment(); i++; print(i); } private class Closure implements Incrementable { + @Override public void increment() { // Specify outer-class method, otherwise // you'd get an infinite recursion: diff --git a/innerclasses/ClassInInterface.java b/innerclasses/ClassInInterface.java index d3683e51..fb5f196b 100644 --- a/innerclasses/ClassInInterface.java +++ b/innerclasses/ClassInInterface.java @@ -4,6 +4,7 @@ public interface ClassInInterface { void howdy(); class Test implements ClassInInterface { + @Override public void howdy() { System.out.println("Howdy!"); } diff --git a/innerclasses/Games.java b/innerclasses/Games.java index 2fe5f1f7..50a43ed8 100644 --- a/innerclasses/Games.java +++ b/innerclasses/Games.java @@ -9,6 +9,7 @@ class Checkers implements Game { private Checkers() {} private int moves = 0; private static final int MOVES = 3; + @Override public boolean move() { print("Checkers move " + moves); return ++moves != MOVES; diff --git a/innerclasses/GreenhouseControls.java b/innerclasses/GreenhouseControls.java index 2d4d2d76..bd6f0ded 100644 --- a/innerclasses/GreenhouseControls.java +++ b/innerclasses/GreenhouseControls.java @@ -9,39 +9,47 @@ public class GreenhouseControls extends Controller { private boolean light = false; public class LightOn extends Event { public LightOn(long delayTime) { super(delayTime); } + @Override public void action() { // Put hardware control code here to // physically turn on the light. light = true; } + @Override public String toString() { return "Light is on"; } } public class LightOff extends Event { public LightOff(long delayTime) { super(delayTime); } + @Override public void action() { // Put hardware control code here to // physically turn off the light. light = false; } + @Override public String toString() { return "Light is off"; } } private boolean water = false; public class WaterOn extends Event { public WaterOn(long delayTime) { super(delayTime); } + @Override public void action() { // Put hardware control code here. water = true; } + @Override public String toString() { return "Greenhouse water is on"; } } public class WaterOff extends Event { public WaterOff(long delayTime) { super(delayTime); } + @Override public void action() { // Put hardware control code here. water = false; } + @Override public String toString() { return "Greenhouse water is off"; } @@ -51,10 +59,12 @@ public class GreenhouseControls extends Controller { public ThermostatNight(long delayTime) { super(delayTime); } + @Override public void action() { // Put hardware control code here. thermostat = "Night"; } + @Override public String toString() { return "Thermostat on night setting"; } @@ -63,10 +73,12 @@ public class GreenhouseControls extends Controller { public ThermostatDay(long delayTime) { super(delayTime); } + @Override public void action() { // Put hardware control code here. thermostat = "Day"; } + @Override public String toString() { return "Thermostat on day setting"; } @@ -75,9 +87,11 @@ public class GreenhouseControls extends Controller { // 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)); } + @Override public String toString() { return "Bing!"; } } public class Restart extends Event { @@ -88,6 +102,7 @@ public class GreenhouseControls extends Controller { for(Event e : eventList) addEvent(e); } + @Override public void action() { for(Event e : eventList) { e.start(); // Rerun each event @@ -96,13 +111,16 @@ public class GreenhouseControls extends Controller { start(); // Rerun this Event addEvent(this); } + @Override public String toString() { return "Restarting system"; } } public static class Terminate extends Event { public Terminate(long delayTime) { super(delayTime); } + @Override public void action() { System.exit(0); } + @Override public String toString() { return "Terminating"; } } } ///:~ diff --git a/innerclasses/LambdaExpressions.java b/innerclasses/LambdaExpressions.java new file mode 100644 index 00000000..272297c2 --- /dev/null +++ b/innerclasses/LambdaExpressions.java @@ -0,0 +1,15 @@ +//: innerclasses/LambdaExpressions.java + +interface Description { + String brief(); +} + +public class LambdaExpressions { + Description desc = new Description() { + @Override + public String brief() { + return "Short info"; + } + }; + Description desc2 = () -> "Short info"; +} ///:~ diff --git a/innerclasses/LocalInnerClass.java b/innerclasses/LocalInnerClass.java index 3234410c..da0852e2 100644 --- a/innerclasses/LocalInnerClass.java +++ b/innerclasses/LocalInnerClass.java @@ -15,6 +15,7 @@ public class LocalInnerClass { // Local inner class can have a constructor print("LocalCounter()"); } + @Override public int next() { printnb(name); // Access local final return count++; @@ -30,6 +31,7 @@ public class LocalInnerClass { { print("Counter()"); } + @Override public int next() { printnb(name); // Access local final return count++; diff --git a/innerclasses/Parcel10.java b/innerclasses/Parcel10.java index 05875d27..b2a48448 100644 --- a/innerclasses/Parcel10.java +++ b/innerclasses/Parcel10.java @@ -14,6 +14,7 @@ public class Parcel10 { System.out.println("Over budget!"); } private String label = dest; + @Override public String readLabel() { return label; } }; } diff --git a/innerclasses/Parcel11.java b/innerclasses/Parcel11.java index 30c4c286..0a2e990e 100644 --- a/innerclasses/Parcel11.java +++ b/innerclasses/Parcel11.java @@ -4,6 +4,7 @@ public class Parcel11 { private static class ParcelContents implements Contents { private int i = 11; + @Override public int value() { return i; } } protected static class ParcelDestination @@ -12,6 +13,7 @@ public class Parcel11 { private ParcelDestination(String whereTo) { label = whereTo; } + @Override public String readLabel() { return label; } // Nested classes can contain other static elements: public static void f() {} diff --git a/innerclasses/Parcel5.java b/innerclasses/Parcel5.java index 13a90b65..9f752841 100644 --- a/innerclasses/Parcel5.java +++ b/innerclasses/Parcel5.java @@ -8,6 +8,7 @@ public class Parcel5 { private PDestination(String whereTo) { label = whereTo; } + @Override public String readLabel() { return label; } } return new PDestination(s); diff --git a/innerclasses/Parcel7.java b/innerclasses/Parcel7.java index 8fe6690d..333dbd8c 100644 --- a/innerclasses/Parcel7.java +++ b/innerclasses/Parcel7.java @@ -5,6 +5,7 @@ public class Parcel7 { public Contents contents() { return new Contents() { // Insert a class definition private int i = 11; + @Override public int value() { return i; } }; // Semicolon required in this case } diff --git a/innerclasses/Parcel7b.java b/innerclasses/Parcel7b.java index 814fd651..43fe4dee 100644 --- a/innerclasses/Parcel7b.java +++ b/innerclasses/Parcel7b.java @@ -4,6 +4,7 @@ public class Parcel7b { class MyContents implements Contents { private int i = 11; + @Override public int value() { return i; } } public Contents contents() { return new MyContents(); } diff --git a/innerclasses/Parcel8.java b/innerclasses/Parcel8.java index 1176811e..01495648 100644 --- a/innerclasses/Parcel8.java +++ b/innerclasses/Parcel8.java @@ -5,6 +5,7 @@ public class Parcel8 { public Wrapping wrapping(int x) { // Base constructor call: return new Wrapping(x) { // Pass constructor argument. + @Override public int value() { return super.value() * 47; } diff --git a/innerclasses/Parcel9.java b/innerclasses/Parcel9.java index a3d59fa8..f7edb7a9 100644 --- a/innerclasses/Parcel9.java +++ b/innerclasses/Parcel9.java @@ -8,6 +8,7 @@ public class Parcel9 { public Destination destination(final String dest) { return new Destination() { private String label = dest; + @Override public String readLabel() { return label; } }; } diff --git a/innerclasses/Sequence.java b/innerclasses/Sequence.java index 12ccde09..de24a4dd 100644 --- a/innerclasses/Sequence.java +++ b/innerclasses/Sequence.java @@ -17,8 +17,11 @@ public class Sequence { } private class SequenceSelector implements Selector { private int i = 0; + @Override public boolean end() { return i == items.length; } + @Override public Object current() { return items[i]; } + @Override public void next() { if(i < items.length) i++; } } public Selector selector() { diff --git a/innerclasses/TestParcel.java b/innerclasses/TestParcel.java index e283d85e..7e55b2c6 100644 --- a/innerclasses/TestParcel.java +++ b/innerclasses/TestParcel.java @@ -3,6 +3,7 @@ class Parcel4 { private class PContents implements Contents { private int i = 11; + @Override public int value() { return i; } } protected class PDestination implements Destination { @@ -10,6 +11,7 @@ class Parcel4 { private PDestination(String whereTo) { label = whereTo; } + @Override public String readLabel() { return label; } } public Destination destination(String s) { diff --git a/innerclasses/build.xml b/innerclasses/build.xml new file mode 100644 index 00000000..80c13c02 --- /dev/null +++ b/innerclasses/build.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/innerclasses/controller/Controller.java b/innerclasses/controller/Controller.java index dff8f2dd..a4cb0a82 100644 --- a/innerclasses/controller/Controller.java +++ b/innerclasses/controller/Controller.java @@ -5,13 +5,13 @@ import java.util.*; public class Controller { // A class from java.util to hold Event objects: - private List eventList = new ArrayList(); + private List eventList = new ArrayList<>(); public void addEvent(Event c) { eventList.add(c); } public void run() { while(eventList.size() > 0) // Make a copy so you're not modifying the list // while you're selecting the elements in it: - for(Event e : new ArrayList(eventList)) + for(Event e : new ArrayList<>(eventList)) if(e.ready()) { System.out.println(e); e.action(); diff --git a/interfaces/AdaptedRandomDoubles.java b/interfaces/AdaptedRandomDoubles.java index faf07809..0e556de5 100644 --- a/interfaces/AdaptedRandomDoubles.java +++ b/interfaces/AdaptedRandomDoubles.java @@ -9,6 +9,7 @@ implements Readable { public AdaptedRandomDoubles(int count) { this.count = count; } + @Override public int read(CharBuffer cb) { if(count-- == 0) return -1; diff --git a/interfaces/Factories.java b/interfaces/Factories.java index 25e9f6f0..58743141 100644 --- a/interfaces/Factories.java +++ b/interfaces/Factories.java @@ -17,6 +17,7 @@ class Implementation1 implements Service { } class Implementation1Factory implements ServiceFactory { + @Override public Service getService() { return new Implementation1(); } @@ -29,6 +30,7 @@ class Implementation2 implements Service { } class Implementation2Factory implements ServiceFactory { + @Override public Service getService() { return new Implementation2(); } diff --git a/interfaces/Games.java b/interfaces/Games.java index 68d7c0eb..ab02f3e9 100644 --- a/interfaces/Games.java +++ b/interfaces/Games.java @@ -8,6 +8,7 @@ interface GameFactory { Game getGame(); } class Checkers implements Game { private int moves = 0; private static final int MOVES = 3; + @Override public boolean move() { print("Checkers move " + moves); return ++moves != MOVES; @@ -15,12 +16,14 @@ class Checkers implements Game { } class CheckersFactory implements GameFactory { + @Override public Game getGame() { return new Checkers(); } } class Chess implements Game { private int moves = 0; private static final int MOVES = 4; + @Override public boolean move() { print("Chess move " + moves); return ++moves != MOVES; @@ -28,6 +31,7 @@ class Chess implements Game { } class ChessFactory implements GameFactory { + @Override public Game getGame() { return new Chess(); } } diff --git a/interfaces/HorrorShow.java b/interfaces/HorrorShow.java index a3689a3a..574fd435 100644 --- a/interfaces/HorrorShow.java +++ b/interfaces/HorrorShow.java @@ -14,7 +14,9 @@ interface Lethal { } class DragonZilla implements DangerousMonster { + @Override public void menace() {} + @Override public void destroy() {} } @@ -23,9 +25,13 @@ interface Vampire extends DangerousMonster, Lethal { } class VeryBadVampire implements Vampire { + @Override public void menace() {} + @Override public void destroy() {} + @Override public void kill() {} + @Override public void drinkBlood() {} } diff --git a/interfaces/InterfaceCollision.java b/interfaces/InterfaceCollision.java index d9a9e1e0..3e6056d3 100644 --- a/interfaces/InterfaceCollision.java +++ b/interfaces/InterfaceCollision.java @@ -7,16 +7,20 @@ interface I3 { int f(); } class C { public int f() { return 1; } } class C2 implements I1, I2 { + @Override public void f() {} + @Override public int f(int i) { return 1; } // overloaded } class C3 extends C implements I2 { + @Override public int f(int i) { return 1; } // overloaded } class C4 extends C implements I3 { // Identical, no problem: + @Override public int f() { return 1; } } diff --git a/interfaces/RandomWords.java b/interfaces/RandomWords.java index 871839b3..6812dffb 100644 --- a/interfaces/RandomWords.java +++ b/interfaces/RandomWords.java @@ -13,6 +13,7 @@ public class RandomWords implements Readable { "aeiou".toCharArray(); private int count; public RandomWords(int count) { this.count = count; } + @Override public int read(CharBuffer cb) { if(count-- == 0) return -1; // Indicates end of input diff --git a/interfaces/build.xml b/interfaces/build.xml new file mode 100644 index 00000000..3fac2e35 --- /dev/null +++ b/interfaces/build.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interfaces/classprocessor/Apply.java b/interfaces/classprocessor/Apply.java index 0b6609eb..a9562ba3 100644 --- a/interfaces/classprocessor/Apply.java +++ b/interfaces/classprocessor/Apply.java @@ -11,18 +11,21 @@ class Processor { } class Upcase extends Processor { + @Override String process(Object input) { // Covariant return return ((String)input).toUpperCase(); } } class Downcase extends Processor { + @Override String process(Object input) { return ((String)input).toLowerCase(); } } class Splitter extends Processor { + @Override String process(Object input) { // The split() argument divides a String into pieces: return Arrays.toString(((String)input).split(" ")); diff --git a/interfaces/filters/BandPass.java b/interfaces/filters/BandPass.java index b949b1fa..e8b3645a 100644 --- a/interfaces/filters/BandPass.java +++ b/interfaces/filters/BandPass.java @@ -7,5 +7,6 @@ public class BandPass extends Filter { lowCutoff = lowCut; highCutoff = highCut; } + @Override public Waveform process(Waveform input) { return input; } } ///:~ diff --git a/interfaces/filters/HighPass.java b/interfaces/filters/HighPass.java index b4983ae6..6a878fb8 100644 --- a/interfaces/filters/HighPass.java +++ b/interfaces/filters/HighPass.java @@ -4,5 +4,6 @@ package interfaces.filters; public class HighPass extends Filter { double cutoff; public HighPass(double cutoff) { this.cutoff = cutoff; } + @Override public Waveform process(Waveform input) { return input; } } ///:~ diff --git a/interfaces/filters/LowPass.java b/interfaces/filters/LowPass.java index 00d671e2..8b039b95 100644 --- a/interfaces/filters/LowPass.java +++ b/interfaces/filters/LowPass.java @@ -4,6 +4,7 @@ package interfaces.filters; public class LowPass extends Filter { double cutoff; public LowPass(double cutoff) { this.cutoff = cutoff; } + @Override public Waveform process(Waveform input) { return input; // Dummy processing } diff --git a/interfaces/filters/Waveform.java b/interfaces/filters/Waveform.java index adccc4d2..3302c3c6 100644 --- a/interfaces/filters/Waveform.java +++ b/interfaces/filters/Waveform.java @@ -4,5 +4,6 @@ package interfaces.filters; public class Waveform { private static long counter; private final long id = counter++; + @Override public String toString() { return "Waveform " + id; } } ///:~ diff --git a/interfaces/interfaceprocessor/FilterProcessor.java b/interfaces/interfaceprocessor/FilterProcessor.java index a2b6dc5c..9ef68df9 100644 --- a/interfaces/interfaceprocessor/FilterProcessor.java +++ b/interfaces/interfaceprocessor/FilterProcessor.java @@ -7,7 +7,9 @@ class FilterAdapter implements Processor { public FilterAdapter(Filter filter) { this.filter = filter; } + @Override public String name() { return filter.name(); } + @Override public Waveform process(Object input) { return filter.process((Waveform)input); } diff --git a/interfaces/interfaceprocessor/StringProcessor.java b/interfaces/interfaceprocessor/StringProcessor.java index ff3ee085..4d2a5944 100644 --- a/interfaces/interfaceprocessor/StringProcessor.java +++ b/interfaces/interfaceprocessor/StringProcessor.java @@ -3,9 +3,11 @@ package interfaces.interfaceprocessor; import java.util.*; public abstract class StringProcessor implements Processor{ + @Override public String name() { return getClass().getSimpleName(); } + @Override public abstract String process(Object input); public static String s = "If she weighs the same as a duck, she's made of wood"; @@ -17,18 +19,21 @@ public abstract class StringProcessor implements Processor{ } class Upcase extends StringProcessor { + @Override public String process(Object input) { // Covariant return return ((String)input).toUpperCase(); } } class Downcase extends StringProcessor { + @Override public String process(Object input) { return ((String)input).toLowerCase(); } } class Splitter extends StringProcessor { + @Override public String process(Object input) { return Arrays.toString(((String)input).split(" ")); } diff --git a/interfaces/music4/Music4.java b/interfaces/music4/Music4.java index 08cec33b..1183b194 100644 --- a/interfaces/music4/Music4.java +++ b/interfaces/music4/Music4.java @@ -12,40 +12,53 @@ abstract class Instrument { } class Wind extends Instrument { + @Override public void play(Note n) { print("Wind.play() " + n); } + @Override public String what() { return "Wind"; } + @Override public void adjust() {} } class Percussion extends Instrument { + @Override public void play(Note n) { print("Percussion.play() " + n); } + @Override public String what() { return "Percussion"; } + @Override public void adjust() {} } class Stringed extends Instrument { + @Override public void play(Note n) { print("Stringed.play() " + n); } + @Override public String what() { return "Stringed"; } + @Override public void adjust() {} } class Brass extends Wind { + @Override public void play(Note n) { print("Brass.play() " + n); } + @Override public void adjust() { print("Brass.adjust()"); } } class Woodwind extends Wind { + @Override public void play(Note n) { print("Woodwind.play() " + n); } + @Override public String what() { return "Woodwind"; } } diff --git a/interfaces/music5/Music5.java b/interfaces/music5/Music5.java index 1d3d2d61..7828c88d 100644 --- a/interfaces/music5/Music5.java +++ b/interfaces/music5/Music5.java @@ -13,34 +13,45 @@ interface Instrument { } class Wind implements Instrument { + @Override public void play(Note n) { print(this + ".play() " + n); } + @Override public String toString() { return "Wind"; } + @Override public void adjust() { print(this + ".adjust()"); } } class Percussion implements Instrument { + @Override public void play(Note n) { print(this + ".play() " + n); } + @Override public String toString() { return "Percussion"; } + @Override public void adjust() { print(this + ".adjust()"); } } class Stringed implements Instrument { + @Override public void play(Note n) { print(this + ".play() " + n); } + @Override public String toString() { return "Stringed"; } + @Override public void adjust() { print(this + ".adjust()"); } } class Brass extends Wind { + @Override public String toString() { return "Brass"; } } class Woodwind extends Wind { + @Override public String toString() { return "Woodwind"; } } diff --git a/interfaces/nesting/NestingInterfaces.java b/interfaces/nesting/NestingInterfaces.java index 121a9c91..98a356a2 100644 --- a/interfaces/nesting/NestingInterfaces.java +++ b/interfaces/nesting/NestingInterfaces.java @@ -6,27 +6,33 @@ class A { void f(); } public class BImp implements B { + @Override public void f() {} } private class BImp2 implements B { + @Override public void f() {} } public interface C { void f(); } class CImp implements C { + @Override public void f() {} } private class CImp2 implements C { + @Override public void f() {} } private interface D { void f(); } private class DImp implements D { + @Override public void f() {} } public class DImp2 implements D { + @Override public void f() {} } public D getD() { return new DImp2(); } @@ -52,9 +58,11 @@ interface E { public class NestingInterfaces { public class BImp implements A.B { + @Override public void f() {} } class CImp implements A.C { + @Override public void f() {} } // Cannot implement a private interface except @@ -63,14 +71,18 @@ public class NestingInterfaces { //! public void f() {} //! } class EImp implements E { + @Override public void g() {} } class EGImp implements E.G { + @Override public void f() {} } class EImp2 implements E { + @Override public void g() {} class EG implements E.G { + @Override public void f() {} } } diff --git a/io/AStoreCADState.java b/io/AStoreCADState.java new file mode 100644 index 00000000..81e2cbbd --- /dev/null +++ b/io/AStoreCADState.java @@ -0,0 +1,106 @@ +//: io/AStoreCADState.java +// Saving the state of a pretend 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 int counter = 0; + public abstract void setColor(int newColor); + public abstract int getColor(); + public Shape(int xVal, int yVal, int dim) { + xPos = xVal; + yPos = yVal; + dimension = dim; + } + public String toString() { + return getClass() + + "color[" + getColor() + "] xPos[" + xPos + + "] yPos[" + yPos + "] dim[" + dimension + "]\n"; + } + public static Shape randomFactory() { + int xVal = rand.nextInt(100); + int yVal = rand.nextInt(100); + int dim = rand.nextInt(100); + switch(counter++ % 3) { + default: + case 0: return new Circle(xVal, yVal, dim); + case 1: return new Square(xVal, yVal, dim); + case 2: return new Line(xVal, yVal, dim); + } + } +} + +class Circle extends Shape { + private static int color = RED; + public Circle(int xVal, int yVal, int dim) { + super(xVal, yVal, dim); + } + public void setColor(int newColor) { color = newColor; } + public int getColor() { return color; } +} + +class Square extends Shape { + private static int color; + public Square(int xVal, int yVal, int dim) { + super(xVal, yVal, dim); + color = RED; + } + public void setColor(int newColor) { color = newColor; } + public int getColor() { return color; } +} + +class Line extends Shape { + private static int color = RED; + public static void + serializeStaticState(ObjectOutputStream os) + throws IOException { os.writeInt(color); } + public static void + deserializeStaticState(ObjectInputStream os) + throws IOException { color = os.readInt(); } + public Line(int xVal, int yVal, int dim) { + super(xVal, yVal, dim); + } + public void setColor(int newColor) { color = newColor; } + public int getColor() { return color; } +} + +public class AStoreCADState { + public static void main(String[] args) throws Exception { + List> shapeTypes = + new ArrayList<>(); + // Add references to the class objects: + shapeTypes.add(Circle.class); + shapeTypes.add(Square.class); + shapeTypes.add(Line.class); + List shapes = new ArrayList<>(); + // Make some shapes: + for(int i = 0; i < 10; i++) + shapes.add(Shape.randomFactory()); + // Set all the static colors to GREEN: + 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.out")); + out.writeObject(shapeTypes); + Line.serializeStaticState(out); + out.writeObject(shapes); + // Display the shapes: + System.out.println(shapes); + } +} /* Output: +[class Circlecolor[3] xPos[58] yPos[55] dim[93] +, class Squarecolor[3] xPos[61] yPos[61] dim[29] +, class Linecolor[3] xPos[68] yPos[0] dim[22] +, class Circlecolor[3] xPos[7] yPos[88] dim[28] +, class Squarecolor[3] xPos[51] yPos[89] dim[9] +, class Linecolor[3] xPos[78] yPos[98] dim[61] +, class Circlecolor[3] xPos[20] yPos[58] dim[16] +, class Squarecolor[3] xPos[40] yPos[11] dim[22] +, class Linecolor[3] xPos[4] yPos[83] dim[6] +, class Circlecolor[3] xPos[75] yPos[10] dim[42] +] +*///:~ diff --git a/io/AvailableCharSets.java b/io/AvailableCharSets.java index 23c564ff..4c9247b6 100644 --- a/io/AvailableCharSets.java +++ b/io/AvailableCharSets.java @@ -26,11 +26,11 @@ public class AvailableCharSets { } } /* Output: Big5: csBig5 -Big5-HKSCS: big5-hkscs, big5hk, big5-hkscs:unicode3.0, big5hkscs, Big5_HKSCS -EUC-JP: eucjis, x-eucjp, csEUCPkdFmtjapanese, eucjp, Extended_UNIX_Code_Packed_Format_for_Japanese, x-euc-jp, euc_jp -EUC-KR: ksc5601, 5601, ksc5601_1987, ksc_5601, ksc5601-1987, euc_kr, ks_c_5601-1987, euckr, csEUCKR +Big5-HKSCS: big5-hkscs:unicode3.0, Big5_HKSCS, big5-hkscs, big5hkscs, big5hk +EUC-JP: eucjis, Extended_UNIX_Code_Packed_Format_for_Japanese, x-eucjp, eucjp, csEUCPkdFmtjapanese, euc_jp, x-euc-jp +EUC-KR: 5601, ksc5601-1987, ksc5601_1987, euckr, ksc5601, ksc_5601, ks_c_5601-1987, euc_kr, csEUCKR GB18030: gb18030-2000 -GB2312: gb2312-1980, gb2312, EUC_CN, gb2312-80, euc-cn, euccn, x-EUC-CN -GBK: windows-936, CP936 +GB2312: euc-cn, x-EUC-CN, gb2312-1980, gb2312, gb2312-80, euccn, EUC_CN +GBK: CP936, windows-936 ... *///:~ diff --git a/io/Blip3.java b/io/Blip3.java index 9bf85de2..a84d4d04 100644 --- a/io/Blip3.java +++ b/io/Blip3.java @@ -16,7 +16,9 @@ public class Blip3 implements Externalizable { i = a; // s & i initialized only in non-default constructor. } + @Override public String toString() { return s + i; } + @Override public void writeExternal(ObjectOutput out) throws IOException { print("Blip3.writeExternal"); @@ -24,6 +26,7 @@ public class Blip3 implements Externalizable { out.writeObject(s); out.writeInt(i); } + @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { print("Blip3.readExternal"); diff --git a/io/Blips.java b/io/Blips.java index 848ce348..c83bcfcc 100644 --- a/io/Blips.java +++ b/io/Blips.java @@ -7,10 +7,12 @@ class Blip1 implements Externalizable { public Blip1() { print("Blip1 Constructor"); } + @Override public void writeExternal(ObjectOutput out) throws IOException { print("Blip1.writeExternal"); } + @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { print("Blip1.readExternal"); @@ -21,10 +23,12 @@ class Blip2 implements Externalizable { Blip2() { print("Blip2 Constructor"); } + @Override public void writeExternal(ObjectOutput out) throws IOException { print("Blip2.writeExternal"); } + @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { print("Blip2.readExternal"); diff --git a/io/DirList.java b/io/DirList.java index 1b69d2bd..2ccc559a 100644 --- a/io/DirList.java +++ b/io/DirList.java @@ -24,6 +24,7 @@ class DirFilter implements FilenameFilter { public DirFilter(String regex) { pattern = Pattern.compile(regex); } + @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } diff --git a/io/DirList2.java b/io/DirList2.java index 55b6de80..4af27fb5 100644 --- a/io/DirList2.java +++ b/io/DirList2.java @@ -10,6 +10,7 @@ public class DirList2 { // Creation of anonymous inner class: return new FilenameFilter() { private Pattern pattern = Pattern.compile(regex); + @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } diff --git a/io/DirList3.java b/io/DirList3.java index fbf0b705..cb504a41 100644 --- a/io/DirList3.java +++ b/io/DirList3.java @@ -14,6 +14,7 @@ public class DirList3 { else list = path.list(new FilenameFilter() { private Pattern pattern = Pattern.compile(args[0]); + @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } diff --git a/io/Echo.java b/io/Echo.java index d87db452..ead399fa 100644 --- a/io/Echo.java +++ b/io/Echo.java @@ -1,6 +1,6 @@ //: io/Echo.java // How to read from standard input. -// {RunByHand} +// {TimeOutDuringTesting} import java.io.*; public class Echo { diff --git a/io/FormattedMemoryInput.java b/io/FormattedMemoryInput.java index 5fddcb02..c30ba561 100644 --- a/io/FormattedMemoryInput.java +++ b/io/FormattedMemoryInput.java @@ -15,4 +15,4 @@ public class FormattedMemoryInput { System.err.println("End of stream"); } } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/io/GZIPcompress.java b/io/GZIPcompress.java index 711b8217..70d8b956 100644 --- a/io/GZIPcompress.java +++ b/io/GZIPcompress.java @@ -32,4 +32,4 @@ public class GZIPcompress { while((s = in2.readLine()) != null) System.out.println(s); } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/io/GetChannel.java b/io/GetChannel.java index 23e3ae85..727518af 100644 --- a/io/GetChannel.java +++ b/io/GetChannel.java @@ -28,4 +28,4 @@ public class GetChannel { } } /* Output: Some text Some more -*///:~ \ No newline at end of file +*///:~ diff --git a/io/LargeMappedFiles.java b/io/LargeMappedFiles.java index 88bfb610..277de180 100644 --- a/io/LargeMappedFiles.java +++ b/io/LargeMappedFiles.java @@ -1,6 +1,5 @@ //: io/LargeMappedFiles.java // Creating a very large file using mapping. -// {RunByHand} import java.nio.*; import java.nio.channels.*; import java.io.*; @@ -18,4 +17,4 @@ public class LargeMappedFiles { for(int i = length/2; i < length/2 + 6; i++) printnb((char)out.get(i)); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/io/LockingMappedFiles.java b/io/LockingMappedFiles.java index eb536f8d..8ef36170 100644 --- a/io/LockingMappedFiles.java +++ b/io/LockingMappedFiles.java @@ -1,6 +1,5 @@ //: io/LockingMappedFiles.java // Locking portions of a mapped file. -// {RunByHand} import java.nio.*; import java.nio.channels.*; import java.io.*; @@ -29,6 +28,7 @@ public class LockingMappedFiles { buff = mbb.slice(); start(); } + @Override public void run() { try { // Exclusive lock with no overlap: diff --git a/io/Logon.java b/io/Logon.java index 0c7b652f..a1cd9768 100644 --- a/io/Logon.java +++ b/io/Logon.java @@ -13,6 +13,7 @@ public class Logon implements Serializable { username = name; password = pwd; } + @Override public String toString() { return "logon info: \n username: " + username + "\n date: " + date + "\n password: " + password; diff --git a/io/MakeDirectories.java b/io/MakeDirectories.java index 5f5d440b..8251e3cf 100644 --- a/io/MakeDirectories.java +++ b/io/MakeDirectories.java @@ -78,4 +78,4 @@ Absolute path: d:\aaa-TIJ4\code\io\MakeDirectoriesTest length: 0 lastModified: 1101690308831 It's a directory -*///:~ \ No newline at end of file +*///:~ diff --git a/io/MappedIO.java b/io/MappedIO.java index 2848a99f..2e05a7c0 100644 --- a/io/MappedIO.java +++ b/io/MappedIO.java @@ -24,6 +24,7 @@ public class MappedIO { } private static Tester[] tests = { new Tester("Stream Write") { + @Override public void test() throws IOException { DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( @@ -34,6 +35,7 @@ public class MappedIO { } }, new Tester("Mapped Write") { + @Override public void test() throws IOException { FileChannel fc = new RandomAccessFile("temp.tmp", "rw") @@ -47,6 +49,7 @@ public class MappedIO { } }, new Tester("Stream Read") { + @Override public void test() throws IOException { DataInputStream dis = new DataInputStream( new BufferedInputStream( @@ -57,6 +60,7 @@ public class MappedIO { } }, new Tester("Mapped Read") { + @Override public void test() throws IOException { FileChannel fc = new FileInputStream( new File("temp.tmp")).getChannel(); @@ -69,6 +73,7 @@ public class MappedIO { } }, new Tester("Stream Read/Write") { + @Override public void test() throws IOException { RandomAccessFile raf = new RandomAccessFile( new File("temp.tmp"), "rw"); @@ -81,6 +86,7 @@ public class MappedIO { } }, new Tester("Mapped Read/Write") { + @Override public void test() throws IOException { FileChannel fc = new RandomAccessFile( new File("temp.tmp"), "rw").getChannel(); diff --git a/io/MyWorld.java b/io/MyWorld.java index 09c6db53..c4890302 100644 --- a/io/MyWorld.java +++ b/io/MyWorld.java @@ -12,6 +12,7 @@ class Animal implements Serializable { name = nm; preferredHouse = h; } + @Override public String toString() { return name + "[" + super.toString() + "], " + preferredHouse + "\n"; @@ -22,7 +23,7 @@ public class MyWorld { public static void main(String[] args) throws IOException, ClassNotFoundException { House house = new House(); - List animals = new ArrayList(); + 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)); diff --git a/io/RecoverCADState.java b/io/RecoverCADState.java index fa969eed..15a1dab9 100644 --- a/io/RecoverCADState.java +++ b/io/RecoverCADState.java @@ -28,4 +28,4 @@ public class RecoverCADState { , class Linecolor[3] xPos[4] yPos[83] dim[6] , class Circlecolor[1] xPos[75] yPos[10] dim[42] ] -*///:~ \ No newline at end of file +*///:~ diff --git a/io/SerialCtl.java b/io/SerialCtl.java index 8436ebff..9cf7430c 100644 --- a/io/SerialCtl.java +++ b/io/SerialCtl.java @@ -10,6 +10,7 @@ public class SerialCtl implements Serializable { a = "Not Transient: " + aa; b = "Transient: " + bb; } + @Override public String toString() { return a + "\n" + b; } private void writeObject(ObjectOutputStream stream) throws IOException { diff --git a/io/TestEOF.java b/io/TestEOF.java index c329dc37..c1612e9c 100644 --- a/io/TestEOF.java +++ b/io/TestEOF.java @@ -11,4 +11,4 @@ public class TestEOF { while(in.available() != 0) System.out.write(in.readByte()); } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/io/Worm.java b/io/Worm.java index 2e2177c6..89dfa260 100644 --- a/io/Worm.java +++ b/io/Worm.java @@ -7,6 +7,7 @@ import static net.mindview.util.Print.*; class Data implements Serializable { private int n; public Data(int n) { this.n = n; } + @Override public String toString() { return Integer.toString(n); } } @@ -29,6 +30,7 @@ public class Worm implements Serializable { public Worm() { print("Default constructor"); } + @Override public String toString() { StringBuilder result = new StringBuilder(":"); result.append(c); diff --git a/io/ZipCompress.java b/io/ZipCompress.java index 0ad6fbcb..3dd5d616 100644 --- a/io/ZipCompress.java +++ b/io/ZipCompress.java @@ -59,4 +59,4 @@ public class ZipCompress { } /* if(args.length == 1) */ } -} /* (Execute to see output) *///:~ \ No newline at end of file +} /* (Execute to see output) *///:~ diff --git a/io/build.xml b/io/build.xml new file mode 100644 index 00000000..baa0481e --- /dev/null +++ b/io/build.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/io/xfiles/ThawAlien.java b/io/xfiles/ThawAlien.java index e6471a18..a510654b 100644 --- a/io/xfiles/ThawAlien.java +++ b/io/xfiles/ThawAlien.java @@ -1,7 +1,7 @@ //: io/xfiles/ThawAlien.java // Try to recover a serialized file without the // class of object that's stored in that file. -// {RunByHand} +// {ThrowsException} import java.io.*; public class ThawAlien { @@ -11,6 +11,4 @@ public class ThawAlien { Object mystery = in.readObject(); System.out.println(mystery.getClass()); } -} /* Output: -class Alien -*///:~ +} ///:~ diff --git a/logging/ConfigureLogging.java b/logging/ConfigureLogging.java new file mode 100644 index 00000000..4b670cd5 --- /dev/null +++ b/logging/ConfigureLogging.java @@ -0,0 +1,36 @@ +//: logging/ConfigureLogging.java +// {JVMArgs: -Djava.util.logging.config.file=log.prop} +// {Clean: java0.log,java0.log.lck} +import java.util.logging.*; + +public class ConfigureLogging { + static Logger lgr = Logger.getLogger("com"), + lgr2 = Logger.getLogger("com.bruceeckel"), + util = Logger.getLogger("com.bruceeckel.util"), + test = Logger.getLogger("com.bruceeckel.test"), + rand = Logger.getLogger("random"); + public ConfigureLogging() { + /* Set Additional formatters, Filters and Handlers for + the loggers here. You cannot specify the Handlers + for loggers except the root logger from the + configuration file. */ + } + public static void main(String[] args) { + sendLogMessages(lgr); + sendLogMessages(lgr2); + sendLogMessages(util); + sendLogMessages(test); + sendLogMessages(rand); + } + private static void sendLogMessages(Logger logger) { + System.out.println(" Logger Name : " + + logger.getName() + " Level: " + logger.getLevel()); + logger.finest("Finest"); + logger.finer("Finer"); + logger.fine("Fine"); + logger.config("Config"); + logger.info("Info"); + logger.warning("Warning"); + logger.severe("Severe"); + } +} ///:~ diff --git a/logging/CustomHandler.java b/logging/CustomHandler.java new file mode 100644 index 00000000..7d43f5ac --- /dev/null +++ b/logging/CustomHandler.java @@ -0,0 +1,29 @@ +//: logging/CustomHandler.java +// How to write custom handler +import java.util.logging.*; +import java.util.*; + +public class CustomHandler { + private static Logger logger = + Logger.getLogger("CustomHandler"); + private static List strHolder = new ArrayList(); + public static void main(String[] args) { + logger.addHandler(new Handler() { + @Override + public void publish(LogRecord logRecord) { + strHolder.add(logRecord.getLevel() + ":"); + strHolder.add(logRecord.getSourceClassName()+":"); + strHolder.add(logRecord.getSourceMethodName()+":"); + strHolder.add("<" + logRecord.getMessage() + ">"); + strHolder.add("\n"); + } + @Override + public void flush() {} + @Override + public void close() {} + }); + logger.warning("Logging Warning"); + logger.info("Logging Info"); + System.out.print(strHolder); + } +} ///:~ diff --git a/logging/EmailLogger.java b/logging/EmailLogger.java new file mode 100644 index 00000000..3d09cade --- /dev/null +++ b/logging/EmailLogger.java @@ -0,0 +1,92 @@ +//: logging/EmailLogger.java +// {CompileTimeError} +// Must be connected to the Internet +// {Depends: mail.jar,activation.jar} +import java.util.logging.*; +import java.io.*; +import java.util.Properties; +import javax.mail.*; +import javax.mail.internet.*; + +public class EmailLogger { + private static Logger logger = + Logger.getLogger("EmailLogger"); + public static void main(String[] args) throws Exception { + logger.setUseParentHandlers(false); + Handler conHdlr = new ConsoleHandler(); + conHdlr.setFormatter(new Formatter() { + @Override + public String format(LogRecord record) { + return record.getLevel() + " : " + + record.getSourceClassName() + ":" + + record.getSourceMethodName() + ":" + + record.getMessage() + "\n"; + } + }); + logger.addHandler(conHdlr); + logger.addHandler( + new FileHandler("EmailLoggerOutput.xml")); + logger.addHandler(new MailingHandler()); + logger.log(Level.INFO, + "Testing Multiple Handlers", "SendMailTrue"); + } +} + +// A handler that sends mail messages +class MailingHandler extends Handler { + @Override + public void publish(LogRecord record) { + Object[] params = record.getParameters(); + if(params == null) return; + // Send mail only if the parameter is true + if(params[0].equals("SendMailTrue")) { + new MailInfo("bruce@theunixman.com", + new String[] { "bruce@theunixman.com" }, + "smtp.theunixman.com", "Test Subject", + "Test Content").sendMail(); + } + } + @Override + public void close() {} + @Override + public void flush() {} +} + +class MailInfo { + private String fromAddr; + private String[] toAddr; + private String serverAddr; + private String subject; + private String message; + public MailInfo(String from, String[] to, + String server, String subject, String message) { + fromAddr = from; + toAddr = to; + serverAddr = server; + this.subject = subject; + this.message = message; + } + public void sendMail() { + try { + Properties prop = new Properties(); + prop.put("mail.smtp.host", serverAddr); + Session session = + Session.getDefaultInstance(prop, null); + session.setDebug(true); + // Create a message + Message mimeMsg = new MimeMessage(session); + // Set the from and to address + Address addressFrom = new InternetAddress(fromAddr); + mimeMsg.setFrom(addressFrom); + Address[] to = new InternetAddress[toAddr.length]; + for(int i = 0; i < toAddr.length; i++) + to[i] = new InternetAddress(toAddr[i]); + mimeMsg.setRecipients(Message.RecipientType.TO,to); + mimeMsg.setSubject(subject); + mimeMsg.setText(message); + Transport.send(mimeMsg); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} ///:~ diff --git a/logging/InfoLogging.java b/logging/InfoLogging.java new file mode 100644 index 00000000..e062f964 --- /dev/null +++ b/logging/InfoLogging.java @@ -0,0 +1,11 @@ +//: logging/InfoLogging.java +import java.util.logging.*; +import java.io.*; + +public class InfoLogging { + private static Logger logger = + Logger.getLogger("InfoLogging"); + public static void main(String[] args) { + logger.info("Logging an INFO-level message"); + } +} ///:~ diff --git a/logging/InfoLogging2.java b/logging/InfoLogging2.java new file mode 100644 index 00000000..a20a6952 --- /dev/null +++ b/logging/InfoLogging2.java @@ -0,0 +1,13 @@ +//: logging/InfoLogging2.java +// Guaranteeing proper class and method names +import java.util.logging.*; +import java.io.*; + +public class InfoLogging2 { + private static Logger logger = + Logger.getLogger("InfoLogging2"); + public static void main(String[] args) { + logger.logp(Level.INFO, "InfoLogging2", "main", + "Logging an INFO-level message"); + } +} ///:~ diff --git a/logging/LogToFile.java b/logging/LogToFile.java new file mode 100644 index 00000000..5bdafc3d --- /dev/null +++ b/logging/LogToFile.java @@ -0,0 +1,12 @@ +//: logging/LogToFile.java +// {Clean: LogToFile.xml,LogToFile.xml.lck} +import java.util.logging.*; + +public class LogToFile { + private static Logger logger = + Logger.getLogger("LogToFile"); + public static void main(String[] args) throws Exception { + logger.addHandler(new FileHandler("LogToFile.xml")); + logger.info("A message logged to the file"); + } +} ///:~ diff --git a/logging/LogToFile2.java b/logging/LogToFile2.java new file mode 100644 index 00000000..1fef163a --- /dev/null +++ b/logging/LogToFile2.java @@ -0,0 +1,14 @@ +//: logging/LogToFile2.java +// {Clean: LogToFile2.txt,LogToFile2.txt.lck} +import java.util.logging.*; + +public class LogToFile2 { + private static Logger logger = + Logger.getLogger("LogToFile2"); + public static void main(String[] args) throws Exception { + FileHandler logFile= new FileHandler("LogToFile2.txt"); + logFile.setFormatter(new SimpleFormatter()); + logger.addHandler(logFile); + logger.info("A message logged to the file"); + } +} ///:~ diff --git a/logging/LoggingLevelManipulation.java b/logging/LoggingLevelManipulation.java new file mode 100644 index 00000000..8b5099e5 --- /dev/null +++ b/logging/LoggingLevelManipulation.java @@ -0,0 +1,56 @@ +//: logging/LoggingLevelManipulation.java +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.Handler; +import java.util.logging.LogManager; + +public class LoggingLevelManipulation { + private static Logger + lgr = Logger.getLogger("com"), + lgr2 = Logger.getLogger("com.bruceeckel"), + util = Logger.getLogger("com.bruceeckel.util"), + test = Logger.getLogger("com.bruceeckel.test"), + rand = Logger.getLogger("random"); + static void printLogMessages(Logger logger) { + logger.finest(logger.getName() + " Finest"); + logger.finer(logger.getName() + " Finer"); + logger.fine(logger.getName() + " Fine"); + logger.config(logger.getName() + " Config"); + logger.info(logger.getName() + " Info"); + logger.warning(logger.getName() + " Warning"); + logger.severe(logger.getName() + " Severe"); + } + static void logMessages() { + printLogMessages(lgr); + printLogMessages(lgr2); + printLogMessages(util); + printLogMessages(test); + printLogMessages(rand); + } + static void printLevels() { + System.out.println(" -- printing levels -- " + + lgr.getName() + " : " + lgr.getLevel() + + " " + lgr2.getName() + " : " + lgr2.getLevel() + + " " + util.getName() + " : " + util.getLevel() + + " " + test.getName() + " : " + test.getLevel() + + " " + rand.getName() + " : " + rand.getLevel()); + } + public static void main(String[] args) { + printLevels(); + lgr.setLevel(Level.SEVERE); + printLevels(); + System.out.println("com level: SEVERE"); + logMessages(); + util.setLevel(Level.FINEST); + test.setLevel(Level.FINEST); + rand.setLevel(Level.FINEST); + printLevels(); + System.out.println( + "individual loggers set to FINEST"); + logMessages(); + lgr.setLevel(Level.FINEST); + printLevels(); + System.out.println("com level: FINEST"); + logMessages(); + } +} ///:~ diff --git a/logging/LoggingLevels.java b/logging/LoggingLevels.java new file mode 100644 index 00000000..25edb735 --- /dev/null +++ b/logging/LoggingLevels.java @@ -0,0 +1,34 @@ +//: logging/LoggingLevels.java +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.Handler; +import java.util.logging.LogManager; + +public class LoggingLevels { + private static Logger + lgr = Logger.getLogger("com"), + lgr2 = Logger.getLogger("com.bruceeckel"), + util = Logger.getLogger("com.bruceeckel.util"), + test = Logger.getLogger("com.bruceeckel.test"), + rand = Logger.getLogger("random"); + private static void logMessages() { + lgr.info("com : info"); + lgr2.info("com.bruceeckel : info"); + util.info("util : info"); + test.severe("test : severe"); + rand.info("random : info"); + } + public static void main(String[] args) { + lgr.setLevel(Level.SEVERE); + System.out.println("com level: SEVERE"); + logMessages(); + util.setLevel(Level.FINEST); + test.setLevel(Level.FINEST); + rand.setLevel(Level.FINEST); + System.out.println("individual loggers set to FINEST"); + logMessages(); + lgr.setLevel(Level.SEVERE); + System.out.println("com level: SEVERE"); + logMessages(); + } +} ///:~ diff --git a/logging/MultipleHandlers.java b/logging/MultipleHandlers.java new file mode 100644 index 00000000..1f2cba70 --- /dev/null +++ b/logging/MultipleHandlers.java @@ -0,0 +1,15 @@ +//: logging/MultipleHandlers.java +// {Clean: MultipleHandlers.xml,MultipleHandlers.xml.lck} +import java.util.logging.*; + +public class MultipleHandlers { + private static Logger logger = + Logger.getLogger("MultipleHandlers"); + public static void main(String[] args) throws Exception { + FileHandler logFile = + new FileHandler("MultipleHandlers.xml"); + logger.addHandler(logFile); + logger.addHandler(new ConsoleHandler()); + logger.warning("Output to multiple handlers"); + } +} ///:~ diff --git a/logging/MultipleHandlers2.java b/logging/MultipleHandlers2.java new file mode 100644 index 00000000..fa7e7674 --- /dev/null +++ b/logging/MultipleHandlers2.java @@ -0,0 +1,16 @@ +//: logging/MultipleHandlers2.java +// {Clean: MultipleHandlers2.xml,MultipleHandlers2.xml.lck} +import java.util.logging.*; + +public class MultipleHandlers2 { + private static Logger logger = + Logger.getLogger("MultipleHandlers2"); + public static void main(String[] args) throws Exception { + FileHandler logFile = + new FileHandler("MultipleHandlers2.xml"); + logger.addHandler(logFile); + logger.addHandler(new ConsoleHandler()); + logger.setUseParentHandlers(false); + logger.warning("Output to multiple handlers"); + } +} ///:~ diff --git a/logging/PrintableLogRecord.java b/logging/PrintableLogRecord.java new file mode 100644 index 00000000..6d1a61d1 --- /dev/null +++ b/logging/PrintableLogRecord.java @@ -0,0 +1,38 @@ +//: logging/PrintableLogRecord.java +// Override LogRecord toString() +import java.util.ResourceBundle; +import java.util.logging.*; + +public class PrintableLogRecord extends LogRecord { + public PrintableLogRecord(Level level, String str) { + super(level, str); + } + @Override + public String toString() { + String result = "Level<" + getLevel() + ">\n" + + "LoggerName<" + getLoggerName() + ">\n" + + "Message<" + getMessage() + ">\n" + + "CurrentMillis<" + getMillis() + ">\n" + + "Params"; + Object[] objParams = getParameters(); + if(objParams == null) + result += "\n"; + else + for(int i = 0; i < objParams.length; i++) + result += " Param # <" + i + " value " + + objParams[i].toString() + ">\n"; + result += "ResourceBundle<" + getResourceBundle() + + ">\nResourceBundleName<" + getResourceBundleName() + + ">\nSequenceNumber<" + getSequenceNumber() + + ">\nSourceClassName<" + getSourceClassName() + + ">\nSourceMethodName<" + getSourceMethodName() + + ">\nThread Id<" + getThreadID() + + ">\nThrown<" + getThrown() + ">"; + return result; + } + public static void main(String[] args) { + PrintableLogRecord logRecord = new PrintableLogRecord( + Level.FINEST, "Simple Log Record"); + System.out.println(logRecord); + } +} ///:~ diff --git a/logging/SimpleFilter.java b/logging/SimpleFilter.java new file mode 100644 index 00000000..98ba6a90 --- /dev/null +++ b/logging/SimpleFilter.java @@ -0,0 +1,30 @@ +//: logging/SimpleFilter.java +import java.util.logging.*; + +public class SimpleFilter { + private static Logger logger = + Logger.getLogger("SimpleFilter"); + static class Duck {}; + static class Wombat {}; + static void sendLogMessages() { + logger.log(Level.WARNING, + "A duck in the house!", new Duck()); + logger.log(Level.WARNING, + "A Wombat at large!", new Wombat()); + } + public static void main(String[] args) { + sendLogMessages(); + logger.setFilter(new Filter() { + public boolean isLoggable(LogRecord record) { + Object[] params = record.getParameters(); + if(params == null) + return true; // No parameters + if(record.getParameters()[0] instanceof Duck) + return true; // Only log Ducks + return false; + } + }); + logger.info("After setting filter.."); + sendLogMessages(); + } +} ///:~ diff --git a/logging/SimpleFormatterExample.java b/logging/SimpleFormatterExample.java new file mode 100644 index 00000000..b621a7e9 --- /dev/null +++ b/logging/SimpleFormatterExample.java @@ -0,0 +1,27 @@ +//: logging/SimpleFormatterExample.java +// {CompileTimeError} +import java.util.logging.*; +import java.util.*; + +public class SimpleFormatterExample { + private static Logger logger = + Logger.getLogger("SimpleFormatterExample"); + private static void logMessages() { + logger.info("Line One"); + logger.info("Line Two"); + } + public static void main(String[] args) { + logger.setUseParentHandlers(false); + Handler conHdlr = new ConsoleHandler(); + conHdlr.setFormatter(new Formatter() { + public String format(LogRecord record) { + return record.getLevel() + " : " + + record.getSourceClassName() + " -:- " + + record.getSourceMethodName() + " -:- " + + record.getMessage() + "\n"; + } + }); + logger.addHandler(conHdlr); + logMessages(); + } +} ///:~ diff --git a/logging/build.xml b/logging/build.xml new file mode 100644 index 00000000..6aedb7c3 --- /dev/null +++ b/logging/build.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/logging/log.prop b/logging/log.prop new file mode 100644 index 00000000..7b4fae70 --- /dev/null +++ b/logging/log.prop @@ -0,0 +1,33 @@ +//: logging/log.prop +#### Configuration File #### +# Global Params +# Handlers installed for the root logger +handlers= java.util.logging.ConsoleHandler java.util.logging.FileHandler +# Level for root loggeris used by any logger +# that does not have its level set +.level= FINEST +# Initialization classthe public default constructor +# of this class is called by the Logging framework +config = ConfigureLogging + +# Configure FileHandler +# Logging file name - %u specifies unique +java.util.logging.FileHandler.pattern = java%g.log +# Write 100000 bytes before rotating this file +java.util.logging.FileHandler.limit = 100000 +# Number of rotating files to be used +java.util.logging.FileHandler.count = 3 +# Formatter to be used with this FileHandler +java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter + +# Configure ConsoleHandler +java.util.logging.ConsoleHandler.level = FINEST +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + +# Set Logger Levels # +com.level=SEVERE +com.bruceeckel.level = FINEST +com.bruceeckel.util.level = INFO +com.bruceeckel.test.level = FINER +random.level= SEVERE +///:~ diff --git a/net/build.xml b/net/build.xml new file mode 100644 index 00000000..5238217a --- /dev/null +++ b/net/build.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/net/mindview/atunit/AtUnit.java b/net/mindview/atunit/AtUnit.java index 43c85a67..7f24d98a 100644 --- a/net/mindview/atunit/AtUnit.java +++ b/net/mindview/atunit/AtUnit.java @@ -1,6 +1,5 @@ //: net/mindview/atunit/AtUnit.java // An annotation-based unit-test framework. -// {RunByHand} package net.mindview.atunit; import java.lang.reflect.*; import java.io.*; @@ -10,7 +9,7 @@ import static net.mindview.util.Print.*; public class AtUnit implements ProcessFiles.Strategy { static Class testClass; - static List failedTests= new ArrayList(); + static List failedTests= new ArrayList<>(); static long testsRun = 0; static long failures = 0; public static void main(String[] args) throws Exception { @@ -27,6 +26,7 @@ public class AtUnit implements ProcessFiles.Strategy { print(" " + failed); } } + @Override public void process(File cFile) { try { String cName = ClassNameFinder.thisClass( diff --git a/net/mindview/atunit/AtUnitRemover.java b/net/mindview/atunit/AtUnitRemover.java index 540fef49..187cf228 100644 --- a/net/mindview/atunit/AtUnitRemover.java +++ b/net/mindview/atunit/AtUnitRemover.java @@ -26,6 +26,7 @@ implements ProcessFiles.Strategy { new ProcessFiles( new AtUnitRemover(), "class").start(args); } + @Override public void process(File cFile) { boolean modified = false; try { @@ -61,4 +62,4 @@ implements ProcessFiles.Strategy { throw new RuntimeException(e); } } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/net/mindview/atunit/ClassNameFinder.java b/net/mindview/atunit/ClassNameFinder.java index 91588c44..9b7bed24 100644 --- a/net/mindview/atunit/ClassNameFinder.java +++ b/net/mindview/atunit/ClassNameFinder.java @@ -7,10 +7,8 @@ import static net.mindview.util.Print.*; public class ClassNameFinder { public static String thisClass(byte[] classBytes) { - Map offsetTable = - new HashMap(); - Map classNameTable = - new HashMap(); + Map offsetTable = new HashMap<>(); + Map classNameTable = new HashMap<>(); try { DataInputStream data = new DataInputStream( new ByteArrayInputStream(classBytes)); diff --git a/net/mindview/atunit/TestProperty.java b/net/mindview/atunit/TestProperty.java index 697b9072..aa521325 100644 --- a/net/mindview/atunit/TestProperty.java +++ b/net/mindview/atunit/TestProperty.java @@ -6,4 +6,4 @@ import java.lang.annotation.*; // Both fields and methods can be tagged as properties: @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) -public @interface TestProperty {} ///:~ \ No newline at end of file +public @interface TestProperty {} ///:~ diff --git a/net/mindview/util/BasicGenerator.java b/net/mindview/util/BasicGenerator.java index 7c588eb6..62ed83c9 100644 --- a/net/mindview/util/BasicGenerator.java +++ b/net/mindview/util/BasicGenerator.java @@ -6,6 +6,7 @@ package net.mindview.util; public class BasicGenerator implements Generator { private Class type; public BasicGenerator(Class type){ this.type = type; } + @Override public T next() { try { // Assumes type is a public class: @@ -16,6 +17,6 @@ public class BasicGenerator implements Generator { } // Produce a Default generator given a type token: public static Generator create(Class type) { - return new BasicGenerator(type); + return new BasicGenerator<>(type); } } ///:~ diff --git a/net/mindview/util/CollectionData.java b/net/mindview/util/CollectionData.java index 7c0542e3..6a580263 100644 --- a/net/mindview/util/CollectionData.java +++ b/net/mindview/util/CollectionData.java @@ -11,6 +11,6 @@ public class CollectionData extends ArrayList { // A generic convenience method: public static CollectionData list(Generator gen, int quantity) { - return new CollectionData(gen, quantity); + return new CollectionData<>(gen, quantity); } } ///:~ diff --git a/net/mindview/util/ContainerMethodDifferences.java b/net/mindview/util/ContainerMethodDifferences.java index 4798b9a5..eacb3ad5 100644 --- a/net/mindview/util/ContainerMethodDifferences.java +++ b/net/mindview/util/ContainerMethodDifferences.java @@ -5,7 +5,7 @@ import java.util.*; public class ContainerMethodDifferences { static Set methodSet(Class type) { - Set result = new TreeSet(); + Set result = new TreeSet<>(); for(Method m : type.getMethods()) result.add(m.getName()); return result; @@ -13,7 +13,7 @@ public class ContainerMethodDifferences { static void interfaces(Class type) { System.out.print("Interfaces in " + type.getSimpleName() + ": "); - List result = new ArrayList(); + List result = new ArrayList<>(); for(Class c : type.getInterfaces()) result.add(c.getSimpleName()); System.out.println(result); diff --git a/net/mindview/util/CountingGenerator.java b/net/mindview/util/CountingGenerator.java index fb3376a0..3655f200 100644 --- a/net/mindview/util/CountingGenerator.java +++ b/net/mindview/util/CountingGenerator.java @@ -6,6 +6,7 @@ public class CountingGenerator { public static class Boolean implements Generator { private boolean value = false; + @Override public java.lang.Boolean next() { value = !value; // Just flips back and forth return value; @@ -14,6 +15,7 @@ public class CountingGenerator { public static class Byte implements Generator { private byte value = 0; + @Override public java.lang.Byte next() { return value++; } } static char[] chars = ("abcdefghijklmnopqrstuvwxyz" + @@ -21,6 +23,7 @@ public class CountingGenerator { public static class Character implements Generator { int index = -1; + @Override public java.lang.Character next() { index = (index + 1) % chars.length; return chars[index]; @@ -32,6 +35,7 @@ public class CountingGenerator { Generator cg = new Character(); public String() {} public String(int length) { this.length = length; } + @Override public java.lang.String next() { char[] buf = new char[length]; for(int i = 0; i < length; i++) @@ -42,21 +46,25 @@ public class CountingGenerator { public static class Short implements Generator { private short value = 0; + @Override public java.lang.Short next() { return value++; } } public static class Integer implements Generator { private int value = 0; + @Override public java.lang.Integer next() { return value++; } } public static class Long implements Generator { private long value = 0; + @Override public java.lang.Long next() { return value++; } } public static class Float implements Generator { private float value = 0; + @Override public java.lang.Float next() { float result = value; value += 1.0; @@ -66,6 +74,7 @@ public class CountingGenerator { public static class Double implements Generator { private double value = 0.0; + @Override public java.lang.Double next() { double result = value; value += 1.0; diff --git a/net/mindview/util/CountingIntegerList.java b/net/mindview/util/CountingIntegerList.java index e6c97885..b26fefe6 100644 --- a/net/mindview/util/CountingIntegerList.java +++ b/net/mindview/util/CountingIntegerList.java @@ -9,9 +9,11 @@ extends AbstractList { public CountingIntegerList(int size) { this.size = size < 0 ? 0 : size; } + @Override public Integer get(int index) { - return Integer.valueOf(index); + return index; } + @Override public int size() { return size; } public static void main(String[] args) { System.out.println(new CountingIntegerList(30)); diff --git a/net/mindview/util/CountingMapData.java b/net/mindview/util/CountingMapData.java index 44ac914b..e2c0f501 100644 --- a/net/mindview/util/CountingMapData.java +++ b/net/mindview/util/CountingMapData.java @@ -17,26 +17,32 @@ extends AbstractMap { implements Map.Entry { int index; Entry(int index) { this.index = index; } + @Override public boolean equals(Object o) { return Integer.valueOf(index).equals(o); } + @Override public Integer getKey() { return index; } + @Override public String getValue() { return chars[index % chars.length] + Integer.toString(index / chars.length); } + @Override public String setValue(String value) { throw new UnsupportedOperationException(); } + @Override public int hashCode() { return Integer.valueOf(index).hashCode(); } } + @Override public Set> entrySet() { // LinkedHashSet retains initialization order: Set> entries = - new LinkedHashSet>(); + new LinkedHashSet<>(); for(int i = 0; i < size; i++) entries.add(new Entry(i)); return entries; @@ -46,4 +52,4 @@ extends AbstractMap { } } /* Output: {0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0, 10=K0, 11=L0, 12=M0, 13=N0, 14=O0, 15=P0, 16=Q0, 17=R0, 18=S0, 19=T0, 20=U0, 21=V0, 22=W0, 23=X0, 24=Y0, 25=Z0, 26=A1, 27=B1, 28=C1, 29=D1, 30=E1, 31=F1, 32=G1, 33=H1, 34=I1, 35=J1, 36=K1, 37=L1, 38=M1, 39=N1, 40=O1, 41=P1, 42=Q1, 43=R1, 44=S1, 45=T1, 46=U1, 47=V1, 48=W1, 49=X1, 50=Y1, 51=Z1, 52=A2, 53=B2, 54=C2, 55=D2, 56=E2, 57=F2, 58=G2, 59=H2} -*///:~ \ No newline at end of file +*///:~ diff --git a/net/mindview/util/Countries.java b/net/mindview/util/Countries.java index f0a96555..e367d00c 100644 --- a/net/mindview/util/Countries.java +++ b/net/mindview/util/Countries.java @@ -137,14 +137,19 @@ public class Countries { implements Map.Entry { int index; Entry(int index) { this.index = index; } + @Override public boolean equals(Object o) { return DATA[index][0].equals(o); } + @Override public String getKey() { return DATA[index][0]; } + @Override public String getValue() { return DATA[index][1]; } + @Override public String setValue(String value) { throw new UnsupportedOperationException(); } + @Override public int hashCode() { return DATA[index][0].hashCode(); } @@ -162,22 +167,27 @@ public class Countries { else this.size = size; } + @Override public int size() { return size; } private class Iter implements Iterator> { // Only one Entry object per Iterator: private Entry entry = new Entry(-1); + @Override public boolean hasNext() { return entry.index < size - 1; } + @Override public Map.Entry next() { entry.index++; return entry; } + @Override public void remove() { throw new UnsupportedOperationException(); } } + @Override public Iterator> iterator() { return new Iter(); @@ -185,6 +195,7 @@ public class Countries { } private static Set> entries = new EntrySet(DATA.length); + @Override public Set> entrySet() { return entries; } @@ -192,6 +203,7 @@ public class Countries { // Create a partial map of 'size' countries: static Map select(final int size) { return new FlyweightMap() { + @Override public Set> entrySet() { return new EntrySet(size); } @@ -205,38 +217,38 @@ public class Countries { return select(size); // A partial map } static List names = - new ArrayList(map.keySet()); + new ArrayList<>(map.keySet()); // All the names: public static List names() { return names; } // A partial list: public static List names(int size) { - return new ArrayList(select(size).keySet()); + return new ArrayList<>(select(size).keySet()); } public static void main(String[] args) { print(capitals(10)); print(names(10)); - print(new HashMap(capitals(3))); - print(new LinkedHashMap(capitals(3))); - print(new TreeMap(capitals(3))); - print(new Hashtable(capitals(3))); - print(new HashSet(names(6))); - print(new LinkedHashSet(names(6))); - print(new TreeSet(names(6))); - print(new ArrayList(names(6))); - print(new LinkedList(names(6))); + print(new HashMap<>(capitals(3))); + print(new LinkedHashMap<>(capitals(3))); + print(new TreeMap<>(capitals(3))); + print(new Hashtable<>(capitals(3))); + print(new HashSet<>(names(6))); + print(new LinkedHashSet<>(names(6))); + print(new TreeSet<>(names(6))); + print(new ArrayList<>(names(6))); + print(new LinkedList<>(names(6))); print(capitals().get("BRAZIL")); } } /* Output: -{ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo, BOTSWANA=Gaberone, BULGARIA=Sofia, BURKINA FASO=Ouagadougou, BURUNDI=Bujumbura, CAMEROON=Yaounde, CAPE VERDE=Praia, CENTRAL AFRICAN REPUBLIC=Bangui} -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC] -{BENIN=Porto-Novo, ANGOLA=Luanda, ALGERIA=Algiers} +{ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo, BOTSWANA=Gaberone, BURKINA FASO=Ouagadougou, BURUNDI=Bujumbura, CAMEROON=Yaounde, CAPE VERDE=Praia, CENTRAL AFRICAN REPUBLIC=Bangui, CHAD=N'djamena} +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, CHAD] +{ANGOLA=Luanda, ALGERIA=Algiers, BENIN=Porto-Novo} {ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo} {ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo} {ALGERIA=Algiers, ANGOLA=Luanda, BENIN=Porto-Novo} -[BULGARIA, BURKINA FASO, BOTSWANA, BENIN, ANGOLA, ALGERIA] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] -[ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO] +[ANGOLA, ALGERIA, BURKINA FASO, BENIN, BURUNDI, BOTSWANA] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] +[ALGERIA, ANGOLA, BENIN, BOTSWANA, BURKINA FASO, BURUNDI] Brasilia *///:~ diff --git a/net/mindview/util/DaemonThreadFactory.java b/net/mindview/util/DaemonThreadFactory.java index 635ee789..0eadd0f2 100644 --- a/net/mindview/util/DaemonThreadFactory.java +++ b/net/mindview/util/DaemonThreadFactory.java @@ -3,6 +3,7 @@ package net.mindview.util; import java.util.concurrent.*; public class DaemonThreadFactory implements ThreadFactory { + @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); diff --git a/net/mindview/util/DaemonThreadPoolExecutor.java b/net/mindview/util/DaemonThreadPoolExecutor.java index 03dec859..f436293a 100644 --- a/net/mindview/util/DaemonThreadPoolExecutor.java +++ b/net/mindview/util/DaemonThreadPoolExecutor.java @@ -6,7 +6,7 @@ public class DaemonThreadPoolExecutor extends ThreadPoolExecutor { public DaemonThreadPoolExecutor() { super(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, - new SynchronousQueue(), + new SynchronousQueue<>(), new DaemonThreadFactory()); } } ///:~ diff --git a/net/mindview/util/Deque.java b/net/mindview/util/Deque.java index 19739422..157a8ecd 100644 --- a/net/mindview/util/Deque.java +++ b/net/mindview/util/Deque.java @@ -4,7 +4,7 @@ package net.mindview.util; import java.util.*; public class Deque { - private LinkedList deque = new LinkedList(); + private LinkedList deque = new LinkedList<>(); public void addFirst(T e) { deque.addFirst(e); } public void addLast(T e) { deque.addLast(e); } public T getFirst() { return deque.getFirst(); } @@ -12,6 +12,7 @@ public class Deque { public T removeFirst() { return deque.removeFirst(); } public T removeLast() { return deque.removeLast(); } public int size() { return deque.size(); } + @Override public String toString() { return deque.toString(); } // And other methods as necessary... } ///:~ diff --git a/net/mindview/util/Directory.java b/net/mindview/util/Directory.java index 2139149d..6c68dc32 100644 --- a/net/mindview/util/Directory.java +++ b/net/mindview/util/Directory.java @@ -12,6 +12,7 @@ public final class Directory { local(File dir, final String regex) { return dir.listFiles(new FilenameFilter() { private Pattern pattern = Pattern.compile(regex); + @Override public boolean accept(File dir, String name) { return pattern.matcher( new File(name).getName()).matches(); @@ -24,9 +25,10 @@ public final class Directory { } // A two-tuple for returning a pair of objects: public static class TreeInfo implements Iterable { - public List files = new ArrayList(); - public List dirs = new ArrayList(); + public List files = new ArrayList<>(); + public List dirs = new ArrayList<>(); // The default iterable element is the file list: + @Override public Iterator iterator() { return files.iterator(); } @@ -34,6 +36,7 @@ public final class Directory { files.addAll(other.files); dirs.addAll(other.dirs); } + @Override public String toString() { return "dirs: " + PPrint.pformat(dirs) + "\n\nfiles: " + PPrint.pformat(files); diff --git a/net/mindview/util/FiveTuple.java b/net/mindview/util/FiveTuple.java index f2f3e39f..eef662d2 100644 --- a/net/mindview/util/FiveTuple.java +++ b/net/mindview/util/FiveTuple.java @@ -8,6 +8,7 @@ extends FourTuple { super(a, b, c, d); fifth = e; } + @Override public String toString() { return "(" + first + ", " + second + ", " + third + ", " + fourth + ", " + fifth + ")"; diff --git a/net/mindview/util/FourTuple.java b/net/mindview/util/FourTuple.java index 4eee0e97..69360952 100644 --- a/net/mindview/util/FourTuple.java +++ b/net/mindview/util/FourTuple.java @@ -7,6 +7,7 @@ public class FourTuple extends ThreeTuple { super(a, b, c); fourth = d; } + @Override public String toString() { return "(" + first + ", " + second + ", " + third + ", " + fourth + ")"; diff --git a/net/mindview/util/Generated.java b/net/mindview/util/Generated.java index 27706558..4fa3bc52 100644 --- a/net/mindview/util/Generated.java +++ b/net/mindview/util/Generated.java @@ -4,7 +4,7 @@ package net.mindview.util; public class Generated { // Fill an existing array: public static T[] array(T[] a, Generator gen) { - return new CollectionData(gen, a.length).toArray(a); + return new CollectionData<>(gen, a.length).toArray(a); } // Create a new array: @SuppressWarnings("unchecked") @@ -12,6 +12,6 @@ public class Generated { Generator gen, int size) { T[] a = (T[])java.lang.reflect.Array.newInstance(type, size); - return new CollectionData(gen, size).toArray(a); + return new CollectionData<>(gen, size).toArray(a); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/net/mindview/util/MapData.java b/net/mindview/util/MapData.java index 2d923a31..1b3c5788 100644 --- a/net/mindview/util/MapData.java +++ b/net/mindview/util/MapData.java @@ -39,22 +39,22 @@ public class MapData extends LinkedHashMap { // Generic convenience methods: public static MapData map(Generator> gen, int quantity) { - return new MapData(gen, quantity); + return new MapData<>(gen, quantity); } public static MapData map(Generator genK, Generator genV, int quantity) { - return new MapData(genK, genV, quantity); + return new MapData<>(genK, genV, quantity); } public static MapData map(Generator genK, V value, int quantity) { - return new MapData(genK, value, quantity); + return new MapData<>(genK, value, quantity); } public static MapData map(Iterable genK, Generator genV) { - return new MapData(genK, genV); + return new MapData<>(genK, genV); } public static MapData map(Iterable genK, V value) { - return new MapData(genK, value); + return new MapData<>(genK, value); } } ///:~ diff --git a/net/mindview/util/New.java b/net/mindview/util/New.java index 16ed4be0..ea9a78ca 100644 --- a/net/mindview/util/New.java +++ b/net/mindview/util/New.java @@ -6,19 +6,19 @@ import java.util.*; public class New { public static Map map() { - return new HashMap(); + return new HashMap<>(); } public static List list() { - return new ArrayList(); + return new ArrayList<>(); } public static LinkedList lList() { - return new LinkedList(); + return new LinkedList<>(); } public static Set set() { - return new HashSet(); + return new HashSet<>(); } public static Queue queue() { - return new LinkedList(); + return new LinkedList<>(); } // Examples: public static void main(String[] args) { diff --git a/net/mindview/util/PPrint.java b/net/mindview/util/PPrint.java index 535b81b8..a9297687 100644 --- a/net/mindview/util/PPrint.java +++ b/net/mindview/util/PPrint.java @@ -5,7 +5,7 @@ import java.util.*; public class PPrint { public static String pformat(Collection c) { - if(c.size() == 0) return "[]"; + if(c.isEmpty()) return "[]"; StringBuilder result = new StringBuilder("["); for(Object elem : c) { if(c.size() != 1) diff --git a/net/mindview/util/Print.java b/net/mindview/util/Print.java index 551ea87c..8738c864 100644 --- a/net/mindview/util/Print.java +++ b/net/mindview/util/Print.java @@ -1,6 +1,6 @@ //: net/mindview/util/Print.java // Print methods that can be used without -// qualifiers, using Java SE5 static imports: +// qualifiers, using Java 5 static imports: package net.mindview.util; import java.io.*; @@ -17,9 +17,9 @@ public class Print { public static void printnb(Object obj) { System.out.print(obj); } - // The Java SE5 printf() (from C): + // The Java 5 printf() (from C): public static PrintStream printf(String format, Object... args) { return System.out.printf(format, args); } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/net/mindview/util/ProcessFiles.java b/net/mindview/util/ProcessFiles.java index c32d30f1..cdb710d5 100644 --- a/net/mindview/util/ProcessFiles.java +++ b/net/mindview/util/ProcessFiles.java @@ -42,6 +42,7 @@ public class ProcessFiles { // Demonstration of how to use it: public static void main(String[] args) { new ProcessFiles(new ProcessFiles.Strategy() { + @Override public void process(File file) { System.out.println(file); } diff --git a/net/mindview/util/RandomGenerator.java b/net/mindview/util/RandomGenerator.java index 1aee91aa..4f1c62b1 100644 --- a/net/mindview/util/RandomGenerator.java +++ b/net/mindview/util/RandomGenerator.java @@ -7,18 +7,21 @@ public class RandomGenerator { private static Random r = new Random(47); public static class Boolean implements Generator { + @Override public java.lang.Boolean next() { return r.nextBoolean(); } } public static class Byte implements Generator { + @Override public java.lang.Byte next() { return (byte)r.nextInt(); } } public static class Character implements Generator { + @Override public java.lang.Character next() { return CountingGenerator.chars[ r.nextInt(CountingGenerator.chars.length)]; @@ -33,6 +36,7 @@ public class RandomGenerator { } public static class Short implements Generator { + @Override public java.lang.Short next() { return (short)r.nextInt(); } @@ -42,6 +46,7 @@ public class RandomGenerator { private int mod = 10000; public Integer() {} public Integer(int modulo) { mod = modulo; } + @Override public java.lang.Integer next() { return r.nextInt(mod); } @@ -51,12 +56,14 @@ public class RandomGenerator { private int mod = 10000; public Long() {} public Long(int modulo) { mod = modulo; } + @Override public java.lang.Long next() { return new java.lang.Long(r.nextInt(mod)); } } public static class Float implements Generator { + @Override public java.lang.Float next() { // Trim all but the first two decimal places: int trimmed = Math.round(r.nextFloat() * 100); @@ -65,6 +72,7 @@ public class RandomGenerator { } public static class Double implements Generator { + @Override public java.lang.Double next() { long trimmed = Math.round(r.nextDouble() * 100); return ((double)trimmed) / 100; diff --git a/net/mindview/util/Range.java b/net/mindview/util/Range.java index 6cc55555..1b1279b3 100644 --- a/net/mindview/util/Range.java +++ b/net/mindview/util/Range.java @@ -1,6 +1,6 @@ //: net/mindview/util/Range.java // Array creation methods that can be used without -// qualifiers, using Java SE5 static imports: +// qualifiers, using Java 5 static imports: package net.mindview.util; public class Range { diff --git a/net/mindview/util/Sets.java b/net/mindview/util/Sets.java index d04afc1b..adcfe6fd 100644 --- a/net/mindview/util/Sets.java +++ b/net/mindview/util/Sets.java @@ -4,20 +4,20 @@ import java.util.*; public class Sets { public static Set union(Set a, Set b) { - Set result = new HashSet(a); + Set result = new HashSet<>(a); result.addAll(b); return result; } public static Set intersection(Set a, Set b) { - Set result = new HashSet(a); + Set result = new HashSet<>(a); result.retainAll(b); return result; } // Subtract subset from superset: public static Set difference(Set superset, Set subset) { - Set result = new HashSet(superset); + Set result = new HashSet<>(superset); result.removeAll(subset); return result; } diff --git a/net/mindview/util/Stack.java b/net/mindview/util/Stack.java index 97f622e0..79ab36f8 100644 --- a/net/mindview/util/Stack.java +++ b/net/mindview/util/Stack.java @@ -4,10 +4,11 @@ package net.mindview.util; import java.util.LinkedList; public class Stack { - private LinkedList storage = new LinkedList(); + private LinkedList storage = new LinkedList<>(); 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(); } + @Override public String toString() { return storage.toString(); } } ///:~ diff --git a/net/mindview/util/SwingConsole.java b/net/mindview/util/SwingConsole.java index 279e0131..c1733e7e 100644 --- a/net/mindview/util/SwingConsole.java +++ b/net/mindview/util/SwingConsole.java @@ -8,6 +8,7 @@ public class SwingConsole { public static void run(final JFrame f, final int width, final int height) { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { f.setTitle(f.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); diff --git a/net/mindview/util/TaskManager.java b/net/mindview/util/TaskManager.java index a923b545..2d5cd8e5 100644 --- a/net/mindview/util/TaskManager.java +++ b/net/mindview/util/TaskManager.java @@ -9,11 +9,11 @@ extends ArrayList> { private ExecutorService exec = Executors.newSingleThreadExecutor(); public void add(C task) { - add(new TaskItem(exec.submit(task),task)); + add(new TaskItem<>(exec.submit(task),task)); } public List getResults() { Iterator> items = iterator(); - List results = new ArrayList(); + List results = new ArrayList<>(); while(items.hasNext()) { TaskItem item = items.next(); if(item.future.isDone()) { @@ -29,7 +29,7 @@ extends ArrayList> { } public List purge() { Iterator> items = iterator(); - List results = new ArrayList(); + List results = new ArrayList<>(); while(items.hasNext()) { TaskItem item = items.next(); // Leave completed tasks for results reporting: @@ -41,4 +41,4 @@ extends ArrayList> { } return results; } -} ///:~ \ No newline at end of file +} ///:~ diff --git a/net/mindview/util/TextFile.java b/net/mindview/util/TextFile.java index eaaf9bd1..2a25e199 100644 --- a/net/mindview/util/TextFile.java +++ b/net/mindview/util/TextFile.java @@ -72,7 +72,7 @@ public class TextFile extends ArrayList { TextFile text = new TextFile("test.txt"); text.write("test2.txt"); // Break into unique sorted list of words: - TreeSet words = new TreeSet( + TreeSet words = new TreeSet<>( new TextFile("TextFile.java", "\\W+")); // Display the capitalized words: System.out.println(words.headSet("a")); diff --git a/net/mindview/util/ThreeTuple.java b/net/mindview/util/ThreeTuple.java index aed60a0d..33e713c0 100644 --- a/net/mindview/util/ThreeTuple.java +++ b/net/mindview/util/ThreeTuple.java @@ -7,6 +7,7 @@ public class ThreeTuple extends TwoTuple { super(a, b); third = c; } + @Override public String toString() { return "(" + first + ", " + second + ", " + third +")"; } diff --git a/net/mindview/util/Tuple.java b/net/mindview/util/Tuple.java index 8fe2c8f1..d0fe5069 100644 --- a/net/mindview/util/Tuple.java +++ b/net/mindview/util/Tuple.java @@ -4,18 +4,18 @@ package net.mindview.util; public class Tuple { public static TwoTuple tuple(A a, B b) { - return new TwoTuple(a, b); + return new TwoTuple<>(a, b); } public static ThreeTuple tuple(A a, B b, C c) { - return new ThreeTuple(a, b, c); + return new ThreeTuple<>(a, b, c); } public static FourTuple tuple(A a, B b, C c, D d) { - return new FourTuple(a, b, c, d); + return new FourTuple<>(a, b, c, d); } public static FiveTuple tuple(A a, B b, C c, D d, E e) { - return new FiveTuple(a, b, c, d, e); + return new FiveTuple<>(a, b, c, d, e); } } ///:~ diff --git a/net/mindview/util/TwoTuple.java b/net/mindview/util/TwoTuple.java index 02e6f7d6..9da50c96 100644 --- a/net/mindview/util/TwoTuple.java +++ b/net/mindview/util/TwoTuple.java @@ -5,6 +5,7 @@ public class TwoTuple { public final A first; public final B second; public TwoTuple(A a, B b) { first = a; second = b; } + @Override public String toString() { return "(" + first + ", " + second + ")"; } diff --git a/net/mindview/util/TypeCounter.java b/net/mindview/util/TypeCounter.java index b2cfe5ba..410afc3a 100644 --- a/net/mindview/util/TypeCounter.java +++ b/net/mindview/util/TypeCounter.java @@ -24,6 +24,7 @@ public class TypeCounter extends HashMap,Integer>{ baseType.isAssignableFrom(superClass)) countClass(superClass); } + @Override public String toString() { StringBuilder result = new StringBuilder("{"); for(Map.Entry,Integer> pair : entrySet()) { diff --git a/network/ChatterClient.java b/network/ChatterClient.java new file mode 100644 index 00000000..047b923b --- /dev/null +++ b/network/ChatterClient.java @@ -0,0 +1,64 @@ +//: network/ChatterClient.java +// {TimeOutDuringTesting} +// Tests the ChatterServer by starting multiple +// clients, each of which sends datagrams. +import java.lang.Thread; +import java.net.*; +import java.io.*; + +public class ChatterClient extends Thread { + // Can listen & send on the same socket: + private DatagramSocket s; + private InetAddress hostAddress; + private byte[] buf = new byte[1000]; + private DatagramPacket dp = + new DatagramPacket(buf, buf.length); + private int id; + + public ChatterClient(int identifier) { + id = identifier; + try { + // Auto-assign port number: + s = new DatagramSocket(); + hostAddress = + InetAddress.getByName("localhost"); + } catch(UnknownHostException e) { + System.err.println("Cannot find host"); + System.exit(1); + } catch(SocketException e) { + System.err.println("Can't open socket"); + e.printStackTrace(); + System.exit(1); + } + System.out.println("ChatterClient starting"); + } + @Override + public void run() { + try { + for(int i = 0; i < 25; i++) { + String outMessage = "Client #" + + id + ", message #" + i; + // Make and send a datagram: + s.send(Dgram.toDatagram(outMessage, + hostAddress, + ChatterServer.INPORT)); + // Block until it echoes back: + s.receive(dp); + // Print out the echoed contents: + String rcvd = "Client #" + id + + ", rcvd from " + + dp.getAddress() + ", " + + dp.getPort() + ": " + + Dgram.toString(dp); + System.out.println(rcvd); + } + } catch(IOException e) { + e.printStackTrace(); + System.exit(1); + } + } + public static void main(String[] args) { + for(int i = 0; i < 10; i++) + new ChatterClient(i).start(); + } +} ///:~ diff --git a/network/ChatterServer.java b/network/ChatterServer.java new file mode 100644 index 00000000..38993354 --- /dev/null +++ b/network/ChatterServer.java @@ -0,0 +1,48 @@ +//: network/ChatterServer.java +// {TimeOutDuringTesting} +// A server that echoes datagrams +import java.net.*; +import java.io.*; +import java.util.*; + +public class ChatterServer { + static final int INPORT = 1711; + private byte[] buf = new byte[1000]; + private DatagramPacket dp = + new DatagramPacket(buf, buf.length); + // Can listen & send on the same socket: + private DatagramSocket socket; + + public ChatterServer() { + try { + socket = new DatagramSocket(INPORT); + System.out.println("Server started"); + while(true) { + // Block until a datagram appears: + socket.receive(dp); + String rcvd = Dgram.toString(dp) + + ", from address: " + dp.getAddress() + + ", port: " + dp.getPort(); + System.out.println(rcvd); + String echoString = + "Echoed: " + rcvd; + // Extract the address and port from the + // received datagram to find out where to + // send it back: + DatagramPacket echo = + Dgram.toDatagram(echoString, + dp.getAddress(), dp.getPort()); + socket.send(echo); + } + } catch(SocketException e) { + System.err.println("Can't open socket"); + System.exit(1); + } catch(IOException e) { + System.err.println("Communication error"); + e.printStackTrace(); + } + } + public static void main(String[] args) { + new ChatterServer(); + } +} ///:~ diff --git a/network/Dgram.java b/network/Dgram.java new file mode 100644 index 00000000..30cdba7e --- /dev/null +++ b/network/Dgram.java @@ -0,0 +1,26 @@ +//: network/Dgram.java +// A utility class to convert back and forth +// Between Strings and DataGramPackets. +import java.net.*; + +public class Dgram { + public static DatagramPacket toDatagram( + String s, InetAddress destIA, int destPort) { + // Deprecated in Java 1.1, but it works: + byte[] buf = new byte[s.length() + 1]; + s.getBytes(0, s.length(), buf, 0); + // The correct Java 1.1 approach, but it's + // Broken (it truncates the String): + // byte[] buf = s.getBytes(); + return new DatagramPacket(buf, buf.length, + destIA, destPort); + } + public static String toString(DatagramPacket p){ + // The Java 1.0 approach: + // return new String(p.getData(), + // 0, 0, p.getLength()); + // The Java 1.1 approach: + return + new String(p.getData(), 0, p.getLength()); + } +} ///:~ diff --git a/network/MultiSimpleClient.java b/network/MultiSimpleClient.java new file mode 100644 index 00000000..3328decf --- /dev/null +++ b/network/MultiSimpleClient.java @@ -0,0 +1,85 @@ +//: network/MultiSimpleClient.java +// Client that tests the MultiSimpleServer +// by starting up multiple clients. +// {ThrowsException} (When run standalone, +// during testing). +import java.net.*; +import java.io.*; + +class SimpleClientThread extends Thread { + private Socket socket; + private BufferedReader in; + private PrintWriter out; + private static int counter = 0; + private int id = counter++; + private static int threadcount = 0; + public static int threadCount() { + return threadcount; + } + public SimpleClientThread(InetAddress addr) { + System.out.println("Making client " + id); + threadcount++; + try { + socket = + new Socket(addr, MultiSimpleServer.PORT); + } catch(IOException e) { + // If the creation of the socket fails, + // nothing needs to be cleaned up. + } + try { + in = + new BufferedReader( + new InputStreamReader( + socket.getInputStream())); + // Enable auto-flush: + out = + new PrintWriter( + new BufferedWriter( + new OutputStreamWriter( + socket.getOutputStream())), true); + start(); + } catch(IOException e) { + // The socket should be closed on any + // failures other than the socket + // constructor: + try { + socket.close(); + } catch(IOException e2) {} + } + // Otherwise the socket will be closed by + // the run() method of the thread. + } + @Override + public void run() { + try { + for(int i = 0; i < 25; i++) { + out.println("Client " + id + ": " + i); + String str = in.readLine(); + System.out.println(str); + } + out.println("END"); + } catch(IOException e) { + } finally { + // Always close it: + try { + socket.close(); + } catch(IOException e) {} + threadcount--; // Ending this thread + } + } +} + +public class MultiSimpleClient { + static final int MAX_THREADS = 40; + public static void main(String[] args) + throws IOException, InterruptedException { + InetAddress addr = + InetAddress.getByName(null); + while(true) { + if(SimpleClientThread.threadCount() + < MAX_THREADS) + new SimpleClientThread(addr); + Thread.currentThread().sleep(100); + } + } +} ///:~ diff --git a/network/MultiSimpleServer.java b/network/MultiSimpleServer.java new file mode 100644 index 00000000..2445119b --- /dev/null +++ b/network/MultiSimpleServer.java @@ -0,0 +1,72 @@ +//: network/MultiSimpleServer.java +// A server that uses multithreading to handle +// any number of clients. +// {TimeOutDuringTesting} +import java.io.*; +import java.net.*; + +class ServeOneSimple extends Thread { + private Socket socket; + private BufferedReader in; + private PrintWriter out; + public ServeOneSimple(Socket s) + throws IOException { + socket = s; + in = + new BufferedReader( + new InputStreamReader( + socket.getInputStream())); + // Enable auto-flush: + out = + new PrintWriter( + new BufferedWriter( + new OutputStreamWriter( + socket.getOutputStream())), true); + // If any of the above calls throw an + // exception, the caller is responsible for + // closing the socket. Otherwise the thread + // will close it. + start(); // Calls run() + } + @Override + public void run() { + try { + while (true) { + String str = in.readLine(); + if (str.equals("END")) break; + System.out.println("Echoing: " + str); + out.println(str); + } + System.out.println("closing..."); + } catch (IOException e) { + } finally { + try { + socket.close(); + } catch(IOException e) {} + } + } +} + +public class MultiSimpleServer { + static final int PORT = 8080; + public static void main(String[] args) + throws IOException { + ServerSocket s = new ServerSocket(PORT); + System.out.println("Server Started"); + try { + while(true) { + // Blocks until a connection occurs: + Socket socket = s.accept(); + try { + new ServeOneSimple(socket); + } catch(IOException e) { + // If it fails, close the socket, + // otherwise the thread will close it: + socket.close(); + } + } + } finally { + s.close(); + } + } +} ///:~ diff --git a/network/SimpleClient.java b/network/SimpleClient.java new file mode 100644 index 00000000..a8d32826 --- /dev/null +++ b/network/SimpleClient.java @@ -0,0 +1,53 @@ +//: network/SimpleClient.java +// Very simple client that just sends +// lines to the server and reads lines +// that the server sends. +// {ThrowsException} (When run standalone, +// during testing). +import java.net.*; +import java.io.*; + +public class SimpleClient { + 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: + InetAddress addr = + InetAddress.getByName(null); + // Alternatively, you can use + // the address or name: + // InetAddress addr = + // InetAddress.getByName("127.0.0.1"); + // InetAddress addr = + // InetAddress.getByName("localhost"); + System.out.println("addr = " + addr); + Socket socket = + new Socket(addr, SimpleServer.PORT); + // Guard everything in a try-finally to make + // sure that the socket is closed: + try { + System.out.println("socket = " + socket); + BufferedReader in = + new BufferedReader( + new InputStreamReader( + socket.getInputStream())); + // Output is automatically flushed + // by PrintWriter: + PrintWriter out = + new PrintWriter( + new BufferedWriter( + new OutputStreamWriter( + socket.getOutputStream())),true); + for(int i = 0; i < 10; i ++) { + out.println("howdy " + i); + String str = in.readLine(); + System.out.println(str); + } + out.println("END"); + } finally { + System.out.println("closing..."); + socket.close(); + } + } +} ///:~ diff --git a/network/SimpleServer.java b/network/SimpleServer.java new file mode 100644 index 00000000..0992ef69 --- /dev/null +++ b/network/SimpleServer.java @@ -0,0 +1,47 @@ +//: network/SimpleServer.java +// Very simple server that just +// echoes whatever the client sends. +// {TimeOutDuringTesting} +import java.io.*; +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 { + ServerSocket s = new ServerSocket(PORT); + System.out.println("Started: " + s); + try { + // Blocks until a connection occurs: + Socket socket = s.accept(); + try { + System.out.println( + "Connection accepted: "+ socket); + BufferedReader in = + new BufferedReader( + new InputStreamReader( + socket.getInputStream())); + // Output is automatically flushed + // by PrintWriter: + PrintWriter out = + new PrintWriter( + new BufferedWriter( + new OutputStreamWriter( + socket.getOutputStream())),true); + while (true) { + String str = in.readLine(); + if (str.equals("END")) break; + System.out.println("Echoing: " + str); + out.println(str); + } + // Always close the two sockets... + } finally { + System.out.println("closing..."); + socket.close(); + } + } finally { + s.close(); + } + } +} ///:~ diff --git a/network/WhoAmI.java b/network/WhoAmI.java new file mode 100644 index 00000000..fe0cb701 --- /dev/null +++ b/network/WhoAmI.java @@ -0,0 +1,19 @@ +//: network/WhoAmI.java +// Finds out your network address when you're +// connected to the Internet. +// {Args:MindviewToshibaLaptop} +import java.net.*; + +public class WhoAmI { + public static void main(String[] args) + throws Exception { + if(args.length != 1) { + System.err.println( + "Usage: WhoAmI MachineName"); + System.exit(1); + } + InetAddress a = + InetAddress.getByName(args[0]); + System.out.println(a); + } +} ///:~ diff --git a/network/build.xml b/network/build.xml new file mode 100644 index 00000000..a44233d7 --- /dev/null +++ b/network/build.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/object/build.xml b/object/build.xml new file mode 100644 index 00000000..36fa8182 --- /dev/null +++ b/object/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/operators/PassObject.java b/operators/PassObject.java index 8e7f9130..ef8b5ad3 100644 --- a/operators/PassObject.java +++ b/operators/PassObject.java @@ -21,4 +21,4 @@ public class PassObject { } /* Output: 1: x.c: a 2: x.c: z -*///:~ \ No newline at end of file +*///:~ diff --git a/operators/build.xml b/operators/build.xml new file mode 100644 index 00000000..6156ba50 --- /dev/null +++ b/operators/build.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/patterns/CommandPattern.java b/patterns/CommandPattern.java new file mode 100644 index 00000000..b832e0c8 --- /dev/null +++ b/patterns/CommandPattern.java @@ -0,0 +1,49 @@ +//: patterns/CommandPattern.java +import java.util.*; + +interface Command { + void execute(); +} + +class Hello implements Command { + @Override + public void execute() { + System.out.print("Hello "); + } +} + +class World implements Command { + @Override + public void execute() { + System.out.print("World! "); + } +} + +class IAm implements Command { + @Override + public void execute() { + System.out.print("I'm the command pattern!"); + } +} + +// A Command object that holds commands: +class Macro implements Command { + private ArrayList commands = new ArrayList(); + public void add(Command c) { commands.add(c); } + @Override + public void execute() { + Iterator it = commands.iterator(); + while(it.hasNext()) + ((Command)it.next()).execute(); + } +} + +public class CommandPattern { + public static void main(String args[]) { + Macro macro = new Macro(); + macro.add(new Hello()); + macro.add(new World()); + macro.add(new IAm()); + macro.execute(); + } +} ///:~ diff --git a/patterns/Facade.java b/patterns/Facade.java new file mode 100644 index 00000000..eb8a9101 --- /dev/null +++ b/patterns/Facade.java @@ -0,0 +1,21 @@ +//: patterns/Facade.java + +class A { public A(int x) {} } +class B { public B(long x) {} } +class C { public C(double x) {} } + +// Other classes that aren't exposed by the +// facade go here ... + +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[]) { + // The client programmer gets the objects + // by calling the static methods: + A a = Facade.makeA(1); + B b = Facade.makeB(1); + C c = Facade.makeC(1.0); + } +} ///:~ diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java new file mode 100644 index 00000000..ce9d2b1d --- /dev/null +++ b/patterns/PaperScissorsRock.java @@ -0,0 +1,131 @@ +//: patterns/PaperScissorsRock.java +// Demonstration of multiple dispatching. +import java.util.*; + +// An enumeration type: +class Outcome { + private int value; + private Outcome(int val) { value = val; } + public final static Outcome + WIN = new Outcome(0), + LOSE = new Outcome(1), + DRAW = new Outcome(2); + @Override + public String toString() { + switch(value) { + default: + case 0: return "win"; + case 1: return "lose"; + case 2: return "draw"; + } + } + @Override + public boolean equals(Object o) { + return (o instanceof Outcome) + && (value == ((Outcome)o).value); + } +} + +interface Item { + Outcome compete(Item it); + Outcome eval(Paper p); + Outcome eval(Scissors s); + Outcome eval(Rock r); +} + +class Paper implements Item { + @Override + public Outcome compete(Item it) { + return it.eval(this); + } + @Override + public Outcome eval(Paper p) { + return Outcome.DRAW; + } + @Override + public Outcome eval(Scissors s) { + return Outcome.WIN; + } + @Override + public Outcome eval(Rock r) { + return Outcome.LOSE; + } + @Override + public String toString() { return "Paper"; } +} + +class Scissors implements Item { + @Override + public Outcome compete(Item it) { + return it.eval(this); + } + @Override + public Outcome eval(Paper p) { + return Outcome.LOSE; + } + @Override + public Outcome eval(Scissors s) { + return Outcome.DRAW; + } + @Override + public Outcome eval(Rock r) { + return Outcome.WIN; + } + @Override + public String toString() { return "Scissors"; } +} + +class Rock implements Item { + @Override + public Outcome compete(Item it) { + return it.eval(this); + } + @Override + public Outcome eval(Paper p) { + return Outcome.WIN; + } + @Override + public Outcome eval(Scissors s) { + return Outcome.LOSE; + } + @Override + public Outcome eval(Rock r) { + return Outcome.DRAW; + } + @Override + public String toString() { return "Rock"; } +} + +class ItemFactory { + public static Item newItem() { + switch((int)(Math.random() * 3)) { + default: + case 0: + return new Scissors(); + case 1: + return new Paper(); + case 2: + return new Rock(); + } + } +} + +class Compete { + public static Outcome match(Item a, Item b) { + System.out.print(a + " <--> " + b + " : "); + return a.compete(b); + } +} + +public class PaperScissorsRock { + public static void main(String args[]) { + ArrayList items = new ArrayList(); + for(int i = 0; i < 40; i++) + items.add(ItemFactory.newItem()); + for(int i = 0; i < items.size()/2; i++) + System.out.println( + Compete.match( + (Item)items.get(i), + (Item)items.get(i*2))); + } +} ///:~ diff --git a/patterns/ProxyDemo.java b/patterns/ProxyDemo.java new file mode 100644 index 00000000..11106462 --- /dev/null +++ b/patterns/ProxyDemo.java @@ -0,0 +1,43 @@ +//: patterns/ProxyDemo.java +// Simple demonstration of the Proxy pattern. + +interface ProxyBase { + void f(); + void g(); + void h(); +} + +class Proxy implements ProxyBase { + private ProxyBase implementation; + public Proxy() { + implementation = new Implementation(); + } + // Pass method calls to the implementation: + @Override + public void f() { implementation.f(); } + @Override + public void g() { implementation.g(); } + @Override + public void h() { implementation.h(); } +} + +class Implementation implements ProxyBase { + public void f() { + System.out.println("Implementation.f()"); + } + public void g() { + System.out.println("Implementation.g()"); + } + public void h() { + System.out.println("Implementation.h()"); + } +} + +public class ProxyDemo { + public static void main(String args[]) { + Proxy p = new Proxy(); + p.f(); + p.g(); + p.h(); + } +} ///:~ diff --git a/patterns/ShapeFactory2.java b/patterns/ShapeFactory2.java new file mode 100644 index 00000000..d60e8794 --- /dev/null +++ b/patterns/ShapeFactory2.java @@ -0,0 +1,96 @@ +//: patterns/ShapeFactory2.java +// Polymorphic factory methods. +import java.util.*; + +class BadShapeCreation extends Exception { + BadShapeCreation(String msg) { + super(msg); + } +} + +interface Shape { + void draw(); + void erase(); +} + +abstract class ShapeFactory { + protected abstract Shape create(); + static Map factories = new HashMap(); + static Shape createShape(String id) + throws BadShapeCreation { + if(!factories.containsKey(id)) { + try { + Class.forName(id); // Load dynamically + } catch(ClassNotFoundException e) { + throw new BadShapeCreation(id); + } + // See if it was put in: + if(!factories.containsKey(id)) + throw new BadShapeCreation(id); + } + return + ((ShapeFactory)factories.get(id)).create(); + } +} + +class Circle implements Shape { + private Circle() {} + public void draw() { + System.out.println("Circle.draw"); + } + public void erase() { + System.out.println("Circle.erase"); + } + static class Factory extends ShapeFactory { + @Override + protected Shape create() { + return new Circle(); + } + } + static { + ShapeFactory.factories.put( + "Circle", new Circle.Factory()); + } +} + +class Square implements Shape { + private Square() {} + public void draw() { + System.out.println("Square.draw"); + } + public void erase() { + System.out.println("Square.erase"); + } + static class Factory extends ShapeFactory { + @Override + protected Shape create() { + return new Square(); + } + } + static { + ShapeFactory.factories.put( + "Square", new Square.Factory()); + } +} + +public class ShapeFactory2 { + public static void main(String args[]) { + String shlist[] = { "Circle", "Square", + "Square", "Circle", "Circle", "Square" }; + ArrayList shapes = new ArrayList(); + try { + for(int i = 0; i < shlist.length; i++) + shapes.add( + ShapeFactory.createShape(shlist[i])); + } catch(BadShapeCreation e) { + e.printStackTrace(); + return; + } + Iterator i = shapes.iterator(); + while(i.hasNext()) { + Shape s = (Shape)i.next(); + s.draw(); + s.erase(); + } + } +} ///:~ diff --git a/patterns/SingletonPattern.java b/patterns/SingletonPattern.java new file mode 100644 index 00000000..341cfc48 --- /dev/null +++ b/patterns/SingletonPattern.java @@ -0,0 +1,32 @@ +//: patterns/SingletonPattern.java +// The Singleton design pattern: you can +// never instantiate more than one. +// Since this isn't inherited from a Cloneable +// base class and cloneability isn't added, +// making it final prevents cloneability from +// being added through inheritance: + +final class Singleton { + private static Singleton s = new Singleton(47); + private int i; + private Singleton(int x) { i = x; } + public static Singleton getHandle() { + return s; + } + public int getValue() { return i; } + public void setValue(int x) { i = x; } +} + +public class SingletonPattern { + public static void main(String[] args) { + Singleton s = Singleton.getHandle(); + System.out.println(s.getValue()); + Singleton s2 = Singleton.getHandle(); + s2.setValue(9); + System.out.println(s.getValue()); + try { + // Can't do this: compile-time error. + // Singleton s3 = (Singleton)s2.clone(); + } catch(Exception e) {} + } +} ///:~ diff --git a/patterns/StateDemo.java b/patterns/StateDemo.java new file mode 100644 index 00000000..ac763b7f --- /dev/null +++ b/patterns/StateDemo.java @@ -0,0 +1,76 @@ +//: patterns/StateDemo.java +// Simple demonstration of the State pattern. + +interface StateBase { + void f(); + void g(); + void h(); + void changeImp(StateBase newImp); +} + +class State implements StateBase { + private StateBase implementation; + public State(StateBase imp) { + implementation = imp; + } + @Override + public void changeImp(StateBase newImp) { + implementation = newImp; + } + // Pass method calls to the implementation: + @Override + public void f() { implementation.f(); } + @Override + public void g() { implementation.g(); } + @Override + public void h() { implementation.h(); } +} + +class Implementation1 implements StateBase { + @Override + public void f() { + System.out.println("Implementation1.f()"); + } + @Override + public void g() { + System.out.println("Implementation1.g()"); + } + @Override + public void h() { + System.out.println("Implementation1.h()"); + } + @Override + public void changeImp(StateBase newImp) {} +} + +class Implementation2 implements StateBase { + @Override + public void f() { + System.out.println("Implementation2.f()"); + } + @Override + public void g() { + System.out.println("Implementation2.g()"); + } + @Override + public void h() { + System.out.println("Implementation2.h()"); + } + @Override + public void changeImp(StateBase newImp) {} +} + +public class StateDemo { + static void test(StateBase b) { + b.f(); + b.g(); + b.h(); + } + public static void main(String args[]) { + StateBase b = + new State(new Implementation1()); + test(b); + b.changeImp(new Implementation2()); + test(b); + } +} ///:~ diff --git a/patterns/TemplateMethod.java b/patterns/TemplateMethod.java new file mode 100644 index 00000000..3d9e3f85 --- /dev/null +++ b/patterns/TemplateMethod.java @@ -0,0 +1,35 @@ +//: patterns/TemplateMethod.java +// Simple demonstration of Template Method. + +abstract class ApplicationFramework { + public ApplicationFramework() { + templateMethod(); + } + abstract void customize1(); + abstract void customize2(); + // "private" means automatically "final": + private void templateMethod() { + for(int i = 0; i < 5; i++) { + customize1(); + customize2(); + } + } +} + +// Create a new "application": +class MyApp extends ApplicationFramework { + @Override + void customize1() { + System.out.print("Hello "); + } + @Override + void customize2() { + System.out.println("World!"); + } +} + +public class TemplateMethod { + public static void main(String args[]) { + new MyApp(); + } +} ///:~ diff --git a/patterns/absfactory/GameEnvironment.java b/patterns/absfactory/GameEnvironment.java new file mode 100644 index 00000000..676ff336 --- /dev/null +++ b/patterns/absfactory/GameEnvironment.java @@ -0,0 +1,97 @@ +//: patterns/absfactory/GameEnvironment.java +// An example of the Abstract Factory pattern. +package patterns.absfactory; + +interface Obstacle { + void action(); +} + +interface Player { + void interactWith(Obstacle o); +} + +class Kitty implements Player { + @Override + public void interactWith(Obstacle ob) { + System.out.print("Kitty has encountered a "); + ob.action(); + } +} + +class KungFuGuy implements Player { + @Override + public void interactWith(Obstacle ob) { + System.out.print("KungFuGuy now battles a "); + ob.action(); + } +} + +class Puzzle implements Obstacle { + @Override + public void action() { + System.out.println("Puzzle"); + } +} + +class NastyWeapon implements Obstacle { + @Override + public void action() { + System.out.println("NastyWeapon"); + } +} + +// The Abstract Factory: +interface GameElementFactory { + Player makePlayer(); + Obstacle makeObstacle(); +} + +// Concrete factories: +class KittiesAndPuzzles +implements GameElementFactory { + @Override + public Player makePlayer() { + return new Kitty(); + } + @Override + public Obstacle makeObstacle() { + return new Puzzle(); + } +} + +class KillAndDismember +implements GameElementFactory { + @Override + public Player makePlayer() { + return new KungFuGuy(); + } + @Override + public Obstacle makeObstacle() { + return new NastyWeapon(); + } +} + +public class GameEnvironment { + private GameElementFactory gef; + private Player p; + private Obstacle ob; + public GameEnvironment( + GameElementFactory factory) { + gef = factory; + p = factory.makePlayer(); + ob = factory.makeObstacle(); + } + public void play() { + p.interactWith(ob); + } + public static void main(String args[]) { + GameElementFactory + kp = new KittiesAndPuzzles(), + kd = new KillAndDismember(); + GameEnvironment + g1 = new GameEnvironment(kp), + g2 = new GameEnvironment(kd); + g1.play(); + g2.play(); + } +} ///:~ diff --git a/patterns/adapt/Adapter.java b/patterns/adapt/Adapter.java new file mode 100644 index 00000000..47959ca6 --- /dev/null +++ b/patterns/adapt/Adapter.java @@ -0,0 +1,81 @@ +//: patterns/adapt/Adapter.java +// Variations on the Adapter pattern. +package patterns.adapt; + +class WhatIHave { + public void g() {} + public void h() {} +} + +interface WhatIWant { + void f(); +} + +class ProxyAdapter implements WhatIWant { + WhatIHave whatIHave; + public ProxyAdapter(WhatIHave wih) { + whatIHave = wih; + } + @Override + public void f() { + // Implement behavior using + // methods in WhatIHave: + whatIHave.g(); + whatIHave.h(); + } +} + +class WhatIUse { + public void op(WhatIWant wiw) { + wiw.f(); + } +} + +// Approach 2: build adapter use into op(): +class WhatIUse2 extends WhatIUse { + public void op(WhatIHave wih) { + new ProxyAdapter(wih).f(); + } +} + +// Approach 3: build adapter into WhatIHave: +class WhatIHave2 extends WhatIHave +implements WhatIWant { + @Override + public void f() { + g(); + h(); + } +} + +// Approach 4: use an inner class: +class WhatIHave3 extends WhatIHave { + private class InnerAdapter implements WhatIWant{ + @Override + public void f() { + g(); + h(); + } + } + public WhatIWant whatIWant() { + return new InnerAdapter(); + } +} + +public class Adapter { + public static void main(String args[]) { + WhatIUse whatIUse = new WhatIUse(); + WhatIHave whatIHave = new WhatIHave(); + WhatIWant adapt= new ProxyAdapter(whatIHave); + whatIUse.op(adapt); + // Approach 2: + WhatIUse2 whatIUse2 = new WhatIUse2(); + whatIUse2.op(whatIHave); + // Approach 3: + WhatIHave2 whatIHave2 = new WhatIHave2(); + whatIUse.op(whatIHave2); + // Approach 4: + WhatIHave3 whatIHave3 = new WhatIHave3(); + whatIUse.op(whatIHave3.whatIWant()); + } +} ///:~ diff --git a/patterns/build.xml b/patterns/build.xml new file mode 100644 index 00000000..276d40d6 --- /dev/null +++ b/patterns/build.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/patterns/chain/ChainOfResponsibility.java b/patterns/chain/ChainOfResponsibility.java new file mode 100644 index 00000000..19a9aa72 --- /dev/null +++ b/patterns/chain/ChainOfResponsibility.java @@ -0,0 +1,87 @@ +//: patterns/chain/ChainOfResponsibility.java +package patterns.chain; + +class FindMinima { + private FindMinima successor = null; + public void add(FindMinima succ) { + FindMinima end = this; + while(end.successor != null) + end = end.successor; // Traverse list + end.successor = succ; + } + public double[] algorithm(double[] line) { + if(successor != null) + return successor.algorithm(line); + else // Try the next one in the chain: + return new double[] {}; + } +} + +class LeastSquares extends FindMinima { + @Override + public double[] algorithm(double[] line) { + System.out.println("LeastSquares.algorithm"); + boolean weSucceed = false; + if(weSucceed) // Actual test/calculation here + return new double[] { 1.1, 2.2 }; // Dummy + else // Try the next one in the chain: + return super.algorithm(line); + } +} + +class Perturbation extends FindMinima { + @Override + public double[] algorithm(double[] line) { + System.out.println("Perturbation.algorithm"); + boolean weSucceed = false; + if(weSucceed) // Actual test/calculation here + return new double[] { 3.3, 4.4 }; // Dummy + else // Try the next one in the chain: + return super.algorithm(line); + } +} + +class Bisection extends FindMinima { + @Override + public double[] algorithm(double[] line) { + System.out.println("Bisection.algorithm"); + boolean weSucceed = true; + if(weSucceed) // Actual test/calculation here + return new double[] { 5.5, 6.6 }; // Dummy + else + return super.algorithm(line); + } +} + +// The "Handler" proxies to the first functor: +class MinimaSolver { + private FindMinima chain = new FindMinima(); + void add(FindMinima newAlgorithm) { + chain.add(newAlgorithm); + } + // Make the call to the top of the chain: + double[] minima(double[] line) { + return chain.algorithm(line); + } +} + +public class ChainOfResponsibility { + public static void printArray(double[] array) { + for(int i = 0; i < array.length; i++) { + System.out.print(array[i]); + if(i != array.length -1) + System.out.print(", "); + } + System.out.println(); + } + public static void main(String args[]) { + MinimaSolver solver = new MinimaSolver(); + solver.add(new LeastSquares()); + solver.add(new Perturbation()); + solver.add(new Bisection()); + double[] line = { + 1.0, 2.0, 1.0, 2.0, -1.0, + 3.0, 4.0, 5.0, 4.0 }; + printArray(solver.minima(line)); + } +} ///:~ diff --git a/patterns/doubledispatch/DDAluminum.java b/patterns/doubledispatch/DDAluminum.java new file mode 100644 index 00000000..9bb9ecec --- /dev/null +++ b/patterns/doubledispatch/DDAluminum.java @@ -0,0 +1,16 @@ +//: patterns/doubledispatch/DDAluminum.java +// Aluminum for double dispatching. +package patterns.doubledispatch; +import patterns.trash.*; + +public class DDAluminum extends Aluminum + implements TypedBinMember { + public DDAluminum(double wt) { super(wt); } + @Override + public boolean addToBin(TypedBin[] tb) { + for(int i = 0; i < tb.length; i++) + if(tb[i].add(this)) + return true; + return false; + } +} ///:~ diff --git a/patterns/doubledispatch/DDCardboard.java b/patterns/doubledispatch/DDCardboard.java new file mode 100644 index 00000000..f8713adf --- /dev/null +++ b/patterns/doubledispatch/DDCardboard.java @@ -0,0 +1,16 @@ +//: patterns/doubledispatch/DDCardboard.java +// Cardboard for double dispatching. +package patterns.doubledispatch; +import patterns.trash.*; + +public class DDCardboard extends Cardboard + implements TypedBinMember { + public DDCardboard(double wt) { super(wt); } + @Override + public boolean addToBin(TypedBin[] tb) { + for(int i = 0; i < tb.length; i++) + if(tb[i].add(this)) + return true; + return false; + } +} ///:~ diff --git a/patterns/doubledispatch/DDGlass.java b/patterns/doubledispatch/DDGlass.java new file mode 100644 index 00000000..573d2519 --- /dev/null +++ b/patterns/doubledispatch/DDGlass.java @@ -0,0 +1,16 @@ +//: patterns/doubledispatch/DDGlass.java +// Glass for double dispatching. +package patterns.doubledispatch; +import patterns.trash.*; + +public class DDGlass extends Glass + implements TypedBinMember { + public DDGlass(double wt) { super(wt); } + @Override + public boolean addToBin(TypedBin[] tb) { + for(int i = 0; i < tb.length; i++) + if(tb[i].add(this)) + return true; + return false; + } +} ///:~ diff --git a/patterns/doubledispatch/DDPaper.java b/patterns/doubledispatch/DDPaper.java new file mode 100644 index 00000000..6b2feefd --- /dev/null +++ b/patterns/doubledispatch/DDPaper.java @@ -0,0 +1,16 @@ +//: patterns/doubledispatch/DDPaper.java +// Paper for double dispatching. +package patterns.doubledispatch; +import patterns.trash.*; + +public class DDPaper extends Paper + implements TypedBinMember { + public DDPaper(double wt) { super(wt); } + @Override + public boolean addToBin(TypedBin[] tb) { + for(int i = 0; i < tb.length; i++) + if(tb[i].add(this)) + return true; + return false; + } +} ///:~ diff --git a/patterns/doubledispatch/DDTrash.dat b/patterns/doubledispatch/DDTrash.dat new file mode 100644 index 00000000..b1153b21 --- /dev/null +++ b/patterns/doubledispatch/DDTrash.dat @@ -0,0 +1,35 @@ +patterns.doubledispatch.DDGlass:54 +patterns.doubledispatch.DDPaper:22 +patterns.doubledispatch.DDPaper:11 +patterns.doubledispatch.DDGlass:17 +patterns.doubledispatch.DDAluminum:89 +patterns.doubledispatch.DDPaper:88 +patterns.doubledispatch.DDAluminum:76 +patterns.doubledispatch.DDCardboard:96 +patterns.doubledispatch.DDAluminum:25 +patterns.doubledispatch.DDAluminum:34 +patterns.doubledispatch.DDGlass:11 +patterns.doubledispatch.DDGlass:68 +patterns.doubledispatch.DDGlass:43 +patterns.doubledispatch.DDAluminum:27 +patterns.doubledispatch.DDCardboard:44 +patterns.doubledispatch.DDAluminum:18 +patterns.doubledispatch.DDPaper:91 +patterns.doubledispatch.DDGlass:63 +patterns.doubledispatch.DDGlass:50 +patterns.doubledispatch.DDGlass:80 +patterns.doubledispatch.DDAluminum:81 +patterns.doubledispatch.DDCardboard:12 +patterns.doubledispatch.DDGlass:12 +patterns.doubledispatch.DDGlass:54 +patterns.doubledispatch.DDAluminum:36 +patterns.doubledispatch.DDAluminum:93 +patterns.doubledispatch.DDGlass:93 +patterns.doubledispatch.DDPaper:80 +patterns.doubledispatch.DDGlass:36 +patterns.doubledispatch.DDGlass:12 +patterns.doubledispatch.DDGlass:60 +patterns.doubledispatch.DDPaper:66 +patterns.doubledispatch.DDAluminum:36 +patterns.doubledispatch.DDCardboard:22 + diff --git a/patterns/doubledispatch/DoubleDispatch.java b/patterns/doubledispatch/DoubleDispatch.java new file mode 100644 index 00000000..803e8185 --- /dev/null +++ b/patterns/doubledispatch/DoubleDispatch.java @@ -0,0 +1,71 @@ +//: patterns/doubledispatch/DoubleDispatch.java +// Using multiple dispatching to handle more +// than one unknown type during a method call. +package patterns.doubledispatch; +import patterns.trash.*; +import java.util.*; + +class AluminumBin extends TypedBin { + @Override + public boolean add(DDAluminum a) { + return addIt(a); + } +} + +class PaperBin extends TypedBin { + @Override + public boolean add(DDPaper a) { + return addIt(a); + } +} + +class GlassBin extends TypedBin { + @Override + public boolean add(DDGlass a) { + return addIt(a); + } +} + +class CardboardBin extends TypedBin { + @Override + public boolean add(DDCardboard a) { + return addIt(a); + } +} + +class TrashBinSet { + private TypedBin[] binSet = { + new AluminumBin(), + new PaperBin(), + new GlassBin(), + new CardboardBin() + }; + public void sortIntoBins(ArrayList bin) { + Iterator e = bin.iterator(); + while(e.hasNext()) { + TypedBinMember t = + (TypedBinMember)e.next(); + if(!t.addToBin(binSet)) + System.err.println("Couldn't add " + t); + } + } + public TypedBin[] binSet() { return binSet; } +} + +public class DoubleDispatch { + public static void main(String[] args) { + ArrayList bin = new ArrayList(); + TrashBinSet bins = new TrashBinSet(); + // ParseTrash still works, without changes: + ParseTrash.fillBin("DDTrash.dat", bin); + // Sort from the master bin into the + // individually-typed bins: + bins.sortIntoBins(bin); + TypedBin[] tb = bins.binSet(); + // Perform sumValue for each bin... + for(int i = 0; i < tb.length; i++) + Trash.sumValue(tb[i].v); + // ... and for the master bin + Trash.sumValue(bin); + } +} ///:~ diff --git a/patterns/doubledispatch/TypedBin.java b/patterns/doubledispatch/TypedBin.java new file mode 100644 index 00000000..311a9d75 --- /dev/null +++ b/patterns/doubledispatch/TypedBin.java @@ -0,0 +1,28 @@ +//: patterns/doubledispatch/TypedBin.java +// An ArrayList that can grab the right type. +package patterns.doubledispatch; +import patterns.trash.*; +import java.util.*; + +public abstract class TypedBin { + ArrayList v = new ArrayList(); + protected boolean addIt(Trash t) { + v.add(t); + return true; + } + public Iterator elements() { + return v.iterator(); + } + public boolean add(DDAluminum a) { + return false; + } + public boolean add(DDPaper a) { + return false; + } + public boolean add(DDGlass a) { + return false; + } + public boolean add(DDCardboard a) { + return false; + } +} ///:~ diff --git a/patterns/doubledispatch/TypedBinMember.java b/patterns/doubledispatch/TypedBinMember.java new file mode 100644 index 00000000..333088e9 --- /dev/null +++ b/patterns/doubledispatch/TypedBinMember.java @@ -0,0 +1,10 @@ +//: patterns/doubledispatch/TypedBinMember.java +// An interface for adding the double dispatching +// method to the trash hierarchy without +// modifying the original hierarchy. +package patterns.doubledispatch; + +interface TypedBinMember { + // The new method: + boolean addToBin(TypedBin[] tb); +} ///:~ diff --git a/patterns/dynatrash/DynaTrash.java b/patterns/dynatrash/DynaTrash.java new file mode 100644 index 00000000..fea0d776 --- /dev/null +++ b/patterns/dynatrash/DynaTrash.java @@ -0,0 +1,50 @@ +//: patterns/dynatrash/DynaTrash.java +// Using a HashMap of ArrayLists and RTTI +// to automatically sort trash into +// vectors. This solution, despite the +// use of RTTI, is extensible. +package patterns.dynatrash; +import patterns.trash.*; +import java.util.*; + +// Generic TypeMap works in any situation: +class TypeMap { + private HashMap t = new HashMap(); + public void add(Object o) { + Class type = o.getClass(); + if(t.containsKey(type)) + ((ArrayList)t.get(type)).add(o); + else { + ArrayList v = new ArrayList(); + v.add(o); + t.put(type,v); + } + } + public ArrayList get(Class type) { + return (ArrayList)t.get(type); + } + public Iterator keys() { + return t.keySet().iterator(); + } +} + +// Adapter class to allow +// callbacks from ParseTrash.fillBin(): +class TypeMapAdapter implements Fillable { + TypeMap map; + public TypeMapAdapter(TypeMap tm) { map = tm; } + @Override + public void addTrash(Trash t) { map.add(t); } +} + +public class DynaTrash { + public static void main(String[] args) { + TypeMap bin = new TypeMap(); + ParseTrash.fillBin("Trash.dat", + new TypeMapAdapter(bin)); + Iterator keys = bin.keys(); + while(keys.hasNext()) + Trash.sumValue( + bin.get((Class)keys.next())); + } +} ///:~ diff --git a/patterns/dynatrash/Trash.dat b/patterns/dynatrash/Trash.dat new file mode 100644 index 00000000..afa62480 --- /dev/null +++ b/patterns/dynatrash/Trash.dat @@ -0,0 +1,35 @@ +patterns.trash.Glass:54 +patterns.trash.Paper:22 +patterns.trash.Paper:11 +patterns.trash.Glass:17 +patterns.trash.Aluminum:89 +patterns.trash.Paper:88 +patterns.trash.Aluminum:76 +patterns.trash.Cardboard:96 +patterns.trash.Aluminum:25 +patterns.trash.Aluminum:34 +patterns.trash.Glass:11 +patterns.trash.Glass:68 +patterns.trash.Glass:43 +patterns.trash.Aluminum:27 +patterns.trash.Cardboard:44 +patterns.trash.Aluminum:18 +patterns.trash.Paper:91 +patterns.trash.Glass:63 +patterns.trash.Glass:50 +patterns.trash.Glass:80 +patterns.trash.Aluminum:81 +patterns.trash.Cardboard:12 +patterns.trash.Glass:12 +patterns.trash.Glass:54 +patterns.trash.Aluminum:36 +patterns.trash.Aluminum:93 +patterns.trash.Glass:93 +patterns.trash.Paper:80 +patterns.trash.Glass:36 +patterns.trash.Glass:12 +patterns.trash.Glass:60 +patterns.trash.Paper:66 +patterns.trash.Aluminum:36 +patterns.trash.Cardboard:22 + diff --git a/patterns/factory/ShapeFactory1.java b/patterns/factory/ShapeFactory1.java new file mode 100644 index 00000000..2ebd14e7 --- /dev/null +++ b/patterns/factory/ShapeFactory1.java @@ -0,0 +1,66 @@ +//: patterns/factory/ShapeFactory1.java +// A simple static factory method. +package patterns.factory; +import java.util.*; + +class BadShapeCreation extends Exception { + BadShapeCreation(String msg) { + super(msg); + } +} + +abstract class Shape { + public abstract void draw(); + public abstract void erase(); + static Shape factory(String type) + throws BadShapeCreation { + if(type == "Circle") return new Circle(); + if(type == "Square") return new Square(); + throw new BadShapeCreation(type); + } +} + +class Circle extends Shape { + Circle() {} // Friendly constructor + @Override + public void draw() { + System.out.println("Circle.draw"); + } + @Override + public void erase() { + System.out.println("Circle.erase"); + } +} + +class Square extends Shape { + Square() {} // Friendly constructor + @Override + public void draw() { + System.out.println("Square.draw"); + } + @Override + public void erase() { + System.out.println("Square.erase"); + } +} + +public class ShapeFactory1 { + public static void main(String args[]) { + String shlist[] = { "Circle", "Square", + "Square", "Circle", "Circle", "Square" }; + ArrayList shapes = new ArrayList(); + try { + for(int i = 0; i < shlist.length; i++) + shapes.add(Shape.factory(shlist[i])); + } catch(BadShapeCreation e) { + e.printStackTrace(); + return; + } + Iterator i = shapes.iterator(); + while(i.hasNext()) { + Shape s = (Shape)i.next(); + s.draw(); + s.erase(); + } + } +} ///:~ diff --git a/patterns/observer/ObservedFlower.java b/patterns/observer/ObservedFlower.java new file mode 100644 index 00000000..e401f5ba --- /dev/null +++ b/patterns/observer/ObservedFlower.java @@ -0,0 +1,143 @@ +//: patterns/observer/ObservedFlower.java +// Demonstration of "observer" pattern. +package patterns.observer; +import java.util.*; +import static net.mindview.util.Print.*; + +class Flower { + private boolean isOpen; + private OpenNotifier oNotify = + new OpenNotifier(); + private CloseNotifier cNotify = + new CloseNotifier(); + public Flower() { isOpen = false; } + public void open() { // Opens its petals + isOpen = true; + oNotify.notifyObservers(); + cNotify.open(); + } + public void close() { // Closes its petals + isOpen = false; + cNotify.notifyObservers(); + oNotify.close(); + } + public Observable opening() { + return oNotify; + } + public Observable closing() { + return cNotify; + } + private class OpenNotifier extends Observable { + private boolean alreadyOpen = false; + @Override + public void notifyObservers() { + if(isOpen && !alreadyOpen) { + setChanged(); + super.notifyObservers(); + alreadyOpen = true; + } + } + public void close() { alreadyOpen = false; } + } + private class CloseNotifier extends Observable{ + private boolean alreadyClosed = false; + @Override + public void notifyObservers() { + if(!isOpen && !alreadyClosed) { + setChanged(); + super.notifyObservers(); + alreadyClosed = true; + } + } + public void open() { alreadyClosed = false; } + } +} + +class Bee { + private String name; + private OpenObserver openObsrv = + new OpenObserver(); + private CloseObserver closeObsrv = + new CloseObserver(); + public Bee(String nm) { name = nm; } + // An inner class for observing openings: + private class OpenObserver implements Observer{ + @Override + public void update(Observable ob, Object a) { + print("Bee " + name + "'s breakfast time!"); + } + } + // Another inner class for closings: + private class CloseObserver implements Observer{ + @Override + public void update(Observable ob, Object a) { + print("Bee " + name + "'s bed time!"); + } + } + public Observer openObserver() { + return openObsrv; + } + public Observer closeObserver() { + return closeObsrv; + } +} + +class Hummingbird { + private String name; + private OpenObserver openObsrv = + new OpenObserver(); + private CloseObserver closeObsrv = + new CloseObserver(); + public Hummingbird(String nm) { name = nm; } + private class OpenObserver implements Observer{ + @Override + public void update(Observable ob, Object a) { + print("Hummingbird " + name + + "'s breakfast time!"); + } + } + private class CloseObserver implements Observer{ + @Override + public void update(Observable ob, Object a) { + print("Hummingbird " + name + "'s bed time!"); + } + } + public Observer openObserver() { + return openObsrv; + } + public Observer closeObserver() { + return closeObsrv; + } +} + +public class ObservedFlower { + public static void main(String args[]) { + Flower f = new Flower(); + Bee + ba = new Bee("A"), + bb = new Bee("B"); + Hummingbird + ha = new Hummingbird("A"), + hb = new Hummingbird("B"); + f.opening().addObserver(ha.openObserver()); + f.opening().addObserver(hb.openObserver()); + f.opening().addObserver(ba.openObserver()); + f.opening().addObserver(bb.openObserver()); + f.closing().addObserver(ha.closeObserver()); + f.closing().addObserver(hb.closeObserver()); + f.closing().addObserver(ba.closeObserver()); + f.closing().addObserver(bb.closeObserver()); + // Hummingbird B decides to sleep in: + f.opening().deleteObserver(hb.openObserver()); + // A change that interests observers: + f.open(); + f.open(); // It's already open, no change. + // Bee A doesn't want to go to bed: + f.closing().deleteObserver(ba.closeObserver()); + f.close(); + f.close(); // It's already closed; no change + f.opening().deleteObservers(); + f.open(); + f.close(); + } +} ///:~ diff --git a/patterns/recyclea/RecycleA.java b/patterns/recyclea/RecycleA.java new file mode 100644 index 00000000..362e410c --- /dev/null +++ b/patterns/recyclea/RecycleA.java @@ -0,0 +1,102 @@ +//: patterns/recyclea/RecycleA.java +// Recycling with RTTI. +package patterns.recyclea; +import java.util.*; +import java.io.*; + +abstract class Trash { + private double weight; + Trash(double wt) { weight = wt; } + abstract double value(); + double weight() { return weight; } + // Sums the value of Trash in a bin: + static void sumValue(ArrayList bin) { + Iterator e = bin.iterator(); + double val = 0.0f; + while(e.hasNext()) { + // One kind of RTTI: + // A dynamically-checked cast + Trash t = (Trash)e.next(); + // Polymorphism in action: + val += t.weight() * t.value(); + System.out.println( + "weight of " + + // Using RTTI to get type + // information about the class: + t.getClass().getName() + + " = " + t.weight()); + } + System.out.println("Total value = " + val); + } +} + +class Aluminum extends Trash { + static double val = 1.67f; + Aluminum(double wt) { super(wt); } + @Override + double value() { return val; } + static void value(double newval) { + val = newval; + } +} + +class Paper extends Trash { + static double val = 0.10f; + Paper(double wt) { super(wt); } + @Override + double value() { return val; } + static void value(double newval) { + val = newval; + } +} + +class Glass extends Trash { + static double val = 0.23f; + Glass(double wt) { super(wt); } + @Override + double value() { return val; } + static void value(double newval) { + val = newval; + } +} + +public class RecycleA { + public static void main(String[] args) { + ArrayList bin = new ArrayList(); + // Fill up the Trash bin: + for(int i = 0; i < 30; i++) + switch((int)(Math.random() * 3)) { + case 0 : + bin.add(new + Aluminum(Math.random() * 100)); + break; + case 1 : + bin.add(new + Paper(Math.random() * 100)); + break; + case 2 : + bin.add(new + Glass(Math.random() * 100)); + } + ArrayList + glassBin = new ArrayList(), + paperBin = new ArrayList(), + alBin = new ArrayList(); + Iterator sorter = bin.iterator(); + // Sort the Trash: + while(sorter.hasNext()) { + Object t = sorter.next(); + // RTTI to show class membership: + if(t instanceof Aluminum) + alBin.add(t); + if(t instanceof Paper) + paperBin.add(t); + if(t instanceof Glass) + glassBin.add(t); + } + Trash.sumValue(alBin); + Trash.sumValue(paperBin); + Trash.sumValue(glassBin); + Trash.sumValue(bin); + } +} ///:~ diff --git a/patterns/recycleap/RecycleAP.java b/patterns/recycleap/RecycleAP.java new file mode 100644 index 00000000..084118c8 --- /dev/null +++ b/patterns/recycleap/RecycleAP.java @@ -0,0 +1,33 @@ +//: patterns/recycleap/RecycleAP.java +// Recycling with RTTI and Prototypes. +package patterns.recycleap; +import patterns.trash.*; +import java.util.*; + +public class RecycleAP { + public static void main(String[] args) { + ArrayList bin = new ArrayList(); + // Fill up the Trash bin: + ParseTrash.fillBin("Trash.dat", bin); + ArrayList + glassBin = new ArrayList(), + paperBin = new ArrayList(), + alBin = new ArrayList(); + Iterator sorter = bin.iterator(); + // Sort the Trash: + while(sorter.hasNext()) { + Object t = sorter.next(); + // RTTI to show class membership: + if(t instanceof Aluminum) + alBin.add(t); + if(t instanceof Paper) + paperBin.add(t); + if(t instanceof Glass) + glassBin.add(t); + } + Trash.sumValue(alBin); + Trash.sumValue(paperBin); + Trash.sumValue(glassBin); + Trash.sumValue(bin); + } +} ///:~ diff --git a/patterns/recycleap/Trash.dat b/patterns/recycleap/Trash.dat new file mode 100644 index 00000000..afa62480 --- /dev/null +++ b/patterns/recycleap/Trash.dat @@ -0,0 +1,35 @@ +patterns.trash.Glass:54 +patterns.trash.Paper:22 +patterns.trash.Paper:11 +patterns.trash.Glass:17 +patterns.trash.Aluminum:89 +patterns.trash.Paper:88 +patterns.trash.Aluminum:76 +patterns.trash.Cardboard:96 +patterns.trash.Aluminum:25 +patterns.trash.Aluminum:34 +patterns.trash.Glass:11 +patterns.trash.Glass:68 +patterns.trash.Glass:43 +patterns.trash.Aluminum:27 +patterns.trash.Cardboard:44 +patterns.trash.Aluminum:18 +patterns.trash.Paper:91 +patterns.trash.Glass:63 +patterns.trash.Glass:50 +patterns.trash.Glass:80 +patterns.trash.Aluminum:81 +patterns.trash.Cardboard:12 +patterns.trash.Glass:12 +patterns.trash.Glass:54 +patterns.trash.Aluminum:36 +patterns.trash.Aluminum:93 +patterns.trash.Glass:93 +patterns.trash.Paper:80 +patterns.trash.Glass:36 +patterns.trash.Glass:12 +patterns.trash.Glass:60 +patterns.trash.Paper:66 +patterns.trash.Aluminum:36 +patterns.trash.Cardboard:22 + diff --git a/patterns/recycleb/RecycleB.java b/patterns/recycleb/RecycleB.java new file mode 100644 index 00000000..b98c6c32 --- /dev/null +++ b/patterns/recycleb/RecycleB.java @@ -0,0 +1,66 @@ +//: patterns/recycleb/RecycleB.java +// Adding more objects to the recycling problem. +package patterns.recycleb; +import patterns.trash.*; +import java.util.*; + +// A vector that admits only the right type: +class Tbin extends ArrayList { + Class binType; + Tbin(Class binType) { + this.binType = binType; + } + boolean grab(Trash t) { + // Comparing class types: + if(t.getClass().equals(binType)) { + add(t); + return true; // Object grabbed + } + return false; // Object not grabbed + } +} + +class TbinList extends ArrayList { //(*1*) + boolean sort(Trash t) { + Iterator e = iterator(); + while(e.hasNext()) { + Tbin bin = (Tbin)e.next(); + if(bin.grab(t)) return true; + } + return false; // bin not found for t + } + void sortBin(Tbin bin) { // (*2*) + Iterator e = bin.iterator(); + while(e.hasNext()) + if(!sort((Trash)e.next())) + System.out.println("Bin not found"); + } +} + +public class RecycleB { + static Tbin bin = new Tbin(Trash.class); + public static void main(String[] args) { + // Fill up the Trash bin: + ParseTrash.fillBin("Trash.dat", bin); + + TbinList trashBins = new TbinList(); + trashBins.add( + new Tbin(Aluminum.class)); + trashBins.add( + new Tbin(Paper.class)); + trashBins.add( + new Tbin(Glass.class)); + // add one line here: (*3*) + trashBins.add( + new Tbin(Cardboard.class)); + + trashBins.sortBin(bin); // (*4*) + + Iterator e = trashBins.iterator(); + while(e.hasNext()) { + Tbin b = (Tbin)e.next(); + Trash.sumValue(b); + } + Trash.sumValue(bin); + } +} ///:~ diff --git a/patterns/recycleb/Trash.dat b/patterns/recycleb/Trash.dat new file mode 100644 index 00000000..afa62480 --- /dev/null +++ b/patterns/recycleb/Trash.dat @@ -0,0 +1,35 @@ +patterns.trash.Glass:54 +patterns.trash.Paper:22 +patterns.trash.Paper:11 +patterns.trash.Glass:17 +patterns.trash.Aluminum:89 +patterns.trash.Paper:88 +patterns.trash.Aluminum:76 +patterns.trash.Cardboard:96 +patterns.trash.Aluminum:25 +patterns.trash.Aluminum:34 +patterns.trash.Glass:11 +patterns.trash.Glass:68 +patterns.trash.Glass:43 +patterns.trash.Aluminum:27 +patterns.trash.Cardboard:44 +patterns.trash.Aluminum:18 +patterns.trash.Paper:91 +patterns.trash.Glass:63 +patterns.trash.Glass:50 +patterns.trash.Glass:80 +patterns.trash.Aluminum:81 +patterns.trash.Cardboard:12 +patterns.trash.Glass:12 +patterns.trash.Glass:54 +patterns.trash.Aluminum:36 +patterns.trash.Aluminum:93 +patterns.trash.Glass:93 +patterns.trash.Paper:80 +patterns.trash.Glass:36 +patterns.trash.Glass:12 +patterns.trash.Glass:60 +patterns.trash.Paper:66 +patterns.trash.Aluminum:36 +patterns.trash.Cardboard:22 + diff --git a/patterns/state/StateMachineDemo.java b/patterns/state/StateMachineDemo.java new file mode 100644 index 00000000..332f9b57 --- /dev/null +++ b/patterns/state/StateMachineDemo.java @@ -0,0 +1,77 @@ +//: patterns/state/StateMachineDemo.java +// Demonstrates StateMachine pattern +// and Template method. +package patterns.state; +import java.util.*; + +interface State { + void run(); +} + +abstract class StateMachine { + protected State currentState; + abstract protected boolean changeState(); + // Template method: + protected final void runAll() { + while(changeState()) // Customizable + currentState.run(); + } +} + +// A different subclass for each state: + +class Wash implements State { + @Override + public void run() { + System.out.println("Washing"); + try { + Thread.sleep(500); + } catch(InterruptedException e) {} + } +} + +class Spin implements State { + @Override + public void run() { + System.out.println("Spinning"); + try { + Thread.sleep(500); + } catch(InterruptedException e) {} + } +} + +class Rinse implements State { + @Override + public void run() { + System.out.println("Rinsing"); + try { + Thread.sleep(500); + } catch(InterruptedException e) {} + } +} + +class Washer extends StateMachine { + private int i = 0; + // The state table: + private State states[] = { + new Wash(), new Spin(), + new Rinse(), new Spin(), + }; + public Washer() { runAll(); } + @Override + public boolean changeState() { + if(i < states.length) { + // Change the state by setting the + // surrogate handle to a new object: + currentState = states[i++]; + return true; + } else + return false; + } +} + +public class StateMachineDemo { + public static void main(String args[]) { + new Washer(); + } +} ///:~ diff --git a/patterns/strategy/StrategyPattern.java b/patterns/strategy/StrategyPattern.java new file mode 100644 index 00000000..2d81cb86 --- /dev/null +++ b/patterns/strategy/StrategyPattern.java @@ -0,0 +1,65 @@ +//: patterns/strategy/StrategyPattern.java +package patterns.strategy; + +// The strategy interface: +interface FindMinima { + // Line is a sequence of points: + double[] algorithm(double[] line); +} + +// The various strategies: +class LeastSquares implements FindMinima { + @Override + public double[] algorithm(double[] line) { + return new double[] { 1.1, 2.2 }; // Dummy + } +} + +class Perturbation implements FindMinima { + @Override + public double[] algorithm(double[] line) { + return new double[] { 3.3, 4.4 }; // Dummy + } +} + +class Bisection implements FindMinima { + @Override + public double[] algorithm(double[] line) { + return new double[] { 5.5, 6.6 }; // Dummy + } +} + +// The "Context" controls the strategy: +class MinimaSolver { + private FindMinima strategy; + public MinimaSolver(FindMinima strat) { + strategy = strat; + } + double[] minima(double[] line) { + return strategy.algorithm(line); + } + void changeAlgorithm(FindMinima newAlgorithm) { + strategy = newAlgorithm; + } +} + +public class StrategyPattern { + public static void printArray(double[] array) { + for(int i = 0; i < array.length; i++) { + System.out.print(array[i]); + if(i != array.length -1) + System.out.print(", "); + } + System.out.println(); + } + public static void main(String args[]) { + MinimaSolver solver = + new MinimaSolver(new LeastSquares()); + double[] line = { + 1.0, 2.0, 1.0, 2.0, -1.0, + 3.0, 4.0, 5.0, 4.0 }; + printArray(solver.minima(line)); + solver.changeAlgorithm(new Bisection()); + printArray(solver.minima(line)); + } +} ///:~ diff --git a/patterns/trash/Aluminum.java b/patterns/trash/Aluminum.java new file mode 100644 index 00000000..41d2bb19 --- /dev/null +++ b/patterns/trash/Aluminum.java @@ -0,0 +1,13 @@ +//: patterns/trash/Aluminum.java +// The Aluminum class with prototyping. +package patterns.trash; + +public class Aluminum extends Trash { + private static double val = 1.67f; + public Aluminum(double wt) { super(wt); } + @Override + public double value() { return val; } + public static void value(double newVal) { + val = newVal; + } +} ///:~ diff --git a/patterns/trash/Cardboard.java b/patterns/trash/Cardboard.java new file mode 100644 index 00000000..c79d4239 --- /dev/null +++ b/patterns/trash/Cardboard.java @@ -0,0 +1,13 @@ +//: patterns/trash/Cardboard.java +// The Cardboard class with prototyping. +package patterns.trash; + +public class Cardboard extends Trash { + private static double val = 0.23f; + public Cardboard(double wt) { super(wt); } + @Override + public double value() { return val; } + public static void value(double newVal) { + val = newVal; + } +} ///:~ diff --git a/patterns/trash/Fillable.java b/patterns/trash/Fillable.java new file mode 100644 index 00000000..ffaa8e4a --- /dev/null +++ b/patterns/trash/Fillable.java @@ -0,0 +1,7 @@ +//: patterns/trash/Fillable.java +// Any object that can be filled with Trash. +package patterns.trash; + +public interface Fillable { + void addTrash(Trash t); +} ///:~ diff --git a/patterns/trash/FillableArrayList.java b/patterns/trash/FillableArrayList.java new file mode 100644 index 00000000..dc050304 --- /dev/null +++ b/patterns/trash/FillableArrayList.java @@ -0,0 +1,14 @@ +//: patterns/trash/FillableArrayList.java +// Adapter that makes an ArrayList Fillable. +package patterns.trash; +import java.util.*; + +public class FillableArrayList +implements Fillable { + private ArrayList v; + public FillableArrayList(ArrayList vv) { v = vv; } + @Override + public void addTrash(Trash t) { + v.add(t); + } +} ///:~ diff --git a/patterns/trash/Glass.java b/patterns/trash/Glass.java new file mode 100644 index 00000000..fddd7dc7 --- /dev/null +++ b/patterns/trash/Glass.java @@ -0,0 +1,13 @@ +//: patterns/trash/Glass.java +// The Glass class with prototyping. +package patterns.trash; + +public class Glass extends Trash { + private static double val = 0.23f; + public Glass(double wt) { super(wt); } + @Override + public double value() { return val; } + public static void value(double newVal) { + val = newVal; + } +} ///:~ diff --git a/patterns/trash/Paper.java b/patterns/trash/Paper.java new file mode 100644 index 00000000..310e5248 --- /dev/null +++ b/patterns/trash/Paper.java @@ -0,0 +1,13 @@ +//: patterns/trash/Paper.java +// The Paper class with prototyping. +package patterns.trash; + +public class Paper extends Trash { + private static double val = 0.10f; + public Paper(double wt) { super(wt); } + @Override + public double value() { return val; } + public static void value(double newVal) { + val = newVal; + } +} ///:~ diff --git a/patterns/trash/ParseTrash.java b/patterns/trash/ParseTrash.java new file mode 100644 index 00000000..2835ac44 --- /dev/null +++ b/patterns/trash/ParseTrash.java @@ -0,0 +1,40 @@ +//: patterns/trash/ParseTrash.java +// Open a file and parse its contents into +// Trash objects, placing each into an ArrayList. +package patterns.trash; +import java.util.*; +import java.io.*; + +public class ParseTrash { + public static void + fillBin(String filename, Fillable bin) { + try { + BufferedReader data = + new BufferedReader( + new FileReader(filename)); + String buf; + while((buf = data.readLine())!= null) { + if(buf.trim().length() == 0) + continue; // Skip empty lines + String type = buf.substring(0, + buf.indexOf(':')).trim(); + double weight = Double.valueOf( + buf.substring(buf.indexOf(':') + 1) + .trim()).doubleValue(); + bin.addTrash( + Trash.factory( + new Trash.Info(type, weight))); + } + data.close(); + } catch(IOException e) { + e.printStackTrace(); + } catch(Exception e) { + e.printStackTrace(); + } + } + // Special case to handle ArrayList: + public static void + fillBin(String filename, ArrayList bin) { + fillBin(filename, new FillableArrayList(bin)); + } +} ///:~ diff --git a/patterns/trash/Trash.java b/patterns/trash/Trash.java new file mode 100644 index 00000000..34509ec2 --- /dev/null +++ b/patterns/trash/Trash.java @@ -0,0 +1,86 @@ +//: patterns/trash/Trash.java +// Base class for Trash recycling examples. +package patterns.trash; +import java.util.*; +import java.lang.reflect.*; + +public abstract class Trash { + private double weight; + Trash(double wt) { weight = wt; } + Trash() {} + public abstract double value(); + public double weight() { return weight; } + // Sums the value of Trash in a bin: + public static void sumValue(ArrayList bin) { + Iterator e = bin.iterator(); + double val = 0.0f; + while(e.hasNext()) { + // One kind of RTTI: + // A dynamically-checked cast + Trash t = (Trash)e.next(); + val += t.weight() * t.value(); + System.out.println( + "weight of " + + // Using RTTI to get type + // information about the class: + t.getClass().getName() + + " = " + t.weight()); + } + System.out.println("Total value = " + val); + } + // Remainder of class provides support for + // prototyping: + public static class PrototypeNotFoundException + extends Exception {} + public static class CannotCreateTrashException + extends Exception {} + private static ArrayList trashTypes = + new ArrayList(); + public static Trash factory(Info info) + throws PrototypeNotFoundException, + CannotCreateTrashException { + for(int i = 0; i < trashTypes.size(); i++) { + // Somehow determine the new type + // to create, and create one: + Class tc = + (Class)trashTypes.get(i); + if (tc.getName().indexOf(info.id) != -1) { + try { + // Get the dynamic constructor method + // that takes a double argument: + Constructor ctor = + tc.getConstructor( + new Class[] {double.class}); + // Call the constructor to create a + // new object: + return (Trash)ctor.newInstance( + new Object[]{new Double(info.data)}); + } catch(Exception ex) { + ex.printStackTrace(); + throw new CannotCreateTrashException(); + } + } + } + // Class was not in the list. Try to load it, + // but it must be in your class path! + try { + System.out.println("Loading " + info.id); + trashTypes.add( + Class.forName(info.id)); + } catch(Exception e) { + e.printStackTrace(); + throw new PrototypeNotFoundException(); + } + // Loaded successfully. Recursive call + // should work this time: + return factory(info); + } + public static class Info { + public String id; + public double data; + public Info(String name, double data) { + id = name; + this.data = data; + } + } +} ///:~ diff --git a/patterns/trashvisitor/TrashVisitor.java b/patterns/trashvisitor/TrashVisitor.java new file mode 100644 index 00000000..4dd86ecb --- /dev/null +++ b/patterns/trashvisitor/TrashVisitor.java @@ -0,0 +1,110 @@ +//: patterns/trashvisitor/TrashVisitor.java +// The "visitor" pattern. +package patterns.trashvisitor; +import patterns.trash.*; +import java.util.*; + +// Specific group of algorithms packaged +// in each implementation of Visitor: +class PriceVisitor implements Visitor { + private double alSum; // Aluminum + private double pSum; // Paper + private double gSum; // Glass + private double cSum; // Cardboard + @Override + public void visit(VAluminum al) { + double v = al.weight() * al.value(); + System.out.println( + "value of Aluminum= " + v); + alSum += v; + } + @Override + public void visit(VPaper p) { + double v = p.weight() * p.value(); + System.out.println( + "value of Paper= " + v); + pSum += v; + } + @Override + public void visit(VGlass g) { + double v = g.weight() * g.value(); + System.out.println( + "value of Glass= " + v); + gSum += v; + } + @Override + public void visit(VCardboard c) { + double v = c.weight() * c.value(); + System.out.println( + "value of Cardboard = " + v); + cSum += v; + } + void total() { + System.out.println( + "Total Aluminum: $" + alSum + "\n" + + "Total Paper: $" + pSum + "\n" + + "Total Glass: $" + gSum + "\n" + + "Total Cardboard: $" + cSum); + } +} + +class WeightVisitor implements Visitor { + private double alSum; // Aluminum + private double pSum; // Paper + private double gSum; // Glass + private double cSum; // Cardboard + @Override + public void visit(VAluminum al) { + alSum += al.weight(); + System.out.println("weight of Aluminum = " + + al.weight()); + } + @Override + public void visit(VPaper p) { + pSum += p.weight(); + System.out.println("weight of Paper = " + + p.weight()); + } + @Override + public void visit(VGlass g) { + gSum += g.weight(); + System.out.println("weight of Glass = " + + g.weight()); + } + @Override + public void visit(VCardboard c) { + cSum += c.weight(); + System.out.println("weight of Cardboard = " + + c.weight()); + } + void total() { + System.out.println("Total weight Aluminum:" + + alSum); + System.out.println("Total weight Paper:" + + pSum); + System.out.println("Total weight Glass:" + + gSum); + System.out.println("Total weight Cardboard:" + + cSum); + } +} + +public class TrashVisitor { + public static void main(String[] args) { + ArrayList bin = new ArrayList(); + // ParseTrash still works, without changes: + ParseTrash.fillBin("VTrash.dat", bin); + // You could even iterate through + // a list of visitors! + PriceVisitor pv = new PriceVisitor(); + WeightVisitor wv = new WeightVisitor(); + Iterator it = bin.iterator(); + while(it.hasNext()) { + Visitable v = (Visitable)it.next(); + v.accept(pv); + v.accept(wv); + } + pv.total(); + wv.total(); + } +} ///:~ diff --git a/patterns/trashvisitor/VAluminum.java b/patterns/trashvisitor/VAluminum.java new file mode 100644 index 00000000..7c89f290 --- /dev/null +++ b/patterns/trashvisitor/VAluminum.java @@ -0,0 +1,13 @@ +//: patterns/trashvisitor/VAluminum.java +// Aluminum for the visitor pattern. +package patterns.trashvisitor; +import patterns.trash.*; + +public class VAluminum extends Aluminum + implements Visitable { + public VAluminum(double wt) { super(wt); } + @Override + public void accept(Visitor v) { + v.visit(this); + } +} ///:~ diff --git a/patterns/trashvisitor/VCardboard.java b/patterns/trashvisitor/VCardboard.java new file mode 100644 index 00000000..7ef0829a --- /dev/null +++ b/patterns/trashvisitor/VCardboard.java @@ -0,0 +1,13 @@ +//: patterns/trashvisitor/VCardboard.java +// Cardboard for the visitor pattern. +package patterns.trashvisitor; +import patterns.trash.*; + +public class VCardboard extends Cardboard + implements Visitable { + public VCardboard(double wt) { super(wt); } + @Override + public void accept(Visitor v) { + v.visit(this); + } +} ///:~ diff --git a/patterns/trashvisitor/VGlass.java b/patterns/trashvisitor/VGlass.java new file mode 100644 index 00000000..9b5e325b --- /dev/null +++ b/patterns/trashvisitor/VGlass.java @@ -0,0 +1,13 @@ +//: patterns/trashvisitor/VGlass.java +// Glass for the visitor pattern. +package patterns.trashvisitor; +import patterns.trash.*; + +public class VGlass extends Glass + implements Visitable { + public VGlass(double wt) { super(wt); } + @Override + public void accept(Visitor v) { + v.visit(this); + } +} ///:~ diff --git a/patterns/trashvisitor/VPaper.java b/patterns/trashvisitor/VPaper.java new file mode 100644 index 00000000..17089373 --- /dev/null +++ b/patterns/trashvisitor/VPaper.java @@ -0,0 +1,13 @@ +//: patterns/trashvisitor/VPaper.java +// Paper for the visitor pattern. +package patterns.trashvisitor; +import patterns.trash.*; + +public class VPaper extends Paper + implements Visitable { + public VPaper(double wt) { super(wt); } + @Override + public void accept(Visitor v) { + v.visit(this); + } +} ///:~ diff --git a/patterns/trashvisitor/VTrash.dat b/patterns/trashvisitor/VTrash.dat new file mode 100644 index 00000000..bcde40b6 --- /dev/null +++ b/patterns/trashvisitor/VTrash.dat @@ -0,0 +1,35 @@ +patterns.trashvisitor.VGlass:54 +patterns.trashvisitor.VPaper:22 +patterns.trashvisitor.VPaper:11 +patterns.trashvisitor.VGlass:17 +patterns.trashvisitor.VAluminum:89 +patterns.trashvisitor.VPaper:88 +patterns.trashvisitor.VAluminum:76 +patterns.trashvisitor.VCardboard:96 +patterns.trashvisitor.VAluminum:25 +patterns.trashvisitor.VAluminum:34 +patterns.trashvisitor.VGlass:11 +patterns.trashvisitor.VGlass:68 +patterns.trashvisitor.VGlass:43 +patterns.trashvisitor.VAluminum:27 +patterns.trashvisitor.VCardboard:44 +patterns.trashvisitor.VAluminum:18 +patterns.trashvisitor.VPaper:91 +patterns.trashvisitor.VGlass:63 +patterns.trashvisitor.VGlass:50 +patterns.trashvisitor.VGlass:80 +patterns.trashvisitor.VAluminum:81 +patterns.trashvisitor.VCardboard:12 +patterns.trashvisitor.VGlass:12 +patterns.trashvisitor.VGlass:54 +patterns.trashvisitor.VAluminum:36 +patterns.trashvisitor.VAluminum:93 +patterns.trashvisitor.VGlass:93 +patterns.trashvisitor.VPaper:80 +patterns.trashvisitor.VGlass:36 +patterns.trashvisitor.VGlass:12 +patterns.trashvisitor.VGlass:60 +patterns.trashvisitor.VPaper:66 +patterns.trashvisitor.VAluminum:36 +patterns.trashvisitor.VCardboard:22 + diff --git a/patterns/trashvisitor/Visitable.java b/patterns/trashvisitor/Visitable.java new file mode 100644 index 00000000..ff28c7a2 --- /dev/null +++ b/patterns/trashvisitor/Visitable.java @@ -0,0 +1,11 @@ +//: patterns/trashvisitor/Visitable.java +// An interface to add visitor functionality to +// the Trash hierarchy without modifying the +// base class. +package patterns.trashvisitor; +import patterns.trash.*; + +interface Visitable { + // The new method: + void accept(Visitor v); +} ///:~ diff --git a/patterns/trashvisitor/Visitor.java b/patterns/trashvisitor/Visitor.java new file mode 100644 index 00000000..5f915ff4 --- /dev/null +++ b/patterns/trashvisitor/Visitor.java @@ -0,0 +1,11 @@ +//: patterns/trashvisitor/Visitor.java +// The base interface for visitors. +package patterns.trashvisitor; +import patterns.trash.*; + +interface Visitor { + void visit(VAluminum a); + void visit(VPaper p); + void visit(VGlass g); + void visit(VCardboard c); +} ///:~ diff --git a/patterns/visitor/BeeAndFlowers.java b/patterns/visitor/BeeAndFlowers.java new file mode 100644 index 00000000..78b0a45a --- /dev/null +++ b/patterns/visitor/BeeAndFlowers.java @@ -0,0 +1,97 @@ +//: patterns/visitor/BeeAndFlowers.java +// Demonstration of "visitor" pattern. +package patterns.visitor; +import java.util.*; + +interface Visitor { + void visit(Gladiolus g); + void visit(Renuculus r); + void visit(Chrysanthemum c); +} + +// The Flower hierarchy cannot be changed: +interface Flower { + void accept(Visitor v); +} + +class Gladiolus implements Flower { + @Override + public void accept(Visitor v) { v.visit(this);} +} + +class Renuculus implements Flower { + @Override + public void accept(Visitor v) { v.visit(this);} +} + +class Chrysanthemum implements Flower { + @Override + public void accept(Visitor v) { v.visit(this);} +} + +// Add the ability to produce a string: +class StringVal implements Visitor { + String s; + @Override + public String toString() { return s; } + @Override + public void visit(Gladiolus g) { + s = "Gladiolus"; + } + @Override + public void visit(Renuculus r) { + s = "Renuculus"; + } + @Override + public void visit(Chrysanthemum c) { + s = "Chrysanthemum"; + } +} + +// Add the ability to do "Bee" activities: +class Bee implements Visitor { + @Override + public void visit(Gladiolus g) { + System.out.println("Bee and Gladiolus"); + } + @Override + public void visit(Renuculus r) { + System.out.println("Bee and Renuculus"); + } + @Override + public void visit(Chrysanthemum c) { + System.out.println("Bee and Chrysanthemum"); + } +} + +class FlowerFactory { + public static Flower newFlower() { + switch((int)(Math.random() * 3)) { + default: + case 0: return new Gladiolus(); + case 1: return new Renuculus(); + case 2: return new Chrysanthemum(); + } + } +} + +public class BeeAndFlowers { + public static void main(String args[]) { + ArrayList flowers = new ArrayList(); + for(int i = 0; i < 10; i++) + flowers.add(FlowerFactory.newFlower()); + // It's almost as if I had added a function + // to produce a Flower string representation: + StringVal sval = new StringVal(); + Iterator it = flowers.iterator(); + while(it.hasNext()) { + ((Flower)it.next()).accept(sval); + System.out.println(sval); + } + // Perform "Bee" operation on all Flowers: + Bee bee = new Bee(); + it = flowers.iterator(); + while(it.hasNext()) + ((Flower)it.next()).accept(bee); + } +} ///:~ diff --git a/patterns/visualobserver/BoxObserver.java b/patterns/visualobserver/BoxObserver.java new file mode 100644 index 00000000..c733a4fb --- /dev/null +++ b/patterns/visualobserver/BoxObserver.java @@ -0,0 +1,90 @@ +//: patterns/visualobserver/BoxObserver.java +// Demonstration of Observer pattern using +// Java's built-in observer classes. +// {TimeOut:4000} During testing +package patterns.visualobserver; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +// You must inherit a new type of Observable: +class BoxObservable extends Observable { + @Override + public void notifyObservers(Object b) { + // Otherwise it won't propagate changes: + setChanged(); + super.notifyObservers(b); + } +} + +public class BoxObserver extends JFrame { + Observable notifier = new BoxObservable(); + public BoxObserver(int grid) { + setTitle("Demonstrates Observer pattern"); + Container cp = getContentPane(); + cp.setLayout(new GridLayout(grid, grid)); + for(int x = 0; x < grid; x++) + for(int y = 0; y < grid; y++) + cp.add(new OCBox(x, y, notifier)); + } + public static void main(String[] args) { + int grid = 8; + if(args.length > 0) + grid = Integer.parseInt(args[0]); + JFrame f = new BoxObserver(grid); + f.setSize(500, 400); + f.setVisible(true); + f.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + } +} + +class OCBox extends JPanel implements Observer { + Observable notifier; + int x, y; // Locations in grid + Color cColor = newColor(); + static final Color[] colors = { + Color.black, Color.blue, Color.cyan, + Color.darkGray, Color.gray, Color.green, + Color.lightGray, Color.magenta, + Color.orange, Color.pink, Color.red, + Color.white, Color.yellow + }; + static final Color newColor() { + return colors[ + (int)(Math.random() * colors.length) + ]; + } + OCBox(int x, int y, Observable notifier) { + this.x = x; + this.y = y; + notifier.addObserver(this); + this.notifier = notifier; + addMouseListener(new ML()); + } + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + g.setColor(cColor); + Dimension s = getSize(); + g.fillRect(0, 0, s.width, s.height); + } + class ML extends MouseAdapter { + @Override + public void mousePressed(MouseEvent e) { + notifier.notifyObservers(OCBox.this); + } + } + @Override + public void update(Observable o, Object arg) { + OCBox clicked = (OCBox)arg; + if(nextTo(clicked)) { + cColor = clicked.cColor; + repaint(); + } + } + private final boolean nextTo(OCBox b) { + return Math.abs(x - b.x) <= 1 && + Math.abs(y - b.y) <= 1; + } +} ///:~ diff --git a/polymorphism/CovariantReturn.java b/polymorphism/CovariantReturn.java index 78f27488..12e9fb92 100644 --- a/polymorphism/CovariantReturn.java +++ b/polymorphism/CovariantReturn.java @@ -1,10 +1,12 @@ //: polymorphism/CovariantReturn.java class Grain { + @Override public String toString() { return "Grain"; } } class Wheat extends Grain { + @Override public String toString() { return "Wheat"; } } @@ -13,6 +15,7 @@ class Mill { } class WheatMill extends Mill { + @Override Wheat process() { return new Wheat(); } } diff --git a/polymorphism/FieldAccess.java b/polymorphism/FieldAccess.java index 4f3b4854..576ee593 100644 --- a/polymorphism/FieldAccess.java +++ b/polymorphism/FieldAccess.java @@ -8,6 +8,7 @@ class Super { class Sub extends Super { public int field = 1; + @Override public int getField() { return field; } public int getSuperField() { return super.field; } } diff --git a/polymorphism/Frog.java b/polymorphism/Frog.java index da614bc0..c2f19f60 100644 --- a/polymorphism/Frog.java +++ b/polymorphism/Frog.java @@ -46,6 +46,7 @@ class Animal extends LivingCreature { private Description t = new Description("Animal not Vegetable"); Animal() { print("Animal()"); } + @Override protected void dispose() { print("Animal dispose"); t.dispose(); @@ -62,6 +63,7 @@ class Amphibian extends Animal { Amphibian() { print("Amphibian()"); } + @Override protected void dispose() { print("Amphibian dispose"); t.dispose(); @@ -74,6 +76,7 @@ public class Frog extends Amphibian { private Characteristic p = new Characteristic("Croaks"); private Description t = new Description("Eats Bugs"); public Frog() { print("Frog()"); } + @Override protected void dispose() { print("Frog dispose"); t.dispose(); diff --git a/polymorphism/PolyConstructors.java b/polymorphism/PolyConstructors.java index 39a29786..76238cf9 100644 --- a/polymorphism/PolyConstructors.java +++ b/polymorphism/PolyConstructors.java @@ -18,6 +18,7 @@ class RoundGlyph extends Glyph { radius = r; print("RoundGlyph.RoundGlyph(), radius = " + radius); } + @Override void draw() { print("RoundGlyph.draw(), radius = " + radius); } diff --git a/polymorphism/RTTI.java b/polymorphism/RTTI.java index 01b6bed3..798ef8db 100644 --- a/polymorphism/RTTI.java +++ b/polymorphism/RTTI.java @@ -8,7 +8,9 @@ class Useful { } class MoreUseful extends Useful { + @Override public void f() {} + @Override public void g() {} public void u() {} public void v() {} diff --git a/polymorphism/ReferenceCounting.java b/polymorphism/ReferenceCounting.java index c1bbbcf8..238cc8da 100644 --- a/polymorphism/ReferenceCounting.java +++ b/polymorphism/ReferenceCounting.java @@ -14,6 +14,7 @@ class Shared { if(--refcount == 0) print("Disposing " + this); } + @Override public String toString() { return "Shared " + id; } } @@ -30,6 +31,7 @@ class Composing { print("disposing " + this); shared.dispose(); } + @Override public String toString() { return "Composing " + id; } } diff --git a/polymorphism/StaticPolymorphism.java b/polymorphism/StaticPolymorphism.java index 1101d733..3a699528 100644 --- a/polymorphism/StaticPolymorphism.java +++ b/polymorphism/StaticPolymorphism.java @@ -14,6 +14,7 @@ class StaticSub extends StaticSuper { public static String staticGet() { return "Derived staticGet()"; } + @Override public String dynamicGet() { return "Derived dynamicGet()"; } diff --git a/polymorphism/Transmogrify.java b/polymorphism/Transmogrify.java index bc760f68..8e41fb4f 100644 --- a/polymorphism/Transmogrify.java +++ b/polymorphism/Transmogrify.java @@ -8,10 +8,12 @@ class Actor { } class HappyActor extends Actor { + @Override public void act() { print("HappyActor"); } } class SadActor extends Actor { + @Override public void act() { print("SadActor"); } } diff --git a/polymorphism/build.xml b/polymorphism/build.xml new file mode 100644 index 00000000..5ec52f5f --- /dev/null +++ b/polymorphism/build.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/polymorphism/music/Music2.java b/polymorphism/music/Music2.java index 955c2038..b122e373 100644 --- a/polymorphism/music/Music2.java +++ b/polymorphism/music/Music2.java @@ -4,12 +4,14 @@ package polymorphism.music; import static net.mindview.util.Print.*; class Stringed extends Instrument { + @Override public void play(Note n) { print("Stringed.play() " + n); } } class Brass extends Instrument { + @Override public void play(Note n) { print("Brass.play() " + n); } diff --git a/polymorphism/music/Wind.java b/polymorphism/music/Wind.java index 77847d44..b8285bf8 100644 --- a/polymorphism/music/Wind.java +++ b/polymorphism/music/Wind.java @@ -5,6 +5,7 @@ package polymorphism.music; // because they have the same interface: public class Wind extends Instrument { // Redefine interface method: + @Override public void play(Note n) { System.out.println("Wind.play() " + n); } diff --git a/polymorphism/music3/Music3.java b/polymorphism/music3/Music3.java index 27525c87..bcc784ea 100644 --- a/polymorphism/music3/Music3.java +++ b/polymorphism/music3/Music3.java @@ -11,30 +11,43 @@ class Instrument { } class Wind extends Instrument { + @Override void play(Note n) { print("Wind.play() " + n); } + @Override String what() { return "Wind"; } + @Override void adjust() { print("Adjusting Wind"); } } class Percussion extends Instrument { + @Override void play(Note n) { print("Percussion.play() " + n); } + @Override String what() { return "Percussion"; } + @Override void adjust() { print("Adjusting Percussion"); } } class Stringed extends Instrument { + @Override void play(Note n) { print("Stringed.play() " + n); } + @Override String what() { return "Stringed"; } + @Override void adjust() { print("Adjusting Stringed"); } } class Brass extends Wind { + @Override void play(Note n) { print("Brass.play() " + n); } + @Override void adjust() { print("Adjusting Brass"); } } class Woodwind extends Wind { + @Override void play(Note n) { print("Woodwind.play() " + n); } + @Override String what() { return "Woodwind"; } } diff --git a/polymorphism/shape/Circle.java b/polymorphism/shape/Circle.java index ff546325..63ca5122 100644 --- a/polymorphism/shape/Circle.java +++ b/polymorphism/shape/Circle.java @@ -3,6 +3,8 @@ package polymorphism.shape; import static net.mindview.util.Print.*; public class Circle extends Shape { + @Override public void draw() { print("Circle.draw()"); } + @Override public void erase() { print("Circle.erase()"); } } ///:~ diff --git a/polymorphism/shape/Square.java b/polymorphism/shape/Square.java index 1b5c50b1..1514d3e7 100644 --- a/polymorphism/shape/Square.java +++ b/polymorphism/shape/Square.java @@ -3,6 +3,8 @@ package polymorphism.shape; import static net.mindview.util.Print.*; public class Square extends Shape { + @Override public void draw() { print("Square.draw()"); } + @Override public void erase() { print("Square.erase()"); } } ///:~ diff --git a/polymorphism/shape/Triangle.java b/polymorphism/shape/Triangle.java index 58ec072b..65576493 100644 --- a/polymorphism/shape/Triangle.java +++ b/polymorphism/shape/Triangle.java @@ -3,6 +3,8 @@ package polymorphism.shape; import static net.mindview.util.Print.*; public class Triangle extends Shape { + @Override public void draw() { print("Triangle.draw()"); } + @Override public void erase() { print("Triangle.erase()"); } } ///:~ diff --git a/references/AddingClone.java b/references/AddingClone.java new file mode 100644 index 00000000..0d446fdc --- /dev/null +++ b/references/AddingClone.java @@ -0,0 +1,54 @@ +//: references/AddingClone.java +// You must go through a few gyrations +// to add cloning to your own class. +import java.util.*; + +class Int2 implements Cloneable { + private int i; + public Int2(int ii) { i = ii; } + public void increment() { i++; } + @Override + public String toString() { return Integer.toString(i); } + @Override + public Object clone() { + Object o = null; + try { + o = super.clone(); + } catch(CloneNotSupportedException e) { + System.err.println("Int2 can't clone"); + } + return o; + } +} + +// Inheritance doesn't remove cloneability: +class Int3 extends Int2 { + private int j; // Automatically duplicated + public Int3(int i) { super(i); } +} + +public class AddingClone { + public static void main(String[] args) { + Int2 x = new Int2(10); + Int2 x2 = (Int2)x.clone(); + x2.increment(); + System.out.println("x = " + x + ", x2 = " + x2); + // Anything inherited is also cloneable: + Int3 x3 = new Int3(7); + x3 = (Int3)x3.clone(); + ArrayList v = new ArrayList(); + for(int i = 0; i < 10; i++ ) + v.add(new Int2(i)); + System.out.println("v: " + v); + ArrayList v2 = (ArrayList)v.clone(); + // Now clone each element: + for(int i = 0; i < v.size(); i++) + v2.set(i, ((Int2)v2.get(i)).clone()); + // Increment all v2's elements: + for(Iterator e = v2.iterator(); e.hasNext(); ) + ((Int2)e.next()).increment(); + System.out.println("v2: " + v2); + // See if it changed v's elements: + System.out.println("v: " + v); + } +} ///:~ diff --git a/references/Alias1.java b/references/Alias1.java new file mode 100644 index 00000000..d1e4998a --- /dev/null +++ b/references/Alias1.java @@ -0,0 +1,17 @@ +//: references/Alias1.java +// 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 + System.out.println("x: " + x.i); + System.out.println("y: " + y.i); + System.out.println("Incrementing x"); + x.i++; + System.out.println("x: " + x.i); + System.out.println("y: " + y.i); + } +} ///:~ diff --git a/references/Alias2.java b/references/Alias2.java new file mode 100644 index 00000000..b0ee0778 --- /dev/null +++ b/references/Alias2.java @@ -0,0 +1,15 @@ +//: references/Alias2.java +// 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 static void main(String[] args) { + Alias2 x = new Alias2(7); + System.out.println("x: " + x.i); + System.out.println("Calling f(x)"); + f(x); + System.out.println("x: " + x.i); + } +} ///:~ diff --git a/references/CheckCloneable.java b/references/CheckCloneable.java new file mode 100644 index 00000000..0f10b954 --- /dev/null +++ b/references/CheckCloneable.java @@ -0,0 +1,90 @@ +//: references/CheckCloneable.java +// Checking to see if a reference can be cloned. + +// Can't clone this because it doesn't override clone(): +class Ordinary {} + +// Overrides clone, but doesn't implement Cloneable: +class WrongClone extends Ordinary { + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); // Throws exception + } +} + +// Does all the right things for cloning: +class IsCloneable extends Ordinary implements Cloneable { + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} + +// Turn off cloning by throwing the exception: +class NoMore extends IsCloneable { + @Override + public Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + } +} + +class TryMore extends NoMore { + @Override + public Object clone() throws CloneNotSupportedException { + // Calls NoMore.clone(), throws exception: + return super.clone(); + } +} + +class BackOn extends NoMore { + private BackOn duplicate(BackOn b) { + // Somehow make a copy of b and return that copy. + // This is a dummy copy, just to make the point: + return new BackOn(); + } + @Override + public Object clone() { + // Doesn't call NoMore.clone(): + return duplicate(this); + } +} + +// You can't inherit from this, so you can't override +// the clone method as you can in BackOn: +final class ReallyNoMore extends NoMore {} + +public class CheckCloneable { + public static Ordinary tryToClone(Ordinary ord) { + String id = ord.getClass().getName(); + System.out.println("Attempting " + id); + Ordinary x = null; + if(ord instanceof Cloneable) { + try { + x = (Ordinary)((IsCloneable)ord).clone(); + System.out.println("Cloned " + id); + } catch(CloneNotSupportedException e) { + System.err.println("Could not clone " + id); + } + } else { + System.out.println("Doesn't implement Cloneable"); + } + return x; + } + public static void main(String[] args) { + // Upcasting: + Ordinary[] ord = { + new IsCloneable(), + new WrongClone(), + new NoMore(), + new TryMore(), + new BackOn(), + new ReallyNoMore(), + }; + Ordinary x = new Ordinary(); + // This won't compile; clone() is protected in Object: + //! x = (Ordinary)x.clone(); + // Checks first to see if a class implements Cloneable: + for(int i = 0; i < ord.length; i++) + tryToClone(ord[i]); + } +} ///:~ diff --git a/references/Cloning.java b/references/Cloning.java new file mode 100644 index 00000000..bfeb7428 --- /dev/null +++ b/references/Cloning.java @@ -0,0 +1,28 @@ +//: references/Cloning.java +// The clone() operation works for only a few +// items in the standard Java library. +import java.util.*; + +class Int { + private int i; + public Int(int ii) { i = ii; } + public void increment() { i++; } + @Override + public String toString() { return Integer.toString(i); } +} + +public class Cloning { + public static void main(String[] args) { + ArrayList v = new ArrayList(); + for(int i = 0; i < 10; i++ ) + v.add(new Int(i)); + System.out.println("v: " + v); + ArrayList v2 = (ArrayList)v.clone(); + // Increment all v2's elements: + for(Iterator e = v2.iterator(); + e.hasNext(); ) + ((Int)e.next()).increment(); + // See if it changed v's elements: + System.out.println("v: " + v); + } +} ///:~ diff --git a/references/Compete.java b/references/Compete.java new file mode 100644 index 00000000..0689c266 --- /dev/null +++ b/references/Compete.java @@ -0,0 +1,70 @@ +//: references/Compete.java +import java.io.*; + +class Thing1 implements Serializable {} +class Thing2 implements Serializable { + Thing1 o1 = new Thing1(); +} + +class Thing3 implements Cloneable { + @Override + public Object clone() { + Object o = null; + try { + o = super.clone(); + } catch(CloneNotSupportedException e) { + System.err.println("Thing3 can't clone"); + } + return o; + } +} + +class Thing4 implements Cloneable { + private Thing3 o3 = new Thing3(); + @Override + public Object clone() { + Thing4 o = null; + try { + o = (Thing4)super.clone(); + } catch(CloneNotSupportedException e) { + System.err.println("Thing4 can't clone"); + } + // Clone the field, too: + o.o3 = (Thing3)o3.clone(); + return o; + } +} + +public class Compete { + public static final int SIZE = 25000; + public static void main(String[] args) throws Exception { + Thing2[] a = new Thing2[SIZE]; + for(int i = 0; i < a.length; i++) + a[i] = new Thing2(); + Thing4[] b = new Thing4[SIZE]; + for(int i = 0; i < b.length; i++) + b[i] = new Thing4(); + long t1 = System.currentTimeMillis(); + ByteArrayOutputStream buf= new ByteArrayOutputStream(); + ObjectOutputStream o = new ObjectOutputStream(buf); + for(int i = 0; i < a.length; i++) + o.writeObject(a[i]); + // 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(); + t2 = System.currentTimeMillis(); + System.out.println("Duplication via cloning: " + + (t2 - t1) + " Milliseconds"); + } +} ///:~ diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java new file mode 100644 index 00000000..38900388 --- /dev/null +++ b/references/CopyConstructor.java @@ -0,0 +1,152 @@ +//: references/CopyConstructor.java +// A constructor for copying an object of the same +// type, as an attempt to create a local copy. +import java.lang.reflect.*; + +class FruitQualities { + private int weight; + private int color; + private int firmness; + private int ripeness; + private int smell; + // etc. + public FruitQualities() { // Default constructor + // Do something meaningful... + } + // Other constructors: + // ... + // Copy constructor: + public FruitQualities(FruitQualities f) { + weight = f.weight; + color = f.color; + firmness = f.firmness; + ripeness = f.ripeness; + smell = f.smell; + // etc. + } +} + +class Seed { + // Members... + public Seed() { /* Default constructor */ } + public Seed(Seed s) { /* Copy constructor */ } +} + +class Fruit { + private FruitQualities fq; + private int seeds; + private Seed[] s; + public Fruit(FruitQualities q, int seedCount) { + fq = q; + seeds = seedCount; + s = new Seed[seeds]; + for(int i = 0; i < seeds; i++) + s[i] = new Seed(); + } + // Other constructors: + // ... + // Copy constructor: + public Fruit(Fruit f) { + fq = new FruitQualities(f.fq); + seeds = f.seeds; + s = new Seed[seeds]; + // Call all Seed copy-constructors: + for(int i = 0; i < seeds; i++) + s[i] = new Seed(f.s[i]); + // Other copy-construction activities... + } + // To allow derived constructors (or other + // methods) to put in different qualities: + protected void addQualities(FruitQualities q) { + fq = q; + } + protected FruitQualities getQualities() { + return fq; + } +} + +class Tomato extends Fruit { + public Tomato() { + super(new FruitQualities(), 100); + } + public Tomato(Tomato t) { // Copy-constructor + super(t); // Upcast for base copy-constructor + // Other copy-construction activities... + } +} + +class ZebraQualities extends FruitQualities { + private int stripedness; + public ZebraQualities() { // Default constructor + super(); + // do something meaningful... + } + public ZebraQualities(ZebraQualities z) { + super(z); + stripedness = z.stripedness; + } +} + +class GreenZebra extends Tomato { + public GreenZebra() { + addQualities(new ZebraQualities()); + } + public GreenZebra(GreenZebra g) { + super(g); // Calls Tomato(Tomato) + // Restore the right qualities: + addQualities(new ZebraQualities()); + } + public void evaluate() { + ZebraQualities zq = (ZebraQualities)getQualities(); + // Do something with the qualities + // ... + } +} + +public class CopyConstructor { + public static void ripen(Tomato t) { + // Use the "copy constructor": + t = new Tomato(t); + 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? + System.out.println("In slice, f is a " + + f.getClass().getName()); + } + public static void ripen2(Tomato t) { + try { + Class c = t.getClass(); + // Use the "copy constructor": + Constructor ct = c.getConstructor(new Class[] { c }); + Object obj = ct.newInstance(new Object[] { t }); + System.out.println("In ripen2, t is a " + + obj.getClass().getName()); + } + catch(Exception e) { System.out.println(e); } + } + public static void slice2(Fruit f) { + try { + Class c = f.getClass(); + Constructor ct = c.getConstructor(new Class[] { c }); + Object obj = ct.newInstance(new Object[] { f }); + System.out.println("In slice2, f is a " + + obj.getClass().getName()); + } + catch(Exception e) { System.out.println(e); } + } + public static void main(String[] args) { + Tomato tomato = new Tomato(); + ripen(tomato); // OK + slice(tomato); // OOPS! + ripen2(tomato); // OK + slice2(tomato); // OK + GreenZebra g = new GreenZebra(); + ripen(g); // OOPS! + slice(g); // OOPS! + ripen2(g); // OK + slice2(g); // OK + g.evaluate(); + } +} ///:~ diff --git a/references/DeepCopy.java b/references/DeepCopy.java new file mode 100644 index 00000000..a2c19422 --- /dev/null +++ b/references/DeepCopy.java @@ -0,0 +1,111 @@ +//: references/DeepCopy.java +// Cloning a composed object. +// {Depends: junit.jar} +import org.junit.Test; +import org.junit.Assert.*; + +class DepthReading implements Cloneable { + private double depth; + public DepthReading(double depth) { this.depth = depth; } + @Override + public Object clone() { + Object o = null; + try { + o = super.clone(); + } catch(CloneNotSupportedException e) { + e.printStackTrace(); + } + return o; + } + public double getDepth() { return depth; } + public void setDepth(double depth){ this.depth = depth; } + @Override + public String toString() { return String.valueOf(depth);} +} + +class TemperatureReading implements Cloneable { + private long time; + private double temperature; + public TemperatureReading(double temperature) { + time = System.currentTimeMillis(); + this.temperature = temperature; + } + @Override + public Object clone() { + Object o = null; + try { + o = super.clone(); + } catch(CloneNotSupportedException e) { + e.printStackTrace(); + } + return o; + } + public double getTemperature() { return temperature; } + public void setTemperature(double temperature) { + this.temperature = temperature; + } + @Override + public String toString() { + return String.valueOf(temperature); + } +} + +class OceanReading implements Cloneable { + private DepthReading depth; + private TemperatureReading temperature; + public OceanReading(double tdata, double ddata) { + temperature = new TemperatureReading(tdata); + depth = new DepthReading(ddata); + } + @Override + public Object clone() { + OceanReading o = null; + try { + o = (OceanReading)super.clone(); + } catch(CloneNotSupportedException e) { + e.printStackTrace(); + } + // Must clone references: + o.depth = (DepthReading)o.depth.clone(); + o.temperature = + (TemperatureReading)o.temperature.clone(); + return o; // Upcasts back to Object + } + public TemperatureReading getTemperatureReading() { + return temperature; + } + public void setTemperatureReading(TemperatureReading tr){ + temperature = tr; + } + public DepthReading getDepthReading() { return depth; } + public void setDepthReading(DepthReading dr) { + this.depth = dr; + } + @Override + public String toString() { + return "temperature: " + temperature + + ", depth: " + depth; + } +} + +public class DeepCopy { + @Test + public void testClone() { + OceanReading reading = new OceanReading(33.9, 100.5); + // Now clone it: + OceanReading clone = (OceanReading)reading.clone(); + TemperatureReading tr = clone.getTemperatureReading(); + tr.setTemperature(tr.getTemperature() + 1); + clone.setTemperatureReading(tr); + DepthReading dr = clone.getDepthReading(); + dr.setDepth(dr.getDepth() + 1); + clone.setDepthReading(dr); + org.junit.Assert.assertEquals(reading.toString(), + "temperature: 33.9, depth: 100.5"); + org.junit.Assert.assertEquals(clone.toString(), + "temperature: 34.9, depth: 101.5"); + } + public static void main(String[] args) { + org.junit.runner.JUnitCore.runClasses(DeepCopy.class); + } +} ///:~ diff --git a/references/HorrorFlick.java b/references/HorrorFlick.java new file mode 100644 index 00000000..f7a450df --- /dev/null +++ b/references/HorrorFlick.java @@ -0,0 +1,30 @@ +//: references/HorrorFlick.java +// You can insert Cloneability at any level of inheritance. +import java.util.*; + +class Person {} +class Hero extends Person {} +class Scientist extends Person implements Cloneable { + public Object clone() { + try { + return super.clone(); + } catch(CloneNotSupportedException e) { + // This should never happen: It's Cloneable already! + throw new RuntimeException(e); + } + } +} +class MadScientist extends Scientist {} + +public class HorrorFlick { + public static void main(String[] args) { + Person p = new Person(); + Hero h = new Hero(); + Scientist s = new Scientist(); + MadScientist m = new MadScientist(); + //! p = (Person)p.clone(); // Compile error + //! h = (Hero)h.clone(); // Compile error + s = (Scientist)s.clone(); + m = (MadScientist)m.clone(); + } +} ///:~ diff --git a/references/Immutable1.java b/references/Immutable1.java new file mode 100644 index 00000000..e8d0b1d8 --- /dev/null +++ b/references/Immutable1.java @@ -0,0 +1,25 @@ +//: references/Immutable1.java +// Objects that cannot be modified are immune to aliasing. + +public class Immutable1 { + private int data; + public Immutable1(int initVal) { + data = initVal; + } + public int read() { return data; } + public boolean nonzero() { return data != 0; } + public Immutable1 multiply(int multiplier) { + return new Immutable1(data * multiplier); + } + public static void f(Immutable1 i1) { + Immutable1 quad = i1.multiply(4); + System.out.println("i1 = " + i1.read()); + System.out.println("quad = " + quad.read()); + } + public static void main(String[] args) { + Immutable1 x = new Immutable1(47); + System.out.println("x = " + x.read()); + f(x); + System.out.println("x = " + x.read()); + } +} ///:~ diff --git a/references/Immutable2.java b/references/Immutable2.java new file mode 100644 index 00000000..1820f1db --- /dev/null +++ b/references/Immutable2.java @@ -0,0 +1,55 @@ +//: references/Immutable2.java +// A companion class to modify immutable objects. + +class Mutable { + private int data; + public Mutable(int initVal) { data = initVal; } + public Mutable add(int x) { + data += x; + return this; + } + public Mutable multiply(int x) { + data *= x; + return this; + } + public Immutable2 makeImmutable2() { + return new Immutable2(data); + } +} + +public class Immutable2 { + private int data; + public Immutable2(int initVal) { data = initVal; } + public int read() { return data; } + public boolean nonzero() { return data != 0; } + public Immutable2 add(int x) { + return new Immutable2(data + x); + } + public Immutable2 multiply(int x) { + return new Immutable2(data * x); + } + public Mutable makeMutable() { + return new Mutable(data); + } + public static Immutable2 modify1(Immutable2 y) { + Immutable2 val = y.add(12); + val = val.multiply(3); + val = val.add(11); + val = val.multiply(2); + return val; + } + // This produces the same result: + public static Immutable2 modify2(Immutable2 y) { + Mutable m = y.makeMutable(); + m.add(12).multiply(3).add(11).multiply(2); + return m.makeImmutable2(); + } + public static void main(String[] args) { + Immutable2 i2 = new Immutable2(47); + Immutable2 r1 = modify1(i2); + Immutable2 r2 = modify2(i2); + System.out.println("i2 = " + i2.read()); + System.out.println("r1 = " + r1.read()); + System.out.println("r2 = " + r2.read()); + } +} ///:~ diff --git a/references/ImmutableInteger.java b/references/ImmutableInteger.java new file mode 100644 index 00000000..ce0a2af6 --- /dev/null +++ b/references/ImmutableInteger.java @@ -0,0 +1,12 @@ +//: references/ImmutableInteger.java +// The Integer class cannot be changed. +import java.util.*; + +public class ImmutableInteger { + public static void main(String[] args) { + List v = new ArrayList(); + for(int i = 0; i < 10; i++) + v.add(new Integer(i)); + // But how do you change the int inside the Integer? + } +} ///:~ diff --git a/references/ImmutableStrings.java b/references/ImmutableStrings.java new file mode 100644 index 00000000..2eeac760 --- /dev/null +++ b/references/ImmutableStrings.java @@ -0,0 +1,17 @@ +//: references/ImmutableStrings.java +// Demonstrating StringBuffer. + +public class ImmutableStrings { + public static void main(String[] args) { + String foo = "foo"; + String s = "abc" + foo + "def" + Integer.toString(47); + System.out.println(s); + // The "equivalent" using StringBuffer: + StringBuffer sb = + new StringBuffer("abc"); // Creates String! + sb.append(foo); + sb.append("def"); // Creates String! + sb.append(Integer.toString(47)); + System.out.println(sb); + } +} ///:~ diff --git a/references/LocalCopy.java b/references/LocalCopy.java new file mode 100644 index 00000000..2dd5c8f8 --- /dev/null +++ b/references/LocalCopy.java @@ -0,0 +1,47 @@ +//: references/LocalCopy.java +// Creating local copies with clone(). +import java.util.*; + +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); + } +} ///:~ diff --git a/references/MutableInteger.java b/references/MutableInteger.java new file mode 100644 index 00000000..f431bab1 --- /dev/null +++ b/references/MutableInteger.java @@ -0,0 +1,25 @@ +//: references/MutableInteger.java +// A changeable wrapper class. +import java.util.*; + +class IntValue { + private int n; + public IntValue(int x) { n = x; } + 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 MutableInteger { + public static void main(String[] args) { + List v = new ArrayList(); + for(int i = 0; i < 10; i++) + v.add(new IntValue(i)); + System.out.println(v); + for(int i = 0; i < v.size(); i++) + ((IntValue)v.get(i)).increment(); + System.out.println(v); + } +} ///:~ diff --git a/references/PassReferences.java b/references/PassReferences.java new file mode 100644 index 00000000..de153d5d --- /dev/null +++ b/references/PassReferences.java @@ -0,0 +1,13 @@ +//: references/PassReferences.java +// Passing references around. + +public class PassReferences { + public static void f(PassReferences h) { + System.out.println("h inside f(): " + h); + } + public static void main(String[] args) { + PassReferences p = new PassReferences(); + System.out.println("p inside main(): " + p); + f(p); + } +} ///:~ diff --git a/references/Snake.java b/references/Snake.java new file mode 100644 index 00000000..ac171a99 --- /dev/null +++ b/references/Snake.java @@ -0,0 +1,44 @@ +//: references/Snake.java +// Tests cloning to see if destination +// of references are also cloned. + +public class Snake implements Cloneable { + private Snake next; + private char c; + // Value of i == number of segments + public Snake(int i, char x) { + c = x; + if(--i > 0) + next = new Snake(i, (char)(x + 1)); + } + public void increment() { + c++; + if(next != null) + next.increment(); + } + @Override + public String toString() { + String s = ":" + c; + if(next != null) + s += next.toString(); + return s; + } + @Override + public Object clone() { + Object o = null; + try { + o = super.clone(); + } catch(CloneNotSupportedException e) { + System.err.println("Snake can't clone"); + } + return o; + } + public static void main(String[] args) { + Snake s = new Snake(5, 'a'); + System.out.println("s = " + s); + Snake s2 = (Snake)s.clone(); + System.out.println("s2 = " + s2); + s.increment(); + System.out.println("after s.increment, s2 = " + s2); + } +} ///:~ diff --git a/references/Stringer.java b/references/Stringer.java new file mode 100644 index 00000000..8b9a261a --- /dev/null +++ b/references/Stringer.java @@ -0,0 +1,14 @@ +//: references/Stringer.java + +public class Stringer { + public static String upcase(String s) { + return s.toUpperCase(); + } + public static void main(String[] args) { + String q = new String("howdy"); + System.out.println(q); // howdy + String qq = upcase(q); + System.out.println(qq); // HOWDY + System.out.println(q); // howdy + } +} ///:~ diff --git a/references/build.xml b/references/build.xml new file mode 100644 index 00000000..2da6f359 --- /dev/null +++ b/references/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/remote/build.xml b/remote/build.xml new file mode 100644 index 00000000..94da2ef0 --- /dev/null +++ b/remote/build.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/remote/ptime/DisplayPerfectTime.java b/remote/ptime/DisplayPerfectTime.java new file mode 100644 index 00000000..dbcca4a8 --- /dev/null +++ b/remote/ptime/DisplayPerfectTime.java @@ -0,0 +1,22 @@ +//: remote/ptime/DisplayPerfectTime.java +// Uses remote object PerfectTime +// {RunByHand} +package remote.ptime; +import java.rmi.*; +import java.rmi.registry.*; + +public class DisplayPerfectTime { + public static void main(String[] args) { + System.setSecurityManager(new SecurityManager()); + try { + PerfectTimeI t = + (PerfectTimeI)Naming.lookup( + "//MindviewToshibaLaptop:2005/PerfectTime"); + for(int i = 0; i < 10; i++) + System.out.println("Perfect time = " + + t.getPerfectTime()); + } catch(Exception e) { + e.printStackTrace(); + } + } +} ///:~ diff --git a/remote/ptime/PerfectTime.java b/remote/ptime/PerfectTime.java new file mode 100644 index 00000000..09630725 --- /dev/null +++ b/remote/ptime/PerfectTime.java @@ -0,0 +1,37 @@ +//: remote/ptime/PerfectTime.java +// The implementation of the PerfectTime +// remote object. +// {RunByHand} +package remote.ptime; +import java.rmi.*; +import java.rmi.server.*; +import java.rmi.registry.*; +import java.net.*; + +public class PerfectTime + extends UnicastRemoteObject + implements PerfectTimeI { + // Implementation of the interface: + @Override + public long getPerfectTime() + throws RemoteException { + return System.currentTimeMillis(); + } + // Must implement constructor to throw + // RemoteException: + public PerfectTime() throws RemoteException { + // super(); // Called automatically + } + // Registration for RMI serving: + public static void main(String[] args) { + System.setSecurityManager(new SecurityManager()); + try { + PerfectTime pt = new PerfectTime(); + Naming.bind( + "//MindviewToshibaLaptop:2005/PerfectTime", pt); + System.out.println("Ready to do time"); + } catch(Exception e) { + e.printStackTrace(); + } + } +} ///:~ diff --git a/remote/ptime/PerfectTimeI.java b/remote/ptime/PerfectTimeI.java new file mode 100644 index 00000000..06501267 --- /dev/null +++ b/remote/ptime/PerfectTimeI.java @@ -0,0 +1,8 @@ +//: remote/ptime/PerfectTimeI.java +// The PerfectTime remote interface +package remote.ptime; +import java.rmi.*; + +interface PerfectTimeI extends Remote { + long getPerfectTime() throws RemoteException; +} ///:~ diff --git a/reusing/Bath.java b/reusing/Bath.java index a5329ab1..98e3eb6e 100644 --- a/reusing/Bath.java +++ b/reusing/Bath.java @@ -8,6 +8,7 @@ class Soap { print("Soap()"); s = "Constructed"; } + @Override public String toString() { return s; } } @@ -27,6 +28,7 @@ public class Bath { } // Instance initialization: { i = 47; } + @Override public String toString() { if(s4 == null) // Delayed initialization: s4 = "Joy"; diff --git a/reusing/CADSystem.java b/reusing/CADSystem.java index 762b1353..9a022fbf 100644 --- a/reusing/CADSystem.java +++ b/reusing/CADSystem.java @@ -13,6 +13,7 @@ class Circle extends Shape { super(i); print("Drawing Circle"); } + @Override void dispose() { print("Erasing Circle"); super.dispose(); @@ -24,6 +25,7 @@ class Triangle extends Shape { super(i); print("Drawing Triangle"); } + @Override void dispose() { print("Erasing Triangle"); super.dispose(); @@ -38,6 +40,7 @@ class Line extends Shape { this.end = end; print("Drawing Line: " + start + ", " + end); } + @Override void dispose() { print("Erasing Line: " + start + ", " + end); super.dispose(); @@ -56,6 +59,7 @@ public class CADSystem extends Shape { t = new Triangle(1); print("Combined constructor"); } + @Override public void dispose() { print("CADSystem.dispose()"); // The order of cleanup is the reverse diff --git a/reusing/Detergent.java b/reusing/Detergent.java index 0ff9f966..c595b6ed 100644 --- a/reusing/Detergent.java +++ b/reusing/Detergent.java @@ -8,6 +8,7 @@ class Cleanser { public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } + @Override public String toString() { return s; } public static void main(String[] args) { Cleanser x = new Cleanser(); @@ -18,6 +19,7 @@ class Cleanser { public class Detergent extends Cleanser { // Change a method: + @Override public void scrub() { append(" Detergent.scrub()"); super.scrub(); // Call base-class version diff --git a/reusing/FinalData.java b/reusing/FinalData.java index 2325d488..34f41e33 100644 --- a/reusing/FinalData.java +++ b/reusing/FinalData.java @@ -25,6 +25,7 @@ public class FinalData { private static final Value VAL_3 = new Value(33); // Arrays: private final int[] a = { 1, 2, 3, 4, 5, 6 }; + @Override public String toString() { return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5; } diff --git a/reusing/Orc.java b/reusing/Orc.java index 4fd1f061..a2fe6510 100644 --- a/reusing/Orc.java +++ b/reusing/Orc.java @@ -6,6 +6,7 @@ class Villain { private String name; protected void set(String nm) { name = nm; } public Villain(String name) { this.name = name; } + @Override public String toString() { return "I'm a Villain and my name is " + name; } @@ -21,6 +22,7 @@ public class Orc extends Villain { set(name); // Available because it's protected this.orcNumber = orcNumber; } + @Override public String toString() { return "Orc " + orcNumber + ": " + super.toString(); } diff --git a/reusing/SpaceShip.java b/reusing/SpaceShip.java index 8a68c813..99aca2aa 100644 --- a/reusing/SpaceShip.java +++ b/reusing/SpaceShip.java @@ -3,6 +3,7 @@ public class SpaceShip extends SpaceShipControls { private String name; public SpaceShip(String name) { this.name = name; } + @Override public String toString() { return name; } public static void main(String[] args) { SpaceShip protector = new SpaceShip("NSEA Protector"); diff --git a/reusing/SprinklerSystem.java b/reusing/SprinklerSystem.java index 86bb9515..f9d62799 100644 --- a/reusing/SprinklerSystem.java +++ b/reusing/SprinklerSystem.java @@ -7,6 +7,7 @@ class WaterSource { System.out.println("WaterSource()"); s = "Constructed"; } + @Override public String toString() { return s; } } @@ -15,6 +16,7 @@ public class SprinklerSystem { private WaterSource source = new WaterSource(); private int i; private float f; + @Override public String toString() { return "valve1 = " + valve1 + " " + diff --git a/reusing/build.xml b/reusing/build.xml new file mode 100644 index 00000000..7fb8da0f --- /dev/null +++ b/reusing/build.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/strings/ArrayListDisplay.java b/strings/ArrayListDisplay.java index 6b08032d..c44f1549 100644 --- a/strings/ArrayListDisplay.java +++ b/strings/ArrayListDisplay.java @@ -4,7 +4,7 @@ import java.util.*; public class ArrayListDisplay { public static void main(String[] args) { - ArrayList coffees = new ArrayList(); + ArrayList coffees = new ArrayList<>(); for(Coffee c : new CoffeeGenerator(10)) coffees.add(c); System.out.println(coffees); diff --git a/strings/InfiniteRecursion.java b/strings/InfiniteRecursion.java index b2cd579d..6803a5be 100644 --- a/strings/InfiniteRecursion.java +++ b/strings/InfiniteRecursion.java @@ -1,15 +1,15 @@ //: strings/InfiniteRecursion.java // Accidental recursion. -// {RunByHand} +// {ThrowsException} import java.util.*; public class InfiniteRecursion { + @Override public String toString() { return " InfiniteRecursion address: " + this + "\n"; } public static void main(String[] args) { - List v = - new ArrayList(); + List v = new ArrayList<>(); for(int i = 0; i < 10; i++) v.add(new InfiniteRecursion()); System.out.println(v); diff --git a/strings/Receipt.java b/strings/Receipt.java index 300c7c33..da228891 100644 --- a/strings/Receipt.java +++ b/strings/Receipt.java @@ -35,4 +35,4 @@ Three Bears Por 1 14.29 Tax 2.80 ----- Total 49.39 -*///:~ \ No newline at end of file +*///:~ diff --git a/strings/TestRegularExpression.java b/strings/TestRegularExpression.java index 4a27fd17..64623629 100644 --- a/strings/TestRegularExpression.java +++ b/strings/TestRegularExpression.java @@ -36,4 +36,4 @@ Match "abcabcabc" at positions 0-8 Match "abc" at positions 12-14 Regular expression: "(abc){2,}" Match "abcabcabc" at positions 0-8 -*///:~ \ No newline at end of file +*///:~ diff --git a/strings/UsingStringBuilder.java b/strings/UsingStringBuilder.java index 4973033c..d9d44e1a 100644 --- a/strings/UsingStringBuilder.java +++ b/strings/UsingStringBuilder.java @@ -3,6 +3,7 @@ import java.util.*; public class UsingStringBuilder { public static Random rand = new Random(47); + @Override public String toString() { StringBuilder result = new StringBuilder("["); for(int i = 0; i < 25; i++) { diff --git a/strings/build.xml b/strings/build.xml new file mode 100644 index 00000000..2f4b4eea --- /dev/null +++ b/strings/build.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/swt/ColorBoxes.java b/swt/ColorBoxes.java index 69bcfa3e..08a75d89 100644 --- a/swt/ColorBoxes.java +++ b/swt/ColorBoxes.java @@ -32,11 +32,13 @@ class CBox extends Canvas implements Runnable { this.pause = pause; addPaintListener(new CBoxPaintListener()); } + @Override public void run() { try { while(!Thread.interrupted()) { cColor = newColor(); getDisplay().asyncExec(new Runnable() { + @Override public void run() { try { redraw(); } catch(SWTException e) {} // SWTException is OK when the parent @@ -57,6 +59,7 @@ class CBox extends Canvas implements Runnable { public class ColorBoxes implements SWTApplication { private int grid = 12; private int pause = 50; + @Override public void createContents(Composite parent) { GridLayout gridLayout = new GridLayout(grid, true); gridLayout.horizontalSpacing = 0; diff --git a/swt/DisplayEnvironment.java b/swt/DisplayEnvironment.java index b60b26a1..9aab8dbd 100644 --- a/swt/DisplayEnvironment.java +++ b/swt/DisplayEnvironment.java @@ -6,6 +6,7 @@ import org.eclipse.swt.layout.*; import java.util.*; public class DisplayEnvironment implements SWTApplication { + @Override public void createContents(Composite parent) { parent.setLayout(new FillLayout()); Text text = new Text(parent, SWT.WRAP | SWT.V_SCROLL); diff --git a/swt/Menus.java b/swt/Menus.java index 5d6278eb..b44a37af 100644 --- a/swt/Menus.java +++ b/swt/Menus.java @@ -8,11 +8,12 @@ import net.mindview.util.*; public class Menus implements SWTApplication { private static Shell shell; + @Override public void createContents(Composite parent) { shell = parent.getShell(); Menu bar = new Menu(shell, SWT.BAR); shell.setMenuBar(bar); - Set words = new TreeSet( + Set words = new TreeSet<>( new TextFile("Menus.java", "\\W+")); Iterator it = words.iterator(); while(it.next().matches("[0-9]+")) diff --git a/swt/SineWave.java b/swt/SineWave.java index f651611e..94da645f 100644 --- a/swt/SineWave.java +++ b/swt/SineWave.java @@ -51,6 +51,7 @@ class SineDraw extends Canvas { public class SineWave implements SWTApplication { private SineDraw sines; private Slider slider; + @Override public void createContents(Composite parent) { parent.setLayout(new GridLayout(1, true)); sines = new SineDraw(parent, SWT.NONE); diff --git a/swt/TabbedPane.java b/swt/TabbedPane.java index 8994d969..997e50b9 100644 --- a/swt/TabbedPane.java +++ b/swt/TabbedPane.java @@ -11,6 +11,7 @@ import org.eclipse.swt.browser.*; public class TabbedPane implements SWTApplication { private static TabFolder folder; private static Shell shell; + @Override public void createContents(Composite parent) { shell = parent.getShell(); parent.setLayout(new FillLayout()); diff --git a/swt/build.xml b/swt/build.xml new file mode 100644 index 00000000..fbd57d62 --- /dev/null +++ b/swt/build.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/typeinfo/FilledList.java b/typeinfo/FilledList.java index 5bbe9216..5d0b4be8 100644 --- a/typeinfo/FilledList.java +++ b/typeinfo/FilledList.java @@ -4,6 +4,7 @@ import java.util.*; class CountedInteger { private static long counter; private final long id = counter++; + @Override public String toString() { return Long.toString(id); } } @@ -11,7 +12,7 @@ public class FilledList { private Class type; public FilledList(Class type) { this.type = type; } public List create(int nElements) { - List result = new ArrayList(); + List result = new ArrayList<>(); try { for(int i = 0; i < nElements; i++) result.add(type.newInstance()); @@ -22,7 +23,7 @@ public class FilledList { } public static void main(String[] args) { FilledList fl = - new FilledList(CountedInteger.class); + new FilledList<>(CountedInteger.class); System.out.println(fl.create(15)); } } /* Output: diff --git a/typeinfo/ModifyingPrivateFields.java b/typeinfo/ModifyingPrivateFields.java index f576e75c..fbeb2a5f 100644 --- a/typeinfo/ModifyingPrivateFields.java +++ b/typeinfo/ModifyingPrivateFields.java @@ -5,6 +5,7 @@ class WithPrivateFinalField { private int i = 1; private final String s = "I'm totally safe"; private String s2 = "Am I safe?"; + @Override public String toString() { return "i = " + i + ", " + s + ", " + s2; } diff --git a/typeinfo/NullRobot.java b/typeinfo/NullRobot.java index b1538fdd..327017eb 100644 --- a/typeinfo/NullRobot.java +++ b/typeinfo/NullRobot.java @@ -11,12 +11,16 @@ class NullRobotProxyHandler implements InvocationHandler { nullName = type.getSimpleName() + " NullRobot"; } private class NRobot implements Null, Robot { + @Override public String name() { return nullName; } + @Override public String model() { return nullName; } + @Override public List operations() { return Collections.emptyList(); } } + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { diff --git a/typeinfo/Person.java b/typeinfo/Person.java index 5abd3d3d..98fbbe57 100644 --- a/typeinfo/Person.java +++ b/typeinfo/Person.java @@ -12,12 +12,14 @@ class Person { this.last = last; this.address = address; } + @Override public String toString() { return "Person: " + first + " " + last + " " + address; } public static class NullPerson extends Person implements Null { private NullPerson() { super("None", "None", "None"); } + @Override public String toString() { return "NullPerson"; } } public static final Person NULL = new NullPerson(); diff --git a/typeinfo/PetCount.java b/typeinfo/PetCount.java index 3a7403ed..072e1452 100644 --- a/typeinfo/PetCount.java +++ b/typeinfo/PetCount.java @@ -55,4 +55,4 @@ public class PetCount { } /* Output: Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric {Rat=2, Cymric=5, Cat=9, Pet=20, Dog=6, Manx=7, EgyptianMau=2, Pug=3, Mouse=2, Rodent=5, Hamster=1, Mutt=3} -*///:~ \ No newline at end of file +*///:~ diff --git a/typeinfo/PetCount3.java b/typeinfo/PetCount3.java index 28300d93..cc5726bf 100644 --- a/typeinfo/PetCount3.java +++ b/typeinfo/PetCount3.java @@ -18,6 +18,7 @@ public class PetCount3 { if(pair.getKey().isInstance(pet)) put(pair.getKey(), pair.getValue() + 1); } + @Override public String toString() { StringBuilder result = new StringBuilder("{"); for(Map.Entry,Integer> pair diff --git a/typeinfo/Position.java b/typeinfo/Position.java index d1e9a4f8..9ec187e7 100644 --- a/typeinfo/Position.java +++ b/typeinfo/Position.java @@ -23,6 +23,7 @@ class Position { if(person == null) person = Person.NULL; } + @Override public String toString() { return "Position: " + title + " " + person; } diff --git a/typeinfo/RegisteredFactories.java b/typeinfo/RegisteredFactories.java index 872d3100..0895219c 100644 --- a/typeinfo/RegisteredFactories.java +++ b/typeinfo/RegisteredFactories.java @@ -4,11 +4,12 @@ import typeinfo.factory.*; import java.util.*; class Part { + @Override public String toString() { return getClass().getSimpleName(); } static List> partFactories = - new ArrayList>(); + new ArrayList<>(); static { // Collections.addAll() gives an "unchecked generic // array creation ... for varargs parameter" warning. @@ -33,6 +34,7 @@ class FuelFilter extends Filter { // Create a Class Factory for each specific type: public static class Factory implements typeinfo.factory.Factory { + @Override public FuelFilter create() { return new FuelFilter(); } } } @@ -40,6 +42,7 @@ class FuelFilter extends Filter { class AirFilter extends Filter { public static class Factory implements typeinfo.factory.Factory { + @Override public AirFilter create() { return new AirFilter(); } } } @@ -47,6 +50,7 @@ class AirFilter extends Filter { class CabinAirFilter extends Filter { public static class Factory implements typeinfo.factory.Factory { + @Override public CabinAirFilter create() { return new CabinAirFilter(); } @@ -56,6 +60,7 @@ class CabinAirFilter extends Filter { class OilFilter extends Filter { public static class Factory implements typeinfo.factory.Factory { + @Override public OilFilter create() { return new OilFilter(); } } } @@ -65,6 +70,7 @@ class Belt extends Part {} class FanBelt extends Belt { public static class Factory implements typeinfo.factory.Factory { + @Override public FanBelt create() { return new FanBelt(); } } } @@ -72,6 +78,7 @@ class FanBelt extends Belt { class GeneratorBelt extends Belt { public static class Factory implements typeinfo.factory.Factory { + @Override public GeneratorBelt create() { return new GeneratorBelt(); } @@ -81,6 +88,7 @@ class GeneratorBelt extends Belt { class PowerSteeringBelt extends Belt { public static class Factory implements typeinfo.factory.Factory { + @Override public PowerSteeringBelt create() { return new PowerSteeringBelt(); } diff --git a/typeinfo/SelectingMethods.java b/typeinfo/SelectingMethods.java index a02c5b0c..d5da6add 100644 --- a/typeinfo/SelectingMethods.java +++ b/typeinfo/SelectingMethods.java @@ -8,6 +8,7 @@ class MethodSelector implements InvocationHandler { public MethodSelector(Object proxied) { this.proxied = proxied; } + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { @@ -25,11 +26,15 @@ interface SomeMethods { } class Implementation implements SomeMethods { + @Override public void boring1() { print("boring1"); } + @Override public void boring2() { print("boring2"); } + @Override public void interesting(String arg) { print("interesting " + arg); } + @Override public void boring3() { print("boring3"); } } diff --git a/typeinfo/Shapes.java b/typeinfo/Shapes.java index 26a015e4..d1a179f6 100644 --- a/typeinfo/Shapes.java +++ b/typeinfo/Shapes.java @@ -3,18 +3,22 @@ import java.util.*; abstract class Shape { void draw() { System.out.println(this + ".draw()"); } + @Override abstract public String toString(); } class Circle extends Shape { + @Override public String toString() { return "Circle"; } } class Square extends Shape { + @Override public String toString() { return "Square"; } } class Triangle extends Shape { + @Override public String toString() { return "Triangle"; } } diff --git a/typeinfo/SimpleDynamicProxy.java b/typeinfo/SimpleDynamicProxy.java index dd8a7202..7249db32 100644 --- a/typeinfo/SimpleDynamicProxy.java +++ b/typeinfo/SimpleDynamicProxy.java @@ -6,6 +6,7 @@ class DynamicProxyHandler implements InvocationHandler { public DynamicProxyHandler(Object proxied) { this.proxied = proxied; } + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { diff --git a/typeinfo/SimpleProxyDemo.java b/typeinfo/SimpleProxyDemo.java index 2f32ed43..39cae9b0 100644 --- a/typeinfo/SimpleProxyDemo.java +++ b/typeinfo/SimpleProxyDemo.java @@ -7,7 +7,9 @@ interface Interface { } class RealObject implements Interface { + @Override public void doSomething() { print("doSomething"); } + @Override public void somethingElse(String arg) { print("somethingElse " + arg); } @@ -18,10 +20,12 @@ class SimpleProxy implements Interface { public SimpleProxy(Interface proxied) { this.proxied = proxied; } + @Override public void doSomething() { print("SimpleProxy doSomething"); proxied.doSomething(); } + @Override public void somethingElse(String arg) { print("SimpleProxy somethingElse " + arg); proxied.somethingElse(arg); diff --git a/typeinfo/SnowRemovalRobot.java b/typeinfo/SnowRemovalRobot.java index 8b37e7bd..e4b5489c 100644 --- a/typeinfo/SnowRemovalRobot.java +++ b/typeinfo/SnowRemovalRobot.java @@ -4,30 +4,38 @@ import java.util.*; public class SnowRemovalRobot implements Robot { private String name; public SnowRemovalRobot(String name) {this.name = name;} + @Override public String name() { return name; } + @Override public String model() { return "SnowBot Series 11"; } public List operations() { return Arrays.asList( new Operation() { + @Override public String description() { return name + " can shovel snow"; } + @Override public void command() { System.out.println(name + " shoveling snow"); } }, new Operation() { + @Override public String description() { return name + " can chip ice"; } + @Override public void command() { System.out.println(name + " chipping ice"); } }, new Operation() { + @Override public String description() { return name + " can clear the roof"; } + @Override public void command() { System.out.println(name + " clearing roof"); } diff --git a/typeinfo/build.xml b/typeinfo/build.xml new file mode 100644 index 00000000..2473e972 --- /dev/null +++ b/typeinfo/build.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/typeinfo/packageaccess/HiddenC.java b/typeinfo/packageaccess/HiddenC.java index 2505e507..880496ad 100644 --- a/typeinfo/packageaccess/HiddenC.java +++ b/typeinfo/packageaccess/HiddenC.java @@ -4,6 +4,7 @@ import typeinfo.interfacea.*; import static net.mindview.util.Print.*; class C implements A { + @Override public void f() { print("public C.f()"); } public void g() { print("public C.g()"); } void u() { print("package C.u()"); } diff --git a/typeinfo/pets/ForNameCreator.java b/typeinfo/pets/ForNameCreator.java index 6ad63ea7..acd632eb 100644 --- a/typeinfo/pets/ForNameCreator.java +++ b/typeinfo/pets/ForNameCreator.java @@ -4,7 +4,7 @@ import java.util.*; public class ForNameCreator extends PetCreator { private static List> types = - new ArrayList>(); + new ArrayList<>(); // Types that you want to be randomly created: private static String[] typeNames = { "typeinfo.pets.Mutt", @@ -27,5 +27,6 @@ public class ForNameCreator extends PetCreator { } } static { loader(); } + @Override public List> types() {return types;} } ///:~ diff --git a/typeinfo/pets/Individual.java b/typeinfo/pets/Individual.java index b74d5645..cab7907e 100644 --- a/typeinfo/pets/Individual.java +++ b/typeinfo/pets/Individual.java @@ -8,15 +8,18 @@ public class Individual implements Comparable { public Individual(String name) { this.name = name; } // 'name' is optional: public Individual() {} + @Override public String toString() { return getClass().getSimpleName() + (name == null ? "" : " " + name); } public long id() { return id; } + @Override public boolean equals(Object o) { return o instanceof Individual && id == ((Individual)o).id; } + @Override public int hashCode() { int result = 17; if(name != null) @@ -24,6 +27,7 @@ public class Individual implements Comparable { result = 37 * result + (int)id; return result; } + @Override public int compareTo(Individual arg) { // Compare by class name first: String first = getClass().getSimpleName(); diff --git a/typeinfo/pets/LiteralPetCreator.java b/typeinfo/pets/LiteralPetCreator.java index 5b853e05..fe37bdab 100644 --- a/typeinfo/pets/LiteralPetCreator.java +++ b/typeinfo/pets/LiteralPetCreator.java @@ -15,6 +15,7 @@ public class LiteralPetCreator extends PetCreator { private static final List> types = allTypes.subList(allTypes.indexOf(Mutt.class), allTypes.size()); + @Override public List> types() { return types; } diff --git a/typeinfo/pets/PetCreator.java b/typeinfo/pets/PetCreator.java index c9a7f029..868b65f7 100644 --- a/typeinfo/pets/PetCreator.java +++ b/typeinfo/pets/PetCreator.java @@ -24,7 +24,7 @@ public abstract class PetCreator { return result; } public ArrayList arrayList(int size) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); Collections.addAll(result, createArray(size)); return result; } diff --git a/unittesting/build.xml b/unittesting/build.xml new file mode 100644 index 00000000..66bc77c8 --- /dev/null +++ b/unittesting/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/xml/APerson.java b/xml/APerson.java index a014375b..9298d7c8 100644 --- a/xml/APerson.java +++ b/xml/APerson.java @@ -28,6 +28,7 @@ public class APerson { first= person.getFirstChildElement("first").getValue(); last = person.getFirstChildElement("last").getValue(); } + @Override public String toString() { return first + " " + last; } // Make it human-readable: public static void @@ -69,4 +70,4 @@ public class APerson { Fry -*///:~ \ No newline at end of file +*///:~ diff --git a/xml/People.java b/xml/People.java index 438dab61..bcc35e60 100644 --- a/xml/People.java +++ b/xml/People.java @@ -20,4 +20,4 @@ public class People extends ArrayList { } } /* Output: [Dr. Bunsen Honeydew, Gonzo The Great, Phillip J. Fry] -*///:~ \ No newline at end of file +*///:~ diff --git a/xml/build.xml b/xml/build.xml new file mode 100644 index 00000000..a9420cf4 --- /dev/null +++ b/xml/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + +