├── .classpath ├── .gitattributes ├── .gitignore ├── .project ├── .settings ├── org.eclipse.core.resources.prefs ├── org.eclipse.jdt.core.prefs └── org.eclipse.m2e.core.prefs ├── LICENSE ├── README.md ├── lib └── tools-1.7.0.51.jar ├── pom.xml └── src └── main └── java ├── access ├── Cake.java ├── ChocolateChip.java ├── ChocolateChip2.java ├── Dinner.java ├── FullQualification.java ├── IceCream.java ├── ImportedMyClass.java ├── LibTest.java ├── Lunch.java ├── OrganizedByAccess.java ├── Pie.java ├── PrintTest.java ├── QualifiedMyClass.java ├── SingleImport.java ├── cookie2 │ └── Cookie.java ├── dessert │ └── Cookie.java └── mypackage │ └── MyClass.java ├── annotations ├── AtUnitComposition.java ├── AtUnitExample1.java ├── AtUnitExample2.java ├── AtUnitExample3.java ├── AtUnitExample4.java ├── AtUnitExample5.java ├── AtUnitExternalTest.java ├── ExtractInterface.java ├── HashSetTest.java ├── InterfaceExtractorProcessor.java ├── InterfaceExtractorProcessorFactory.java ├── Multiplier.java ├── PasswordUtils.java ├── SimulatingNull.java ├── StackL.java ├── StackLStringTest.java ├── Testable.java ├── UseCase.java ├── UseCaseTracker.java └── database │ ├── Constraints.java │ ├── DBTable.java │ ├── Member.java │ ├── SQLInteger.java │ ├── SQLString.java │ ├── TableCreationProcessorFactory.java │ ├── TableCreator.java │ └── Uniqueness.java ├── arrays ├── AlphabeticSearch.java ├── ArrayOfGenericType.java ├── ArrayOfGenerics.java ├── ArrayOptions.java ├── ArraySearching.java ├── AssemblingMultidimensionalArrays.java ├── AutoboxingArrays.java ├── CompType.java ├── ComparatorTest.java ├── ComparingArrays.java ├── ContainerComparison.java ├── CopyingArrays.java ├── FillingArrays.java ├── GeneratorsTest.java ├── IceCream.java ├── MultiDimWrapperArray.java ├── MultidimensionalObjectArrays.java ├── MultidimensionalPrimitiveArray.java ├── ParameterizedArrayType.java ├── PrimitiveConversionDemonstration.java ├── RaggedArray.java ├── RandomGeneratorsTest.java ├── Reverse.java ├── StringSorting.java ├── TestArrayGeneration.java ├── TestGenerated.java └── ThreeDWithNew.java ├── bangbean ├── BangBean.java └── BangBeanTest.java ├── concurrency ├── ActiveObjectDemo.java ├── AtomicEvenGenerator.java ├── AtomicIntegerTest.java ├── Atomicity.java ├── AtomicityTest.java ├── AttemptLocking.java ├── BankTellerSimulation.java ├── BasicThreads.java ├── CachedThreadPool.java ├── CallableDemo.java ├── CaptureUncaughtException.java ├── CarBuilder.java ├── Chopstick.java ├── CloseResource.java ├── CountDownLatchDemo.java ├── CriticalSection.java ├── DaemonFromFactory.java ├── Daemons.java ├── DaemonsDontRunFinally.java ├── DeadlockingDiningPhilosophers.java ├── DelayQueueDemo.java ├── EvenChecker.java ├── EvenGenerator.java ├── ExceptionThread.java ├── ExchangerDemo.java ├── ExplicitCriticalSection.java ├── FastSimulation.java ├── Fat.java ├── FixedDiningPhilosophers.java ├── FixedThreadPool.java ├── GreenhouseScheduler.java ├── HorseRace.java ├── IntGenerator.java ├── Interrupting.java ├── Interrupting2.java ├── InterruptingIdiom.java ├── Joining.java ├── LiftOff.java ├── ListComparisons.java ├── MainThread.java ├── MapComparisons.java ├── MoreBasicThreads.java ├── MultiLock.java ├── MutexEvenGenerator.java ├── NIOInterruption.java ├── NaiveExceptionHandling.java ├── NotifyVsNotifyAll.java ├── OrnamentalGarden.java ├── Philosopher.java ├── PipedIO.java ├── Pool.java ├── PriorityBlockingQueueDemo.java ├── ReaderWriterList.java ├── ResponsiveUI.java ├── Restaurant.java ├── SelfManaged.java ├── SemaphoreDemo.java ├── SerialNumberChecker.java ├── SerialNumberGenerator.java ├── SettingDefaultHandler.java ├── SimpleDaemons.java ├── SimpleMicroBenchmark.java ├── SimplePriorities.java ├── SimpleThread.java ├── SingleThreadExecutor.java ├── SleepingTask.java ├── SyncObject.java ├── SynchronizationComparisons.java ├── SynchronizedEvenGenerator.java ├── TestBlockingQueues.java ├── Tester.java ├── ThreadLocalVariableHolder.java ├── ThreadVariations.java ├── ToastOMatic.java ├── restaurant2 │ └── RestaurantWithQueues.java ├── waxomatic │ └── WaxOMatic.java └── waxomatic2 │ └── WaxOMatic2.java ├── containers ├── AssociativeArray.java ├── Bits.java ├── CanonicalMapping.java ├── CollectionDataGeneration.java ├── CollectionDataTest.java ├── CollectionMethods.java ├── CountedString.java ├── DequeTest.java ├── Enumerations.java ├── FailFast.java ├── FillingLists.java ├── Groundhog.java ├── Groundhog2.java ├── IndividualTest.java ├── LinkedHashMapDemo.java ├── ListPerformance.java ├── ListSortSearch.java ├── Lists.java ├── MapDataTest.java ├── MapEntry.java ├── MapPerformance.java ├── Maps.java ├── Prediction.java ├── QueueBehavior.java ├── RandomBounds.java ├── ReadOnly.java ├── References.java ├── SetPerformance.java ├── SimpleHashMap.java ├── SlowMap.java ├── SortedMapDemo.java ├── SortedSetDemo.java ├── SpringDetector.java ├── SpringDetector2.java ├── Stacks.java ├── StringHashCode.java ├── Synchronization.java ├── Test.java ├── TestParam.java ├── Tester.java ├── ToDoList.java ├── TypesForSets.java ├── Unsupported.java └── Utilities.java ├── control ├── BreakAndContinue.java ├── CommaOperator.java ├── ForEachFloat.java ├── ForEachInt.java ├── ForEachString.java ├── IfElse.java ├── IfElse2.java ├── LabeledFor.java ├── LabeledWhile.java ├── ListCharacters.java ├── VowelsAndConsonants.java └── WhileTest.java ├── enumerated ├── AlarmPoints.java ├── BigEnumSet.java ├── Burrito.java ├── CarWash.java ├── Competitor.java ├── ConstantSpecificMethod.java ├── EnumClass.java ├── EnumMaps.java ├── EnumSets.java ├── Input.java ├── NonEnum.java ├── NotClasses.java ├── Outcome.java ├── OverrideConstantSpecific.java ├── OzWitch.java ├── PostOffice.java ├── RandomTest.java ├── Reflection.java ├── RoShamBo.java ├── RoShamBo1.java ├── RoShamBo2.java ├── RoShamBo3.java ├── RoShamBo4.java ├── RoShamBo5.java ├── RoShamBo6.java ├── SecurityCategory.java ├── SpaceShip.java ├── Spiciness.java ├── TrafficLight.java ├── UpcastEnum.java ├── VendingMachine.java ├── cartoons │ └── EnumImplementation.java └── menu │ ├── Course.java │ ├── Food.java │ ├── Meal.java │ ├── Meal2.java │ └── TypeOfFood.java ├── exceptions ├── AlwaysFinally.java ├── Cleanup.java ├── CleanupIdiom.java ├── DynamicFields.java ├── ExceptionMethods.java ├── ExceptionSilencer.java ├── ExtraFeatures.java ├── FinallyWorks.java ├── FullConstructors.java ├── Human.java ├── InheritingExceptions.java ├── InputFile.java ├── LoggingExceptions.java ├── LoggingExceptions2.java ├── LostMessage.java ├── MainException.java ├── MultipleReturns.java ├── NeverCaught.java ├── OnOffException1.java ├── OnOffException2.java ├── OnOffSwitch.java ├── RethrowNew.java ├── Rethrowing.java ├── StormyInning.java ├── Switch.java ├── TurnOffChecking.java ├── WhoCalled.java └── WithFinally.java ├── frogbean └── Frog.java ├── generics ├── Apply.java ├── ArrayMaker.java ├── ArrayOfGeneric.java ├── ArrayOfGenericReference.java ├── BankTeller.java ├── BasicBounds.java ├── BasicGeneratorDemo.java ├── BasicHolder.java ├── ByteSet.java ├── CRGWithBasicHolder.java ├── CaptureConversion.java ├── CheckedList.java ├── ClassCasting.java ├── ClassTypeCapture.java ├── ComparablePet.java ├── CompilerIntelligence.java ├── CountedObject.java ├── CovariantArrays.java ├── CovariantReturnTypes.java ├── CreatorGeneric.java ├── CuriouslyRecurringGeneric.java ├── DogsAndRobots.cpp ├── DogsAndRobots.java ├── DynamicProxyMixin.java ├── EpicBattle.java ├── Erased.java ├── ErasedTypeEquivalence.java ├── ErasureAndInheritance.java ├── ExplicitTypeSpecification.java ├── FactoryConstraint.java ├── Fibonacci.java ├── Fill.java ├── Fill2.java ├── FilledListMaker.java ├── Functional.java ├── Generators.java ├── GenericArray.java ├── GenericArray2.java ├── GenericArrayWithTypeToken.java ├── GenericCast.java ├── GenericHolder.java ├── GenericMethods.java ├── GenericReading.java ├── GenericVarargs.java ├── GenericWriting.java ├── GenericsAndCovariance.java ├── GenericsAndReturnTypes.java ├── HasF.java ├── HijackedInterface.java ├── Holder.java ├── Holder1.java ├── Holder2.java ├── Holder3.java ├── InheritBounds.java ├── InstantiateGenericType.cpp ├── InstantiateGenericType.java ├── IterableFibonacci.java ├── LatentReflection.java ├── LimitsOfInference.java ├── LinkedStack.java ├── ListMaker.java ├── ListOfGenerics.java ├── ListOfInt.java ├── LostInformation.java ├── Manipulation.java ├── Manipulator2.java ├── Manipulator3.java ├── Mixins.cpp ├── Mixins.java ├── MultipleInterfaceVariants.java ├── NeedCasting.java ├── NonCovariantGenerics.java ├── NotSelfBounded.java ├── OrdinaryArguments.java ├── Performs.java ├── PlainGenericInheritance.java ├── PrimitiveGenericTest.java ├── RandomList.java ├── RestrictedComparablePets.java ├── ReturnGenericType.java ├── SelfBounding.java ├── SelfBoundingAndCovariantArguments.java ├── SelfBoundingMethods.java ├── SimpleDogsAndRobots.java ├── SimpleHolder.java ├── SimpleQueue.java ├── SimplerPets.java ├── Store.java ├── SuperTypeWildcards.java ├── Templates.cpp ├── ThrowGenericException.java ├── TupleList.java ├── TupleTest.java ├── TupleTest2.java ├── UnboundedWildcards1.java ├── UnboundedWildcards2.java ├── Unconstrained.java ├── UseList.java ├── UseList2.java ├── WatercolorSets.java ├── Wildcards.java ├── coffee │ ├── Americano.java │ ├── Breve.java │ ├── Cappuccino.java │ ├── Coffee.java │ ├── CoffeeGenerator.java │ ├── Latte.java │ └── Mocha.java ├── decorator │ └── Decoration.java └── watercolors │ └── Watercolors.java ├── gui ├── BangBean2.java ├── BeanDumper.java ├── BorderLayout1.java ├── Borders.java ├── Button1.java ├── Button2.java ├── Button2b.java ├── ButtonGroups.java ├── Buttons.java ├── CheckBoxes.java ├── ColorBoxes.java ├── ComboBoxes.java ├── Dialogs.java ├── Face0.gif ├── Face1.gif ├── Face2.gif ├── Face3.gif ├── Face4.gif ├── Faces.java ├── FileChooserTest.java ├── FlowLayout1.java ├── GridLayout1.java ├── HTMLButton.java ├── HelloLabel.java ├── HelloSwing.java ├── InterruptableLongRunningCallable.java ├── InterruptableLongRunningTask.java ├── List.java ├── LongRunningTask.java ├── LookAndFeel.java ├── Menus.java ├── MessageBoxes.java ├── MonitoredLongRunningCallable.java ├── Popup.java ├── Progress.java ├── RadioButtons.java ├── ShowAddListeners.java ├── SimpleMenus.java ├── SineWave.java ├── SubmitLabelManipulationTask.java ├── SubmitSwingProgram.java ├── TabbedPane1.java ├── TextArea.java ├── TextFields.java ├── TextPane.java ├── TicTacToe.java ├── TrackEvent.java ├── flex │ ├── Song.java │ ├── SongService.java │ ├── build-command.txt │ ├── helloflex1.mxml │ ├── helloflex2.mxml │ ├── songScript.as │ ├── songStyles.css │ └── songs.mxml └── jnlp │ ├── JnlpFileChooser.java │ ├── filechooser.html │ ├── filechooser.jnlp │ └── mindview.gif ├── holding ├── AdapterMethodIdiom.java ├── AddingGroups.java ├── ApplesAndOrangesWithGenerics.java ├── ApplesAndOrangesWithoutGenerics.java ├── ArrayIsNotIterable.java ├── AsListInference.java ├── CollectionSequence.java ├── ContainerMethods.java ├── CrossContainerIteration.java ├── EnvironmentVariables.java ├── ForEachCollections.java ├── GenericsAndUpcasting.java ├── InterfaceVsIterator.java ├── IterableClass.java ├── LinkedListFeatures.java ├── ListFeatures.java ├── ListIteration.java ├── MapOfList.java ├── ModifyingArraysAsList.java ├── MultiIterableClass.java ├── NonCollectionSequence.java ├── PetMap.java ├── PrintingContainers.java ├── PriorityQueueDemo.java ├── QueueDemo.java ├── SetOfInteger.java ├── SetOperations.java ├── SimpleCollection.java ├── SimpleIteration.java ├── SortedSetOfInteger.java ├── StackCollision.java ├── StackTest.java ├── Statistics.java ├── UniqueWords.java └── UniqueWordsAlphabetic.java ├── initialization ├── Apricot.java ├── ArrayClassObj.java ├── ArrayInit.java ├── ArrayNew.java ├── ArraysOfPrimitives.java ├── AutoboxingVarargs.java ├── BananaPeel.java ├── Burrito.java ├── Counter.java ├── DefaultConstructor.java ├── Demotion.java ├── DynamicArray.java ├── EnumOrder.java ├── ExplicitStatic.java ├── Flower.java ├── InitialValues.java ├── InitialValues2.java ├── Leaf.java ├── Measurement.java ├── MethodInit.java ├── MethodInit2.java ├── MethodInit3.java ├── Mugs.java ├── NewVarArgs.java ├── NoSynthesis.java ├── OptionalTrailingArguments.java ├── OrderOfInitialization.java ├── Overloading.java ├── OverloadingOrder.java ├── OverloadingVarargs.java ├── OverloadingVarargs2.java ├── OverloadingVarargs3.java ├── PassingThis.java ├── PrimitiveOverloading.java ├── SimpleConstructor.java ├── SimpleConstructor2.java ├── SimpleEnumUse.java ├── Spiciness.java ├── Spoon.java ├── StaticInitialization.java ├── TerminationCondition.java ├── VarArgs.java └── VarargType.java ├── innerclasses ├── AnonymousConstructor.java ├── BigEgg.java ├── BigEgg2.java ├── Callbacks.java ├── ClassInInterface.java ├── Contents.java ├── Destination.java ├── DotNew.java ├── DotThis.java ├── Factories.java ├── Games.java ├── GreenhouseController.java ├── GreenhouseControls.java ├── InheritInner.java ├── LocalInnerClass.java ├── MultiImplementation.java ├── MultiInterfaces.java ├── MultiNestingAccess.java ├── Parcel1.java ├── Parcel10.java ├── Parcel11.java ├── Parcel2.java ├── Parcel3.java ├── Parcel5.java ├── Parcel6.java ├── Parcel7.java ├── Parcel7b.java ├── Parcel8.java ├── Parcel9.java ├── Sequence.java ├── TestBed.java ├── TestParcel.java ├── Wrapping.java └── controller │ ├── Controller.java │ └── Event.java ├── interfaces ├── AdaptedRandomDoubles.java ├── Adventure.java ├── Factories.java ├── Games.java ├── HorrorShow.java ├── InterfaceCollision.java ├── Months.java ├── RandVals.java ├── RandomDoubles.java ├── RandomWords.java ├── TestRandVals.java ├── classprocessor │ └── Apply.java ├── filters │ ├── BandPass.java │ ├── Filter.java │ ├── HighPass.java │ ├── LowPass.java │ └── Waveform.java ├── interfaceprocessor │ ├── Apply.java │ ├── FilterProcessor.java │ ├── Processor.java │ └── StringProcessor.java ├── music4 │ └── Music4.java ├── music5 │ └── Music5.java └── nesting │ └── NestingInterfaces.java ├── io ├── Alien.java ├── AvailableCharSets.java ├── BasicFileOutput.java ├── Blip3.java ├── Blips.java ├── BufferToText.java ├── BufferedInputFile.java ├── ChangeSystemOut.java ├── ChannelCopy.java ├── DirList.java ├── DirList2.java ├── DirList3.java ├── DirectoryDemo.java ├── Echo.java ├── Endians.java ├── FileLocking.java ├── FileOutputShortcut.java ├── FormattedMemoryInput.java ├── FreezeAlien.java ├── GZIPcompress.java ├── GetChannel.java ├── GetData.java ├── IntBufferDemo.java ├── LargeMappedFiles.java ├── LockingMappedFiles.java ├── Logon.java ├── MakeDirectories.java ├── MappedIO.java ├── MemoryInput.java ├── MyWorld.java ├── OSExecuteDemo.java ├── PreferencesDemo.java ├── RecoverCADState.java ├── Redirecting.java ├── SerialCtl.java ├── StoreCADState.java ├── StoringAndRecoveringData.java ├── TestEOF.java ├── TransferTo.java ├── UsingBuffers.java ├── UsingRandomAccessFile.java ├── ViewBuffers.java ├── Worm.java ├── ZipCompress.java └── xfiles │ └── ThawAlien.java ├── net └── mindview │ ├── atunit │ ├── AtUnit.java │ ├── AtUnitRemover.java │ ├── ClassNameFinder.java │ ├── Test.java │ ├── TestObjectCleanup.java │ ├── TestObjectCreate.java │ └── TestProperty.java │ ├── simple │ ├── List.java │ └── Vector.java │ └── util │ ├── BasicGenerator.java │ ├── BinaryFile.java │ ├── CollectionData.java │ ├── ContainerMethodDifferences.java │ ├── ConvertTo.java │ ├── CountingGenerator.java │ ├── CountingIntegerList.java │ ├── CountingMapData.java │ ├── Countries.java │ ├── DaemonThreadFactory.java │ ├── DaemonThreadPoolExecutor.java │ ├── Deque.java │ ├── Directory.java │ ├── Enums.java │ ├── FiveTuple.java │ ├── FourTuple.java │ ├── Generated.java │ ├── Generator.java │ ├── Hex.java │ ├── MapData.java │ ├── New.java │ ├── Null.java │ ├── OSExecute.java │ ├── OSExecuteException.java │ ├── PPrint.java │ ├── Pair.java │ ├── Print.java │ ├── ProcessFiles.java │ ├── RandomGenerator.java │ ├── Range.java │ ├── Sets.java │ ├── Stack.java │ ├── SwingConsole.java │ ├── TaskItem.java │ ├── TaskManager.java │ ├── TextFile.java │ ├── ThreeTuple.java │ ├── Tuple.java │ ├── TwoTuple.java │ └── TypeCounter.java ├── object ├── Documentation1.java ├── Documentation2.java ├── Documentation3.java ├── HelloDate.java └── ShowProperties.java ├── operators ├── AllOps.java ├── Assignment.java ├── AutoInc.java ├── BitManipulation.java ├── Bool.java ├── Casting.java ├── CastingNumbers.java ├── EqualsMethod.java ├── EqualsMethod2.java ├── Equivalence.java ├── Exponents.java ├── HelloDate.java ├── Literals.java ├── MathOps.java ├── Overflow.java ├── PassObject.java ├── Precedence.java ├── RoundingNumbers.java ├── ShortCircuit.java ├── StringOperators.java ├── TernaryIfElse.java └── URShift.java ├── polymorphism ├── CovariantReturn.java ├── FieldAccess.java ├── Frog.java ├── PolyConstructors.java ├── PrivateOverride.java ├── RTTI.java ├── ReferenceCounting.java ├── Sandwich.java ├── Shapes.java ├── StaticPolymorphism.java ├── Transmogrify.java ├── music │ ├── Instrument.java │ ├── Music.java │ ├── Music2.java │ ├── Note.java │ └── Wind.java ├── music3 │ └── Music3.java └── shape │ ├── Circle.java │ ├── RandomShapeGenerator.java │ ├── Shape.java │ ├── Square.java │ └── Triangle.java ├── reusing ├── Bath.java ├── Beetle.java ├── BlankFinal.java ├── CADSystem.java ├── Car.java ├── Cartoon.java ├── Chess.java ├── Detergent.java ├── FinalArguments.java ├── FinalData.java ├── FinalOverridingIllusion.java ├── Hide.java ├── Jurassic.java ├── Lisa.java ├── Orc.java ├── PlaceSetting.java ├── SpaceShip.java ├── SpaceShipControls.java ├── SpaceShipDelegation.java ├── SprinklerSystem.java └── Wind.java ├── strings ├── ArrayListDisplay.java ├── BetterRead.java ├── Concatenation.java ├── Conversion.java ├── DatabaseException.java ├── Finding.java ├── Groups.java ├── Immutable.java ├── InfiniteRecursion.java ├── IntegerMatch.java ├── JGrep.java ├── ReFlags.java ├── Receipt.java ├── Replacing.java ├── ReplacingStringTokenizer.java ├── Resetting.java ├── Rudolph.java ├── ScannerDelimiter.java ├── SimpleFormat.java ├── SimpleRead.java ├── SplitDemo.java ├── Splitting.java ├── StartEnd.java ├── TestRegularExpression.java ├── TheReplacements.java ├── ThreatAnalyzer.java ├── Turtle.java ├── UsingStringBuilder.java └── WhitherStringBuilder.java ├── swt ├── ColorBoxes.java ├── DisplayEnvironment.java ├── DisplayProperties.java ├── HelloSWT.java ├── Menus.java ├── ShellsAreMainWindows.java ├── SineWave.java ├── TabbedPane.java └── util │ ├── SWTApplication.java │ └── SWTConsole.java ├── typeinfo ├── AnonymousImplementation.java ├── BoundedClassReferences.java ├── ClassCasts.java ├── ClassInitialization.java ├── FamilyVsExactType.java ├── FilledList.java ├── GenericClassReferences.java ├── HiddenImplementation.java ├── InnerImplementation.java ├── InterfaceViolation.java ├── ModifyingPrivateFields.java ├── NullRobot.java ├── Operation.java ├── Person.java ├── PetCount.java ├── PetCount2.java ├── PetCount3.java ├── PetCount4.java ├── Position.java ├── RegisteredFactories.java ├── Robot.java ├── SelectingMethods.java ├── Shapes.java ├── ShowMethods.java ├── SimpleDynamicProxy.java ├── SimpleProxyDemo.java ├── SnowRemovalRobot.java ├── Staff.java ├── SweetShop.java ├── WildcardClassReferences.java ├── factory │ └── Factory.java ├── interfacea │ └── A.java ├── packageaccess │ └── HiddenC.java ├── pets │ ├── Cat.java │ ├── Cymric.java │ ├── Dog.java │ ├── EgyptianMau.java │ ├── ForNameCreator.java │ ├── Hamster.java │ ├── Individual.java │ ├── LiteralPetCreator.java │ ├── Manx.java │ ├── Mouse.java │ ├── Mutt.java │ ├── Person.java │ ├── Pet.java │ ├── PetCreator.java │ ├── Pets.java │ ├── Pug.java │ ├── Rat.java │ └── Rodent.java └── toys │ ├── GenericToyTest.java │ └── ToyTest.java └── xml ├── People.java └── Person.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | TIJ4 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.5 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 12 | org.eclipse.jdt.core.compiler.source=1.5 13 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /lib/tools-1.7.0.51.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/lib/tools-1.7.0.51.jar -------------------------------------------------------------------------------- /src/main/java/access/Cake.java: -------------------------------------------------------------------------------- 1 | //: access/Cake.java 2 | // Accesses a class in a separate compilation unit. 3 | package access; 4 | class Cake { 5 | public static void main(String[] args) { 6 | Pie x = new Pie(); 7 | x.f(); 8 | } 9 | } /* Output: 10 | Pie.f() 11 | *///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/access/ChocolateChip.java: -------------------------------------------------------------------------------- 1 | //: access/ChocolateChip.java 2 | // Can't use package-access member from another package. 3 | package access; 4 | import access.dessert.*; 5 | 6 | public class ChocolateChip extends Cookie { 7 | public ChocolateChip() { 8 | System.out.println("ChocolateChip constructor"); 9 | } 10 | public void chomp() { 11 | //! bite(); // Can't access bite 12 | } 13 | public static void main(String[] args) { 14 | ChocolateChip x = new ChocolateChip(); 15 | x.chomp(); 16 | } 17 | } /* Output: 18 | Cookie constructor 19 | ChocolateChip constructor 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/access/ChocolateChip2.java: -------------------------------------------------------------------------------- 1 | //: access/ChocolateChip2.java 2 | package access; 3 | import access.cookie2.*; 4 | 5 | public class ChocolateChip2 extends Cookie { 6 | public ChocolateChip2() { 7 | System.out.println("ChocolateChip2 constructor"); 8 | } 9 | public void chomp() { bite(); } // Protected method 10 | public static void main(String[] args) { 11 | ChocolateChip2 x = new ChocolateChip2(); 12 | x.chomp(); 13 | } 14 | } /* Output: 15 | Cookie constructor 16 | ChocolateChip2 constructor 17 | bite 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/access/Dinner.java: -------------------------------------------------------------------------------- 1 | //: access/Dinner.java 2 | // Uses the library. 3 | package access; 4 | import access.dessert.*; 5 | 6 | public class Dinner { 7 | public static void main(String[] args) { 8 | Cookie x = new Cookie(); 9 | //! x.bite(); // Can't access 10 | } 11 | } /* Output: 12 | Cookie constructor 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/access/FullQualification.java: -------------------------------------------------------------------------------- 1 | //: access/FullQualification.java 2 | package access; 3 | public class FullQualification { 4 | public static void main(String[] args) { 5 | java.util.ArrayList list = new java.util.ArrayList(); 6 | } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/access/IceCream.java: -------------------------------------------------------------------------------- 1 | //: access/IceCream.java 2 | // Demonstrates "private" keyword. 3 | package access; 4 | class Sundae { 5 | private Sundae() {} 6 | static Sundae makeASundae() { 7 | return new Sundae(); 8 | } 9 | } 10 | 11 | public class IceCream { 12 | public static void main(String[] args) { 13 | //! Sundae x = new Sundae(); 14 | Sundae x = Sundae.makeASundae(); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/access/ImportedMyClass.java: -------------------------------------------------------------------------------- 1 | //: access/ImportedMyClass.java 2 | package access; 3 | import access.mypackage.*; 4 | 5 | public class ImportedMyClass { 6 | public static void main(String[] args) { 7 | MyClass m = new MyClass(); 8 | } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/access/LibTest.java: -------------------------------------------------------------------------------- 1 | //: access/LibTest.java 2 | // Uses the library. 3 | package access; 4 | import net.mindview.simple.*; 5 | 6 | public class LibTest { 7 | public static void main(String[] args) { 8 | Vector v = new Vector(); 9 | List l = new List(); 10 | } 11 | } /* Output: 12 | net.mindview.simple.Vector 13 | net.mindview.simple.List 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/access/OrganizedByAccess.java: -------------------------------------------------------------------------------- 1 | //: access/OrganizedByAccess.java 2 | package access; 3 | public class OrganizedByAccess { 4 | public void pub1() { /* ... */ } 5 | public void pub2() { /* ... */ } 6 | public void pub3() { /* ... */ } 7 | private void priv1() { /* ... */ } 8 | private void priv2() { /* ... */ } 9 | private void priv3() { /* ... */ } 10 | private int i; 11 | // ... 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/access/Pie.java: -------------------------------------------------------------------------------- 1 | //: access/Pie.java 2 | // The other class. 3 | package access; 4 | class Pie { 5 | void f() { System.out.println("Pie.f()"); } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/access/PrintTest.java: -------------------------------------------------------------------------------- 1 | //: access/PrintTest.java 2 | // Uses the static printing methods in Print.java. 3 | package access; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class PrintTest { 7 | public static void main(String[] args) { 8 | print("Available from now on!"); 9 | print(100); 10 | print(100L); 11 | print(3.14159); 12 | } 13 | } /* Output: 14 | Available from now on! 15 | 100 16 | 100 17 | 3.14159 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/access/QualifiedMyClass.java: -------------------------------------------------------------------------------- 1 | //: access/QualifiedMyClass.java 2 | package access; 3 | public class QualifiedMyClass { 4 | public static void main(String[] args) { 5 | access.mypackage.MyClass m = 6 | new access.mypackage.MyClass(); 7 | } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/access/SingleImport.java: -------------------------------------------------------------------------------- 1 | //: access/SingleImport.java 2 | package access; 3 | import java.util.ArrayList; 4 | 5 | public class SingleImport { 6 | public static void main(String[] args) { 7 | ArrayList list = new java.util.ArrayList(); 8 | } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/access/cookie2/Cookie.java: -------------------------------------------------------------------------------- 1 | //: access/cookie2/Cookie.java 2 | package access.cookie2; 3 | 4 | public class Cookie { 5 | public Cookie() { 6 | System.out.println("Cookie constructor"); 7 | } 8 | protected void bite() { 9 | System.out.println("bite"); 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/access/dessert/Cookie.java: -------------------------------------------------------------------------------- 1 | //: access/dessert/Cookie.java 2 | // Creates a library. 3 | package access.dessert; 4 | 5 | public class Cookie { 6 | public Cookie() { 7 | System.out.println("Cookie constructor"); 8 | } 9 | void bite() { System.out.println("bite"); } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/access/mypackage/MyClass.java: -------------------------------------------------------------------------------- 1 | //: access/mypackage/MyClass.java 2 | package access.mypackage; 3 | 4 | public class MyClass { 5 | // ... 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/annotations/AtUnitExternalTest.java: -------------------------------------------------------------------------------- 1 | //: annotations/AtUnitExternalTest.java 2 | // Creating non-embedded tests. 3 | package annotations; 4 | import net.mindview.atunit.*; 5 | import net.mindview.util.*; 6 | 7 | public class AtUnitExternalTest extends AtUnitExample1 { 8 | @Test boolean _methodOne() { 9 | return methodOne().equals("This is methodOne"); 10 | } 11 | @Test boolean _methodTwo() { return methodTwo() == 2; } 12 | public static void main(String[] args) throws Exception { 13 | OSExecute.command( 14 | "java net.mindview.atunit.AtUnit AtUnitExternalTest"); 15 | } 16 | } /* Output: 17 | annotations.AtUnitExternalTest 18 | . _methodOne 19 | . _methodTwo This is methodTwo 20 | 21 | OK (2 tests) 22 | *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/annotations/ExtractInterface.java: -------------------------------------------------------------------------------- 1 | //: annotations/ExtractInterface.java 2 | // APT-based annotation processing. 3 | package annotations; 4 | import java.lang.annotation.*; 5 | 6 | @Target(ElementType.TYPE) 7 | @Retention(RetentionPolicy.SOURCE) 8 | public @interface ExtractInterface { 9 | public String value(); 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/annotations/Multiplier.java: -------------------------------------------------------------------------------- 1 | //: annotations/Multiplier.java 2 | // APT-based annotation processing. 3 | package annotations; 4 | 5 | @ExtractInterface("IMultiplier") 6 | public class Multiplier { 7 | public int multiply(int x, int y) { 8 | int total = 0; 9 | for(int i = 0; i < x; i++) 10 | total = add(total, y); 11 | return total; 12 | } 13 | private int add(int x, int y) { return x + y; } 14 | public static void main(String[] args) { 15 | Multiplier m = new Multiplier(); 16 | System.out.println("11*16 = " + m.multiply(11, 16)); 17 | } 18 | } /* Output: 19 | 11*16 = 176 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/annotations/PasswordUtils.java: -------------------------------------------------------------------------------- 1 | package annotations; 2 | import java.util.*; 3 | 4 | public class PasswordUtils { 5 | @UseCase(id = 47, description = 6 | "Passwords must contain at least one numeric") 7 | public boolean validatePassword(String password) { 8 | return (password.matches("\\w*\\d\\w*")); 9 | } 10 | @UseCase(id = 48) 11 | public String encryptPassword(String password) { 12 | return new StringBuilder(password).reverse().toString(); 13 | } 14 | @UseCase(id = 49, description = 15 | "New passwords can't equal previously used ones") 16 | public boolean checkForNewPassword( 17 | List prevPasswords, String password) { 18 | return !prevPasswords.contains(password); 19 | } 20 | } ///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/annotations/SimulatingNull.java: -------------------------------------------------------------------------------- 1 | package annotations; 2 | import java.lang.annotation.*; 3 | 4 | @Target(ElementType.METHOD) 5 | @Retention(RetentionPolicy.RUNTIME) 6 | public @interface SimulatingNull { 7 | public int id() default -1; 8 | public String description() default ""; 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/annotations/StackL.java: -------------------------------------------------------------------------------- 1 | //: annotations/StackL.java 2 | // A stack built on a linkedList. 3 | package annotations; 4 | import java.util.*; 5 | 6 | public class StackL { 7 | private LinkedList list = new LinkedList(); 8 | public void push(T v) { list.addFirst(v); } 9 | public T top() { return list.getFirst(); } 10 | public T pop() { return list.removeFirst(); } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/annotations/Testable.java: -------------------------------------------------------------------------------- 1 | //: annotations/Testable.java 2 | package annotations; 3 | import net.mindview.atunit.*; 4 | 5 | public class Testable { 6 | public void execute() { 7 | System.out.println("Executing.."); 8 | } 9 | @Test void testExecute() { execute(); } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/annotations/UseCase.java: -------------------------------------------------------------------------------- 1 | package annotations; 2 | import java.lang.annotation.*; 3 | 4 | @Target(ElementType.METHOD) 5 | @Retention(RetentionPolicy.RUNTIME) 6 | public @interface UseCase { 7 | public int id(); 8 | public String description() default "no description"; 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/annotations/database/Constraints.java: -------------------------------------------------------------------------------- 1 | //: annotations/database/Constraints.java 2 | package annotations.database; 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.FIELD) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | public @interface Constraints { 8 | boolean primaryKey() default false; 9 | boolean allowNull() default true; 10 | boolean unique() default false; 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/annotations/database/DBTable.java: -------------------------------------------------------------------------------- 1 | //: annotations/database/DBTable.java 2 | package annotations.database; 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.TYPE) // Applies to classes only 6 | @Retention(RetentionPolicy.RUNTIME) 7 | public @interface DBTable { 8 | public String name() default ""; 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/annotations/database/Member.java: -------------------------------------------------------------------------------- 1 | //: annotations/database/Member.java 2 | package annotations.database; 3 | 4 | @DBTable(name = "MEMBER") 5 | public class Member { 6 | @SQLString(30) String firstName; 7 | @SQLString(50) String lastName; 8 | @SQLInteger Integer age; 9 | @SQLString(value = 30, 10 | constraints = @Constraints(primaryKey = true)) 11 | String handle; 12 | static int memberCount; 13 | public String getHandle() { return handle; } 14 | public String getFirstName() { return firstName; } 15 | public String getLastName() { return lastName; } 16 | public String toString() { return handle; } 17 | public Integer getAge() { return age; } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/annotations/database/SQLInteger.java: -------------------------------------------------------------------------------- 1 | //: annotations/database/SQLInteger.java 2 | package annotations.database; 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.FIELD) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | public @interface SQLInteger { 8 | String name() default ""; 9 | Constraints constraints() default @Constraints; 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/annotations/database/SQLString.java: -------------------------------------------------------------------------------- 1 | //: annotations/database/SQLString.java 2 | package annotations.database; 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.FIELD) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | public @interface SQLString { 8 | int value() default 0; 9 | String name() default ""; 10 | Constraints constraints() default @Constraints; 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/annotations/database/Uniqueness.java: -------------------------------------------------------------------------------- 1 | //: annotations/database/Uniqueness.java 2 | // Sample of nested annotations 3 | package annotations.database; 4 | 5 | public @interface Uniqueness { 6 | Constraints constraints() 7 | default @Constraints(unique=true); 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/arrays/ArrayOfGenericType.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | // Arrays of generic types won't compile. 3 | 4 | public class ArrayOfGenericType { 5 | T[] array; // OK 6 | @SuppressWarnings("unchecked") 7 | public ArrayOfGenericType(int size) { 8 | //! array = new T[size]; // Illegal 9 | array = (T[])new Object[size]; // "unchecked" Warning 10 | } 11 | // Illegal: 12 | //! public U[] makeArray() { return new U[10]; } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/arrays/AssemblingMultidimensionalArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | // Creating multidimensional arrays. 3 | import java.util.*; 4 | 5 | public class AssemblingMultidimensionalArrays { 6 | public static void main(String[] args) { 7 | Integer[][] a; 8 | a = new Integer[3][]; 9 | for(int i = 0; i < a.length; i++) { 10 | a[i] = new Integer[3]; 11 | for(int j = 0; j < a[i].length; j++) 12 | a[i][j] = i * j; // Autoboxing 13 | } 14 | System.out.println(Arrays.deepToString(a)); 15 | } 16 | } /* Output: 17 | [[0, 0, 0], [0, 1, 2], [0, 2, 4]] 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/arrays/AutoboxingArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.*; 3 | 4 | public class AutoboxingArrays { 5 | public static void main(String[] args) { 6 | Integer[][] a = { // Autoboxing: 7 | { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 8 | { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 }, 9 | { 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 }, 10 | { 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 }, 11 | }; 12 | System.out.println(Arrays.deepToString(a)); 13 | } 14 | } /* Output: 15 | [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [71, 72, 73, 74, 75, 76, 77, 78, 79, 80]] 16 | *///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/arrays/ComparingArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | // Using Arrays.equals() 3 | import java.util.*; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class ComparingArrays { 7 | public static void main(String[] args) { 8 | int[] a1 = new int[10]; 9 | int[] a2 = new int[10]; 10 | Arrays.fill(a1, 47); 11 | Arrays.fill(a2, 47); 12 | print(Arrays.equals(a1, a2)); 13 | a2[3] = 11; 14 | print(Arrays.equals(a1, a2)); 15 | String[] s1 = new String[4]; 16 | Arrays.fill(s1, "Hi"); 17 | String[] s2 = { new String("Hi"), new String("Hi"), 18 | new String("Hi"), new String("Hi") }; 19 | print(Arrays.equals(s1, s2)); 20 | } 21 | } /* Output: 22 | true 23 | false 24 | true 25 | *///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/arrays/MultidimensionalPrimitiveArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | // Creating multidimensional arrays. 3 | import java.util.*; 4 | 5 | public class MultidimensionalPrimitiveArray { 6 | public static void main(String[] args) { 7 | int[][] a = { 8 | { 1, 2, 3, }, 9 | { 4, 5, 6, }, 10 | }; 11 | System.out.println(Arrays.deepToString(a)); 12 | } 13 | } /* Output: 14 | [[1, 2, 3], [4, 5, 6]] 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/arrays/ParameterizedArrayType.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | class ClassParameter { 4 | public T[] f(T[] arg) { return arg; } 5 | } 6 | 7 | class MethodParameter { 8 | public static T[] f(T[] arg) { return arg; } 9 | } 10 | 11 | public class ParameterizedArrayType { 12 | public static void main(String[] args) { 13 | Integer[] ints = { 1, 2, 3, 4, 5 }; 14 | Double[] doubles = { 1.1, 2.2, 3.3, 4.4, 5.5 }; 15 | Integer[] ints2 = 16 | new ClassParameter().f(ints); 17 | Double[] doubles2 = 18 | new ClassParameter().f(doubles); 19 | ints2 = MethodParameter.f(ints); 20 | doubles2 = MethodParameter.f(doubles); 21 | } 22 | } ///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/arrays/PrimitiveConversionDemonstration.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.*; 3 | import net.mindview.util.*; 4 | 5 | public class PrimitiveConversionDemonstration { 6 | public static void main(String[] args) { 7 | Integer[] a = Generated.array(Integer.class, 8 | new CountingGenerator.Integer(), 15); 9 | int[] b = ConvertTo.primitive(a); 10 | System.out.println(Arrays.toString(b)); 11 | boolean[] c = ConvertTo.primitive( 12 | Generated.array(Boolean.class, 13 | new CountingGenerator.Boolean(), 7)); 14 | System.out.println(Arrays.toString(c)); 15 | } 16 | } /* Output: 17 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 18 | [true, false, true, false, true, false, true] 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/arrays/RaggedArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.*; 3 | 4 | public class RaggedArray { 5 | public static void main(String[] args) { 6 | Random rand = new Random(47); 7 | // 3-D array with varied-length vectors: 8 | int[][][] a = new int[rand.nextInt(7)][][]; 9 | for(int i = 0; i < a.length; i++) { 10 | a[i] = new int[rand.nextInt(5)][]; 11 | for(int j = 0; j < a[i].length; j++) 12 | a[i][j] = new int[rand.nextInt(5)]; 13 | } 14 | System.out.println(Arrays.deepToString(a)); 15 | } 16 | } /* Output: 17 | [[], [[0], [0], [0, 0, 0, 0]], [[], [0, 0], [0, 0]], [[0, 0, 0], [0], [0, 0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0], []], [[0], [], [0]]] 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/arrays/TestGenerated.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.*; 3 | import net.mindview.util.*; 4 | 5 | public class TestGenerated { 6 | public static void main(String[] args) { 7 | Integer[] a = { 9, 8, 7, 6 }; 8 | System.out.println(Arrays.toString(a)); 9 | a = Generated.array(a,new CountingGenerator.Integer()); 10 | System.out.println(Arrays.toString(a)); 11 | Integer[] b = Generated.array(Integer.class, 12 | new CountingGenerator.Integer(), 15); 13 | System.out.println(Arrays.toString(b)); 14 | } 15 | } /* Output: 16 | [9, 8, 7, 6] 17 | [0, 1, 2, 3] 18 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/arrays/ThreeDWithNew.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | import java.util.*; 3 | 4 | public class ThreeDWithNew { 5 | public static void main(String[] args) { 6 | // 3-D array with fixed length: 7 | int[][][] a = new int[2][2][4]; 8 | System.out.println(Arrays.deepToString(a)); 9 | } 10 | } /* Output: 11 | [[[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0]]] 12 | *///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/concurrency/AtomicEvenGenerator.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Atomic classes are occasionally useful in regular code. 3 | // {RunByHand} 4 | import java.util.concurrent.atomic.*; 5 | 6 | public class AtomicEvenGenerator extends IntGenerator { 7 | private AtomicInteger currentEvenValue = 8 | new AtomicInteger(0); 9 | public int next() { 10 | return currentEvenValue.addAndGet(2); 11 | } 12 | public static void main(String[] args) { 13 | EvenChecker.test(new AtomicEvenGenerator()); 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/concurrency/Atomicity.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // {Exec: javap -c Atomicity} 3 | 4 | public class Atomicity { 5 | int i; 6 | void f1() { i++; } 7 | void f2() { i += 3; } 8 | } /* Output: (Sample) 9 | ... 10 | void f1(); 11 | Code: 12 | 0: aload_0 13 | 1: dup 14 | 2: getfield #2; //Field i:I 15 | 5: iconst_1 16 | 6: iadd 17 | 7: putfield #2; //Field i:I 18 | 10: return 19 | 20 | void f2(); 21 | Code: 22 | 0: aload_0 23 | 1: dup 24 | 2: getfield #2; //Field i:I 25 | 5: iconst_3 26 | 6: iadd 27 | 7: putfield #2; //Field i:I 28 | 10: return 29 | *///:~ 30 | -------------------------------------------------------------------------------- /src/main/java/concurrency/BasicThreads.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // The most basic use of the Thread class. 3 | 4 | public class BasicThreads { 5 | public static void main(String[] args) { 6 | Thread t = new Thread(new LiftOff()); 7 | t.start(); 8 | System.out.println("Waiting for LiftOff"); 9 | } 10 | } /* Output: (90% match) 11 | Waiting for LiftOff 12 | #0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!), 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/concurrency/Chopstick.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Chopsticks for dining philosophers. 3 | 4 | public class Chopstick { 5 | private boolean taken = false; 6 | public synchronized 7 | void take() throws InterruptedException { 8 | while(taken) 9 | wait(); 10 | taken = true; 11 | } 12 | public synchronized void drop() { 13 | taken = false; 14 | notifyAll(); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/concurrency/EvenGenerator.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // When threads collide. 3 | 4 | public class EvenGenerator extends IntGenerator { 5 | private int currentEvenValue = 0; 6 | public int next() { 7 | ++currentEvenValue; // Danger point here! 8 | ++currentEvenValue; 9 | return currentEvenValue; 10 | } 11 | public static void main(String[] args) { 12 | EvenChecker.test(new EvenGenerator()); 13 | } 14 | } /* Output: (Sample) 15 | Press Control-C to exit 16 | 89476993 not even! 17 | 89476993 not even! 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/concurrency/ExceptionThread.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // {ThrowsException} 3 | import java.util.concurrent.*; 4 | 5 | public class ExceptionThread implements Runnable { 6 | public void run() { 7 | throw new RuntimeException(); 8 | } 9 | public static void main(String[] args) { 10 | ExecutorService exec = Executors.newCachedThreadPool(); 11 | exec.execute(new ExceptionThread()); 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/concurrency/Fat.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Objects that are expensive to create. 3 | 4 | public class Fat { 5 | private volatile double d; // Prevent optimization 6 | private static int counter = 0; 7 | private final int id = counter++; 8 | public Fat() { 9 | // Expensive, interruptible operation: 10 | for(int i = 1; i < 10000; i++) { 11 | d += (Math.PI + Math.E) / (double)i; 12 | } 13 | } 14 | public void operation() { System.out.println(this); } 15 | public String toString() { return "Fat id: " + id; } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/concurrency/IntGenerator.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | 3 | public abstract class IntGenerator { 4 | private volatile boolean canceled = false; 5 | public abstract int next(); 6 | // Allow this to be canceled: 7 | public void cancel() { canceled = true; } 8 | public boolean isCanceled() { return canceled; } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/concurrency/LiftOff.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Demonstration of the Runnable interface. 3 | 4 | public class LiftOff implements Runnable { 5 | protected int countDown = 10; // Default 6 | private static int taskCount = 0; 7 | private final int id = taskCount++; 8 | public LiftOff() {} 9 | public LiftOff(int countDown) { 10 | this.countDown = countDown; 11 | } 12 | public String status() { 13 | return "#" + id + "(" + 14 | (countDown > 0 ? countDown : "Liftoff!") + "), "; 15 | } 16 | public void run() { 17 | while(countDown-- > 0) { 18 | System.out.print(status()); 19 | Thread.yield(); 20 | } 21 | } 22 | } ///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/concurrency/MainThread.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | 3 | public class MainThread { 4 | public static void main(String[] args) { 5 | LiftOff launch = new LiftOff(); 6 | launch.run(); 7 | } 8 | } /* Output: 9 | #0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!), 10 | *///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/concurrency/MoreBasicThreads.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Adding more threads. 3 | 4 | public class MoreBasicThreads { 5 | public static void main(String[] args) { 6 | for(int i = 0; i < 5; i++) 7 | new Thread(new LiftOff()).start(); 8 | System.out.println("Waiting for LiftOff"); 9 | } 10 | } /* Output: (Sample) 11 | Waiting for LiftOff 12 | #0(9), #1(9), #2(9), #3(9), #4(9), #0(8), #1(8), #2(8), #3(8), #4(8), #0(7), #1(7), #2(7), #3(7), #4(7), #0(6), #1(6), #2(6), #3(6), #4(6), #0(5), #1(5), #2(5), #3(5), #4(5), #0(4), #1(4), #2(4), #3(4), #4(4), #0(3), #1(3), #2(3), #3(3), #4(3), #0(2), #1(2), #2(2), #3(2), #4(2), #0(1), #1(1), #2(1), #3(1), #4(1), #0(Liftoff!), #1(Liftoff!), #2(Liftoff!), #3(Liftoff!), #4(Liftoff!), 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/concurrency/MutexEvenGenerator.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Preventing thread collisions with mutexes. 3 | // {RunByHand} 4 | import java.util.concurrent.locks.*; 5 | 6 | public class MutexEvenGenerator extends IntGenerator { 7 | private int currentEvenValue = 0; 8 | private Lock lock = new ReentrantLock(); 9 | public int next() { 10 | lock.lock(); 11 | try { 12 | ++currentEvenValue; 13 | Thread.yield(); // Cause failure faster 14 | ++currentEvenValue; 15 | return currentEvenValue; 16 | } finally { 17 | lock.unlock(); 18 | } 19 | } 20 | public static void main(String[] args) { 21 | EvenChecker.test(new MutexEvenGenerator()); 22 | } 23 | } ///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/concurrency/NaiveExceptionHandling.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // {ThrowsException} 3 | import java.util.concurrent.*; 4 | 5 | public class NaiveExceptionHandling { 6 | public static void main(String[] args) { 7 | try { 8 | ExecutorService exec = 9 | Executors.newCachedThreadPool(); 10 | exec.execute(new ExceptionThread()); 11 | } catch(RuntimeException ue) { 12 | // This statement will NOT execute! 13 | System.out.println("Exception has been handled!"); 14 | } 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/concurrency/SerialNumberGenerator.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | 3 | public class SerialNumberGenerator { 4 | private static volatile int serialNumber = 0; 5 | public static int nextSerialNumber() { 6 | return serialNumber++; // Not thread-safe 7 | } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/concurrency/SettingDefaultHandler.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | import java.util.concurrent.*; 3 | 4 | public class SettingDefaultHandler { 5 | public static void main(String[] args) { 6 | Thread.setDefaultUncaughtExceptionHandler( 7 | new MyUncaughtExceptionHandler()); 8 | ExecutorService exec = Executors.newCachedThreadPool(); 9 | exec.execute(new ExceptionThread()); 10 | } 11 | } /* Output: 12 | caught java.lang.RuntimeException 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/concurrency/SynchronizedEvenGenerator.java: -------------------------------------------------------------------------------- 1 | package concurrency; 2 | // Simplifying mutexes with the synchronized keyword. 3 | // {RunByHand} 4 | 5 | public class 6 | SynchronizedEvenGenerator extends IntGenerator { 7 | private int currentEvenValue = 0; 8 | public synchronized int next() { 9 | ++currentEvenValue; 10 | Thread.yield(); // Cause failure faster 11 | ++currentEvenValue; 12 | return currentEvenValue; 13 | } 14 | public static void main(String[] args) { 15 | EvenChecker.test(new SynchronizedEvenGenerator()); 16 | } 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/containers/Enumerations.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // Java 1.0/1.1 Vector and Enumeration. 3 | import java.util.*; 4 | import net.mindview.util.*; 5 | 6 | public class Enumerations { 7 | public static void main(String[] args) { 8 | Vector v = 9 | new Vector(Countries.names(10)); 10 | Enumeration e = v.elements(); 11 | while(e.hasMoreElements()) 12 | System.out.print(e.nextElement() + ", "); 13 | // Produce an Enumeration from a Collection: 14 | e = Collections.enumeration(new ArrayList()); 15 | } 16 | } /* Output: 17 | ALGERIA, ANGOLA, BENIN, BOTSWANA, BULGARIA, BURKINA FASO, BURUNDI, CAMEROON, CAPE VERDE, CENTRAL AFRICAN REPUBLIC, 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/containers/FailFast.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // Demonstrates the "fail-fast" behavior. 3 | import java.util.*; 4 | 5 | public class FailFast { 6 | public static void main(String[] args) { 7 | Collection c = new ArrayList(); 8 | Iterator it = c.iterator(); 9 | c.add("An object"); 10 | try { 11 | String s = it.next(); 12 | } catch(ConcurrentModificationException e) { 13 | System.out.println(e); 14 | } 15 | } 16 | } /* Output: 17 | java.util.ConcurrentModificationException 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/containers/Groundhog.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // Looks plausible, but doesn't work as a HashMap key. 3 | 4 | public class Groundhog { 5 | protected int number; 6 | public Groundhog(int n) { number = n; } 7 | public String toString() { 8 | return "Groundhog #" + number; 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/containers/Groundhog2.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // A class that's used as a key in a HashMap 3 | // must override hashCode() and equals(). 4 | 5 | public class Groundhog2 extends Groundhog { 6 | public Groundhog2(int n) { super(n); } 7 | public int hashCode() { return number; } 8 | public boolean equals(Object o) { 9 | return o instanceof Groundhog2 && 10 | (number == ((Groundhog2)o).number); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/containers/IndividualTest.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | import holding.MapOfList; 3 | import typeinfo.pets.*; 4 | import java.util.*; 5 | 6 | public class IndividualTest { 7 | public static void main(String[] args) { 8 | Set pets = new TreeSet(); 9 | for(List lp : 10 | MapOfList.petPeople.values()) 11 | for(Pet p : lp) 12 | pets.add(p); 13 | System.out.println(pets); 14 | } 15 | } /* Output: 16 | [Cat Elsie May, Cat Pinkola, Cat Shackleton, Cat Stanford aka Stinky el Negro, Cymric Molly, Dog Margrett, Mutt Spot, Pug Louie aka Louis Snorkelstein Dupree, Rat Fizzy, Rat Freckly, Rat Fuzzy] 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/containers/Prediction.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // Predicting the weather with groundhogs. 3 | import java.util.*; 4 | 5 | public class Prediction { 6 | private static Random rand = new Random(47); 7 | private boolean shadow = rand.nextDouble() > 0.5; 8 | public String toString() { 9 | if(shadow) 10 | return "Six more weeks of Winter!"; 11 | else 12 | return "Early Spring!"; 13 | } 14 | } ///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/containers/SpringDetector2.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // A working key. 3 | 4 | public class SpringDetector2 { 5 | public static void main(String[] args) throws Exception { 6 | SpringDetector.detectSpring(Groundhog2.class); 7 | } 8 | } /* Output: 9 | 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!} 10 | Looking up prediction for Groundhog #3 11 | Early Spring! 12 | *///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/containers/StringHashCode.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | 3 | public class StringHashCode { 4 | public static void main(String[] args) { 5 | String[] hellos = "Hello Hello".split(" "); 6 | System.out.println(hellos[0].hashCode()); 7 | System.out.println(hellos[1].hashCode()); 8 | } 9 | } /* Output: (Sample) 10 | 69609650 11 | 69609650 12 | *///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/containers/Test.java: -------------------------------------------------------------------------------- 1 | package containers; 2 | // Framework for performing timed tests of containers. 3 | 4 | public abstract class Test { 5 | String name; 6 | public Test(String name) { this.name = name; } 7 | // Override this method for different tests. 8 | // Returns actual number of repetitions of test. 9 | abstract int test(C container, TestParam tp); 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/control/CommaOperator.java: -------------------------------------------------------------------------------- 1 | //: control/CommaOperator.java 2 | package control; 3 | public class CommaOperator { 4 | public static void main(String[] args) { 5 | for(int i = 1, j = i + 10; i < 5; i++, j = i * 2) { 6 | System.out.println("i = " + i + " j = " + j); 7 | } 8 | } 9 | } /* Output: 10 | i = 1 j = 11 11 | i = 2 j = 4 12 | i = 3 j = 6 13 | i = 4 j = 8 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/control/ForEachFloat.java: -------------------------------------------------------------------------------- 1 | //: control/ForEachFloat.java 2 | package control; 3 | import java.util.*; 4 | 5 | public class ForEachFloat { 6 | public static void main(String[] args) { 7 | Random rand = new Random(47); 8 | float f[] = new float[10]; 9 | for(int i = 0; i < 10; i++) 10 | f[i] = rand.nextFloat(); 11 | for(float x : f) 12 | System.out.println(x); 13 | } 14 | } /* Output: 15 | 0.72711575 16 | 0.39982635 17 | 0.5309454 18 | 0.0534122 19 | 0.16020656 20 | 0.57799757 21 | 0.18847865 22 | 0.4170137 23 | 0.51660204 24 | 0.73734957 25 | *///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/control/ForEachInt.java: -------------------------------------------------------------------------------- 1 | //: control/ForEachInt.java 2 | package control; 3 | import static net.mindview.util.Range.*; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class ForEachInt { 7 | public static void main(String[] args) { 8 | for(int i : range(10)) // 0..9 9 | printnb(i + " "); 10 | print(); 11 | for(int i : range(5, 10)) // 5..9 12 | printnb(i + " "); 13 | print(); 14 | for(int i : range(5, 20, 3)) // 5..20 step 3 15 | printnb(i + " "); 16 | print(); 17 | } 18 | } /* Output: 19 | 0 1 2 3 4 5 6 7 8 9 20 | 5 6 7 8 9 21 | 5 8 11 14 17 22 | *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/control/ForEachString.java: -------------------------------------------------------------------------------- 1 | //: control/ForEachString.java 2 | package control; 3 | public class ForEachString { 4 | public static void main(String[] args) { 5 | for(char c : "An African Swallow".toCharArray() ) 6 | System.out.print(c + " "); 7 | } 8 | } /* Output: 9 | A n A f r i c a n S w a l l o w 10 | *///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/control/IfElse.java: -------------------------------------------------------------------------------- 1 | //: control/IfElse.java 2 | package control; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class IfElse { 6 | static int result = 0; 7 | static void test(int testval, int target) { 8 | if(testval > target) 9 | result = +1; 10 | else if(testval < target) 11 | result = -1; 12 | else 13 | result = 0; // Match 14 | } 15 | public static void main(String[] args) { 16 | test(10, 5); 17 | print(result); 18 | test(5, 10); 19 | print(result); 20 | test(5, 5); 21 | print(result); 22 | } 23 | } /* Output: 24 | 1 25 | -1 26 | 0 27 | *///:~ 28 | -------------------------------------------------------------------------------- /src/main/java/control/IfElse2.java: -------------------------------------------------------------------------------- 1 | //: control/IfElse2.java 2 | package control; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class IfElse2 { 6 | static int test(int testval, int target) { 7 | if(testval > target) 8 | return +1; 9 | else if(testval < target) 10 | return -1; 11 | else 12 | return 0; // Match 13 | } 14 | public static void main(String[] args) { 15 | print(test(10, 5)); 16 | print(test(5, 10)); 17 | print(test(5, 5)); 18 | } 19 | } /* Output: 20 | 1 21 | -1 22 | 0 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/control/ListCharacters.java: -------------------------------------------------------------------------------- 1 | //: control/ListCharacters.java 2 | // Demonstrates "for" loop by listing 3 | // all the lowercase ASCII letters. 4 | package control; 5 | public class ListCharacters { 6 | public static void main(String[] args) { 7 | for(char c = 0; c < 128; c++) 8 | if(Character.isLowerCase(c)) 9 | System.out.println("value: " + (int)c + 10 | " character: " + c); 11 | } 12 | } /* Output: 13 | value: 97 character: a 14 | value: 98 character: b 15 | value: 99 character: c 16 | value: 100 character: d 17 | value: 101 character: e 18 | value: 102 character: f 19 | value: 103 character: g 20 | value: 104 character: h 21 | value: 105 character: i 22 | value: 106 character: j 23 | ... 24 | *///:~ 25 | -------------------------------------------------------------------------------- /src/main/java/control/WhileTest.java: -------------------------------------------------------------------------------- 1 | //: control/WhileTest.java 2 | // Demonstrates the while loop. 3 | package control; 4 | public class WhileTest { 5 | static boolean condition() { 6 | boolean result = Math.random() < 0.99; 7 | System.out.print(result + ", "); 8 | return result; 9 | } 10 | public static void main(String[] args) { 11 | while(condition()) 12 | System.out.println("Inside 'while'"); 13 | System.out.println("Exited 'while'"); 14 | } 15 | } /* (Execute to see output) *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/enumerated/AlarmPoints.java: -------------------------------------------------------------------------------- 1 | //: enumerated/AlarmPoints.java 2 | package enumerated; 3 | public enum AlarmPoints { 4 | STAIR1, STAIR2, LOBBY, OFFICE1, OFFICE2, OFFICE3, 5 | OFFICE4, BATHROOM, UTILITY, KITCHEN 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/enumerated/Burrito.java: -------------------------------------------------------------------------------- 1 | //: enumerated/Burrito.java 2 | package enumerated; 3 | import static enumerated.Spiciness.*; 4 | 5 | public class Burrito { 6 | Spiciness degree; 7 | public Burrito(Spiciness degree) { this.degree = degree;} 8 | public String toString() { return "Burrito is "+ degree;} 9 | public static void main(String[] args) { 10 | System.out.println(new Burrito(NOT)); 11 | System.out.println(new Burrito(MEDIUM)); 12 | System.out.println(new Burrito(HOT)); 13 | } 14 | } /* Output: 15 | Burrito is NOT 16 | Burrito is MEDIUM 17 | Burrito is HOT 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/enumerated/Competitor.java: -------------------------------------------------------------------------------- 1 | //: enumerated/Competitor.java 2 | // Switching one enum on another. 3 | package enumerated; 4 | 5 | public interface Competitor> { 6 | Outcome compete(T competitor); 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/enumerated/ConstantSpecificMethod.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | import java.util.*; 3 | import java.text.*; 4 | 5 | public enum ConstantSpecificMethod { 6 | DATE_TIME { 7 | String getInfo() { 8 | return 9 | DateFormat.getDateInstance().format(new Date()); 10 | } 11 | }, 12 | CLASSPATH { 13 | String getInfo() { 14 | return System.getenv("CLASSPATH"); 15 | } 16 | }, 17 | VERSION { 18 | String getInfo() { 19 | return System.getProperty("java.version"); 20 | } 21 | }; 22 | abstract String getInfo(); 23 | public static void main(String[] args) { 24 | for(ConstantSpecificMethod csm : values()) 25 | System.out.println(csm.getInfo()); 26 | } 27 | } /* (Execute to see output) *///:~ 28 | -------------------------------------------------------------------------------- /src/main/java/enumerated/NonEnum.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | 3 | public class NonEnum { 4 | public static void main(String[] args) { 5 | Class intClass = Integer.class; 6 | try { 7 | for(Object en : intClass.getEnumConstants()) 8 | System.out.println(en); 9 | } catch(Exception e) { 10 | System.out.println(e); 11 | } 12 | } 13 | } /* Output: 14 | java.lang.NullPointerException 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/enumerated/NotClasses.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | // {Exec: javap -c LikeClasses} 3 | import static net.mindview.util.Print.*; 4 | 5 | enum LikeClasses { 6 | WINKEN { void behavior() { print("Behavior1"); } }, 7 | BLINKEN { void behavior() { print("Behavior2"); } }, 8 | NOD { void behavior() { print("Behavior3"); } }; 9 | abstract void behavior(); 10 | } 11 | 12 | public class NotClasses { 13 | // void f1(LikeClasses.WINKEN instance) {} // Nope 14 | } /* Output: 15 | Compiled from "NotClasses.java" 16 | abstract class LikeClasses extends java.lang.Enum{ 17 | public static final LikeClasses WINKEN; 18 | 19 | public static final LikeClasses BLINKEN; 20 | 21 | public static final LikeClasses NOD; 22 | ... 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/enumerated/Outcome.java: -------------------------------------------------------------------------------- 1 | //: enumerated/Outcome.java 2 | package enumerated; 3 | public enum Outcome { WIN, LOSE, DRAW } ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/enumerated/OverrideConstantSpecific.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | import static net.mindview.util.Print.*; 3 | 4 | public enum OverrideConstantSpecific { 5 | NUT, BOLT, 6 | WASHER { 7 | void f() { print("Overridden method"); } 8 | }; 9 | void f() { print("default behavior"); } 10 | public static void main(String[] args) { 11 | for(OverrideConstantSpecific ocs : values()) { 12 | printnb(ocs + ": "); 13 | ocs.f(); 14 | } 15 | } 16 | } /* Output: 17 | NUT: default behavior 18 | BOLT: default behavior 19 | WASHER: Overridden method 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/enumerated/RandomTest.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | import net.mindview.util.*; 3 | 4 | enum Activity { SITTING, LYING, STANDING, HOPPING, 5 | RUNNING, DODGING, JUMPING, FALLING, FLYING } 6 | 7 | public class RandomTest { 8 | public static void main(String[] args) { 9 | for(int i = 0; i < 20; i++) 10 | System.out.print(Enums.random(Activity.class) + " "); 11 | } 12 | } /* Output: 13 | STANDING FLYING RUNNING STANDING RUNNING STANDING LYING DODGING SITTING RUNNING HOPPING HOPPING HOPPING RUNNING STANDING LYING FALLING RUNNING FLYING LYING 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/enumerated/RoShamBo.java: -------------------------------------------------------------------------------- 1 | //: enumerated/RoShamBo.java 2 | // Common tools for RoShamBo examples. 3 | package enumerated; 4 | import net.mindview.util.*; 5 | 6 | public class RoShamBo { 7 | public static > 8 | void match(T a, T b) { 9 | System.out.println( 10 | a + " vs. " + b + ": " + a.compete(b)); 11 | } 12 | public static & Competitor> 13 | void play(Class rsbClass, int size) { 14 | for(int i = 0; i < size; i++) 15 | match( 16 | Enums.random(rsbClass),Enums.random(rsbClass)); 17 | } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/enumerated/RoShamBo6.java: -------------------------------------------------------------------------------- 1 | //: enumerated/RoShamBo6.java 2 | // Enums using "tables" instead of multiple dispatch. 3 | package enumerated; 4 | import static enumerated.Outcome.*; 5 | 6 | enum RoShamBo6 implements Competitor { 7 | PAPER, SCISSORS, ROCK; 8 | private static Outcome[][] table = { 9 | { DRAW, LOSE, WIN }, // PAPER 10 | { WIN, DRAW, LOSE }, // SCISSORS 11 | { LOSE, WIN, DRAW }, // ROCK 12 | }; 13 | public Outcome compete(RoShamBo6 other) { 14 | return table[this.ordinal()][other.ordinal()]; 15 | } 16 | public static void main(String[] args) { 17 | RoShamBo.play(RoShamBo6.class, 20); 18 | } 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/enumerated/SpaceShip.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | public enum SpaceShip { 3 | SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP; 4 | public String toString() { 5 | String id = name(); 6 | String lower = id.substring(1).toLowerCase(); 7 | return id.charAt(0) + lower; 8 | } 9 | public static void main(String[] args) { 10 | for(SpaceShip s : values()) { 11 | System.out.println(s); 12 | } 13 | } 14 | } /* Output: 15 | Scout 16 | Cargo 17 | Transport 18 | Cruiser 19 | Battleship 20 | Mothership 21 | *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/enumerated/Spiciness.java: -------------------------------------------------------------------------------- 1 | //: enumerated/Spiciness.java 2 | package enumerated; 3 | 4 | public enum Spiciness { 5 | NOT, MILD, MEDIUM, HOT, FLAMING 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/enumerated/UpcastEnum.java: -------------------------------------------------------------------------------- 1 | package enumerated; 2 | // No values() method if you upcast an enum 3 | 4 | enum Search { HITHER, YON } 5 | 6 | public class UpcastEnum { 7 | public static void main(String[] args) { 8 | Search[] vals = Search.values(); 9 | Enum e = Search.HITHER; // Upcast 10 | // e.values(); // No values() in Enum 11 | for(Enum en : e.getClass().getEnumConstants()) 12 | System.out.println(en); 13 | } 14 | } /* Output: 15 | HITHER 16 | YON 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/enumerated/menu/Course.java: -------------------------------------------------------------------------------- 1 | //: enumerated/menu/Course.java 2 | package enumerated.menu; 3 | import net.mindview.util.*; 4 | 5 | public enum Course { 6 | APPETIZER(Food.Appetizer.class), 7 | MAINCOURSE(Food.MainCourse.class), 8 | DESSERT(Food.Dessert.class), 9 | COFFEE(Food.Coffee.class); 10 | private Food[] values; 11 | private Course(Class kind) { 12 | values = kind.getEnumConstants(); 13 | } 14 | public Food randomSelection() { 15 | return Enums.random(values); 16 | } 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/enumerated/menu/Food.java: -------------------------------------------------------------------------------- 1 | //: enumerated/menu/Food.java 2 | // Subcategorization of enums within interfaces. 3 | package enumerated.menu; 4 | 5 | public interface Food { 6 | enum Appetizer implements Food { 7 | SALAD, SOUP, SPRING_ROLLS; 8 | } 9 | enum MainCourse implements Food { 10 | LASAGNE, BURRITO, PAD_THAI, 11 | LENTILS, HUMMOUS, VINDALOO; 12 | } 13 | enum Dessert implements Food { 14 | TIRAMISU, GELATO, BLACK_FOREST_CAKE, 15 | FRUIT, CREME_CARAMEL; 16 | } 17 | enum Coffee implements Food { 18 | BLACK_COFFEE, DECAF_COFFEE, ESPRESSO, 19 | LATTE, CAPPUCCINO, TEA, HERB_TEA; 20 | } 21 | } ///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/enumerated/menu/Meal.java: -------------------------------------------------------------------------------- 1 | //: enumerated/menu/Meal.java 2 | package enumerated.menu; 3 | 4 | public class Meal { 5 | public static void main(String[] args) { 6 | for(int i = 0; i < 5; i++) { 7 | for(Course course : Course.values()) { 8 | Food food = course.randomSelection(); 9 | System.out.println(food); 10 | } 11 | System.out.println("---"); 12 | } 13 | } 14 | } /* Output: 15 | SPRING_ROLLS 16 | VINDALOO 17 | FRUIT 18 | DECAF_COFFEE 19 | --- 20 | SOUP 21 | VINDALOO 22 | FRUIT 23 | TEA 24 | --- 25 | SALAD 26 | BURRITO 27 | FRUIT 28 | TEA 29 | --- 30 | SALAD 31 | BURRITO 32 | CREME_CARAMEL 33 | LATTE 34 | --- 35 | SOUP 36 | BURRITO 37 | TIRAMISU 38 | ESPRESSO 39 | --- 40 | *///:~ 41 | -------------------------------------------------------------------------------- /src/main/java/enumerated/menu/TypeOfFood.java: -------------------------------------------------------------------------------- 1 | //: enumerated/menu/TypeOfFood.java 2 | package enumerated.menu; 3 | import static enumerated.menu.Food.*; 4 | 5 | public class TypeOfFood { 6 | public static void main(String[] args) { 7 | Food food = Appetizer.SALAD; 8 | food = MainCourse.LASAGNE; 9 | food = Dessert.GELATO; 10 | food = Coffee.CAPPUCCINO; 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/exceptions/ExceptionSilencer.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | 3 | public class ExceptionSilencer { 4 | public static void main(String[] args) { 5 | try { 6 | throw new RuntimeException(); 7 | } finally { 8 | // Using 'return' inside the finally block 9 | // will silence any thrown exception. 10 | return; 11 | } 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/exceptions/Human.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | // Catching exception hierarchies. 3 | 4 | class Annoyance extends Exception {} 5 | class Sneeze extends Annoyance {} 6 | 7 | public class Human { 8 | public static void main(String[] args) { 9 | // Catch the exact type: 10 | try { 11 | throw new Sneeze(); 12 | } catch(Sneeze s) { 13 | System.out.println("Caught Sneeze"); 14 | } catch(Annoyance a) { 15 | System.out.println("Caught Annoyance"); 16 | } 17 | // Catch the base type: 18 | try { 19 | throw new Sneeze(); 20 | } catch(Annoyance a) { 21 | System.out.println("Caught Annoyance"); 22 | } 23 | } 24 | } /* Output: 25 | Caught Sneeze 26 | Caught Annoyance 27 | *///:~ 28 | -------------------------------------------------------------------------------- /src/main/java/exceptions/InheritingExceptions.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | // Creating your own exceptions. 3 | 4 | class SimpleException extends Exception {} 5 | 6 | public class InheritingExceptions { 7 | public void f() throws SimpleException { 8 | System.out.println("Throw SimpleException from f()"); 9 | throw new SimpleException(); 10 | } 11 | public static void main(String[] args) { 12 | InheritingExceptions sed = new InheritingExceptions(); 13 | try { 14 | sed.f(); 15 | } catch(SimpleException e) { 16 | System.out.println("Caught it!"); 17 | } 18 | } 19 | } /* Output: 20 | Throw SimpleException from f() 21 | Caught it! 22 | *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/exceptions/MainException.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | import java.io.*; 3 | 4 | public class MainException { 5 | // Pass all exceptions to the console: 6 | public static void main(String[] args) throws Exception { 7 | // Open the file: 8 | FileInputStream file = 9 | new FileInputStream("MainException.java"); 10 | // Use the file ... 11 | // Close the file: 12 | file.close(); 13 | } 14 | } ///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/exceptions/NeverCaught.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | // Ignoring RuntimeExceptions. 3 | // {ThrowsException} 4 | 5 | public class NeverCaught { 6 | static void f() { 7 | throw new RuntimeException("From f()"); 8 | } 9 | static void g() { 10 | f(); 11 | } 12 | public static void main(String[] args) { 13 | g(); 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/exceptions/OnOffException1.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | public class OnOffException1 extends Exception {} ///:~ 3 | -------------------------------------------------------------------------------- /src/main/java/exceptions/OnOffException2.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | public class OnOffException2 extends Exception {} ///:~ 3 | -------------------------------------------------------------------------------- /src/main/java/exceptions/OnOffSwitch.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | // Why use finally? 3 | 4 | public class OnOffSwitch { 5 | private static Switch sw = new Switch(); 6 | public static void f() 7 | throws OnOffException1,OnOffException2 {} 8 | public static void main(String[] args) { 9 | try { 10 | sw.on(); 11 | // Code that can throw exceptions... 12 | f(); 13 | sw.off(); 14 | } catch(OnOffException1 e) { 15 | System.out.println("OnOffException1"); 16 | sw.off(); 17 | } catch(OnOffException2 e) { 18 | System.out.println("OnOffException2"); 19 | sw.off(); 20 | } 21 | } 22 | } /* Output: 23 | on 24 | off 25 | *///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/exceptions/Switch.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | import static net.mindview.util.Print.*; 3 | 4 | public class Switch { 5 | private boolean state = false; 6 | public boolean read() { return state; } 7 | public void on() { state = true; print(this); } 8 | public void off() { state = false; print(this); } 9 | public String toString() { return state ? "on" : "off"; } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/exceptions/WithFinally.java: -------------------------------------------------------------------------------- 1 | package exceptions; 2 | // Finally Guarantees cleanup. 3 | 4 | public class WithFinally { 5 | static Switch sw = new Switch(); 6 | public static void main(String[] args) { 7 | try { 8 | sw.on(); 9 | // Code that can throw exceptions... 10 | OnOffSwitch.f(); 11 | } catch(OnOffException1 e) { 12 | System.out.println("OnOffException1"); 13 | } catch(OnOffException2 e) { 14 | System.out.println("OnOffException2"); 15 | } finally { 16 | sw.off(); 17 | } 18 | } 19 | } /* Output: 20 | on 21 | off 22 | *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/generics/ArrayMaker.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.lang.reflect.*; 3 | import java.util.*; 4 | 5 | public class ArrayMaker { 6 | private Class kind; 7 | public ArrayMaker(Class kind) { this.kind = kind; } 8 | @SuppressWarnings("unchecked") 9 | T[] create(int size) { 10 | return (T[])Array.newInstance(kind, size); 11 | } 12 | public static void main(String[] args) { 13 | ArrayMaker stringMaker = 14 | new ArrayMaker(String.class); 15 | String[] stringArray = stringMaker.create(9); 16 | System.out.println(Arrays.toString(stringArray)); 17 | } 18 | } /* Output: 19 | [null, null, null, null, null, null, null, null, null] 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/generics/ArrayOfGeneric.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class ArrayOfGeneric { 4 | static final int SIZE = 100; 5 | static Generic[] gia; 6 | @SuppressWarnings("unchecked") 7 | public static void main(String[] args) { 8 | // Compiles; produces ClassCastException: 9 | //! gia = (Generic[])new Object[SIZE]; 10 | // Runtime type is the raw (erased) type: 11 | gia = (Generic[])new Generic[SIZE]; 12 | System.out.println(gia.getClass().getSimpleName()); 13 | gia[0] = new Generic(); 14 | //! gia[1] = new Object(); // Compile-time error 15 | // Discovers type mismatch at compile time: 16 | //! gia[2] = new Generic(); 17 | } 18 | } /* Output: 19 | Generic[] 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/generics/ArrayOfGenericReference.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Generic {} 4 | 5 | public class ArrayOfGenericReference { 6 | static Generic[] gia; 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/generics/BasicGeneratorDemo.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import net.mindview.util.*; 3 | 4 | public class BasicGeneratorDemo { 5 | public static void main(String[] args) { 6 | Generator gen = 7 | BasicGenerator.create(CountedObject.class); 8 | for(int i = 0; i < 5; i++) 9 | System.out.println(gen.next()); 10 | } 11 | } /* Output: 12 | CountedObject 0 13 | CountedObject 1 14 | CountedObject 2 15 | CountedObject 3 16 | CountedObject 4 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/generics/BasicHolder.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class BasicHolder { 4 | T element; 5 | void set(T arg) { element = arg; } 6 | T get() { return element; } 7 | void f() { 8 | System.out.println(element.getClass().getSimpleName()); 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/generics/ByteSet.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class ByteSet { 5 | Byte[] possibles = { 1,2,3,4,5,6,7,8,9 }; 6 | Set mySet = 7 | new HashSet(Arrays.asList(possibles)); 8 | // But you can't do this: 9 | // Set mySet2 = new HashSet( 10 | // Arrays.asList(1,2,3,4,5,6,7,8,9)); 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/generics/CRGWithBasicHolder.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Subtype extends BasicHolder {} 4 | 5 | public class CRGWithBasicHolder { 6 | public static void main(String[] args) { 7 | Subtype st1 = new Subtype(), st2 = new Subtype(); 8 | st1.set(st2); 9 | Subtype st3 = st1.get(); 10 | st1.f(); 11 | } 12 | } /* Output: 13 | Subtype 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/generics/ClassCasting.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | public class ClassCasting { 6 | @SuppressWarnings("unchecked") 7 | public void f(String[] args) throws Exception { 8 | ObjectInputStream in = new ObjectInputStream( 9 | new FileInputStream(args[0])); 10 | // Won't Compile: 11 | // List lw1 = 12 | // List.class.cast(in.readObject()); 13 | List lw2 = List.class.cast(in.readObject()); 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/generics/ComparablePet.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class ComparablePet 4 | implements Comparable { 5 | public int compareTo(ComparablePet arg) { return 0; } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/generics/CompilerIntelligence.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class CompilerIntelligence { 5 | public static void main(String[] args) { 6 | List flist = 7 | Arrays.asList(new Apple()); 8 | Apple a = (Apple)flist.get(0); // No warning 9 | flist.contains(new Apple()); // Argument is 'Object' 10 | flist.indexOf(new Apple()); // Argument is 'Object' 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/CountedObject.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class CountedObject { 4 | private static long counter = 0; 5 | private final long id = counter++; 6 | public long id() { return id; } 7 | public String toString() { return "CountedObject " + id;} 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/generics/CovariantReturnTypes.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Base {} 4 | class Derived extends Base {} 5 | 6 | interface OrdinaryGetter { 7 | Base get(); 8 | } 9 | 10 | interface DerivedGetter extends OrdinaryGetter { 11 | // Return type of overridden method is allowed to vary: 12 | Derived get(); 13 | } 14 | 15 | public class CovariantReturnTypes { 16 | void test(DerivedGetter d) { 17 | Derived d2 = d.get(); 18 | } 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/generics/CreatorGeneric.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | abstract class GenericWithCreate { 4 | final T element; 5 | GenericWithCreate() { element = create(); } 6 | abstract T create(); 7 | } 8 | 9 | class X {} 10 | 11 | class Creator extends GenericWithCreate { 12 | X create() { return new X(); } 13 | void f() { 14 | System.out.println(element.getClass().getSimpleName()); 15 | } 16 | } 17 | 18 | public class CreatorGeneric { 19 | public static void main(String[] args) { 20 | Creator c = new Creator(); 21 | c.f(); 22 | } 23 | } /* Output: 24 | X 25 | *///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/generics/CuriouslyRecurringGeneric.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class GenericType {} 4 | 5 | public class CuriouslyRecurringGeneric 6 | extends GenericType {} ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/generics/DogsAndRobots.cpp: -------------------------------------------------------------------------------- 1 | //: generics/DogsAndRobots.cpp 2 | 3 | class Dog { 4 | public: 5 | void speak() {} 6 | void sit() {} 7 | void reproduce() {} 8 | }; 9 | 10 | class Robot { 11 | public: 12 | void speak() {} 13 | void sit() {} 14 | void oilChange() { 15 | }; 16 | 17 | template void perform(T anything) { 18 | anything.speak(); 19 | anything.sit(); 20 | } 21 | 22 | int main() { 23 | Dog d; 24 | Robot r; 25 | perform(d); 26 | perform(r); 27 | } ///:~ 28 | -------------------------------------------------------------------------------- /src/main/java/generics/Erased.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // {CompileTimeError} (Won't compile) 3 | 4 | public class Erased { 5 | private final int SIZE = 100; 6 | public static void f(Object arg) { 7 | if(arg instanceof T) {} // Error 8 | T var = new T(); // Error 9 | T[] array = new T[SIZE]; // Error 10 | T[] array = (T)new Object[SIZE]; // Unchecked warning 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/ErasedTypeEquivalence.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class ErasedTypeEquivalence { 5 | public static void main(String[] args) { 6 | Class c1 = new ArrayList().getClass(); 7 | Class c2 = new ArrayList().getClass(); 8 | System.out.println(c1 == c2); 9 | } 10 | } /* Output: 11 | true 12 | *///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/ErasureAndInheritance.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class GenericBase { 4 | private T element; 5 | public void set(T arg) { arg = element; } 6 | public T get() { return element; } 7 | } 8 | 9 | class Derived1 extends GenericBase {} 10 | 11 | class Derived2 extends GenericBase {} // No warning 12 | 13 | // class Derived3 extends GenericBase {} 14 | // Strange error: 15 | // unexpected type found : ? 16 | // required: class or interface without bounds 17 | 18 | public class ErasureAndInheritance { 19 | @SuppressWarnings("unchecked") 20 | public static void main(String[] args) { 21 | Derived2 d2 = new Derived2(); 22 | Object obj = d2.get(); 23 | d2.set(obj); // Warning here! 24 | } 25 | } ///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/generics/ExplicitTypeSpecification.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import typeinfo.pets.*; 3 | import java.util.*; 4 | import net.mindview.util.*; 5 | 6 | public class ExplicitTypeSpecification { 7 | static void f(Map> petPeople) {} 8 | public static void main(String[] args) { 9 | f(New.>map()); 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/generics/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // Generate a Fibonacci sequence. 3 | import net.mindview.util.*; 4 | 5 | public class Fibonacci implements Generator { 6 | private int count = 0; 7 | public Integer next() { return fib(count++); } 8 | private int fib(int n) { 9 | if(n < 2) return 1; 10 | return fib(n-2) + fib(n-1); 11 | } 12 | public static void main(String[] args) { 13 | Fibonacci gen = new Fibonacci(); 14 | for(int i = 0; i < 18; i++) 15 | System.out.print(gen.next() + " "); 16 | } 17 | } /* Output: 18 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/generics/FilledListMaker.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class FilledListMaker { 5 | List create(T t, int n) { 6 | List result = new ArrayList(); 7 | for(int i = 0; i < n; i++) 8 | result.add(t); 9 | return result; 10 | } 11 | public static void main(String[] args) { 12 | FilledListMaker stringMaker = 13 | new FilledListMaker(); 14 | List list = stringMaker.create("Hello", 4); 15 | System.out.println(list); 16 | } 17 | } /* Output: 18 | [Hello, Hello, Hello, Hello] 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/generics/GenericArray.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class GenericArray { 4 | private T[] array; 5 | @SuppressWarnings("unchecked") 6 | public GenericArray(int sz) { 7 | array = (T[])new Object[sz]; 8 | } 9 | public void put(int index, T item) { 10 | array[index] = item; 11 | } 12 | public T get(int index) { return array[index]; } 13 | // Method that exposes the underlying representation: 14 | public T[] rep() { return array; } 15 | public static void main(String[] args) { 16 | GenericArray gai = 17 | new GenericArray(10); 18 | // This causes a ClassCastException: 19 | //! Integer[] ia = gai.rep(); 20 | // This is OK: 21 | Object[] oa = gai.rep(); 22 | } 23 | } ///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/generics/GenericHolder.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class GenericHolder { 4 | private T obj; 5 | public void set(T obj) { this.obj = obj; } 6 | public T get() { return obj; } 7 | public static void main(String[] args) { 8 | GenericHolder holder = 9 | new GenericHolder(); 10 | holder.set("Item"); 11 | String s = holder.get(); 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/generics/GenericMethods.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class GenericMethods { 4 | public void f(T x) { 5 | System.out.println(x.getClass().getName()); 6 | } 7 | public static void main(String[] args) { 8 | GenericMethods gm = new GenericMethods(); 9 | gm.f(""); 10 | gm.f(1); 11 | gm.f(1.0); 12 | gm.f(1.0F); 13 | gm.f('c'); 14 | gm.f(gm); 15 | } 16 | } /* Output: 17 | java.lang.String 18 | java.lang.Integer 19 | java.lang.Double 20 | java.lang.Float 21 | java.lang.Character 22 | GenericMethods 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/generics/GenericVarargs.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class GenericVarargs { 5 | public static List makeList(T... args) { 6 | List result = new ArrayList(); 7 | for(T item : args) 8 | result.add(item); 9 | return result; 10 | } 11 | public static void main(String[] args) { 12 | List ls = makeList("A"); 13 | System.out.println(ls); 14 | ls = makeList("A", "B", "C"); 15 | System.out.println(ls); 16 | ls = makeList("ABCDEFFHIJKLMNOPQRSTUVWXYZ".split("")); 17 | System.out.println(ls); 18 | } 19 | } /* Output: 20 | [A] 21 | [A, B, C] 22 | [, A, B, C, D, E, F, F, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z] 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/generics/GenericsAndCovariance.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class GenericsAndCovariance { 5 | public static void main(String[] args) { 6 | // Wildcards allow covariance: 7 | List flist = new ArrayList(); 8 | // Compile Error: can't add any type of object: 9 | // flist.add(new Apple()); 10 | // flist.add(new Fruit()); 11 | // flist.add(new Object()); 12 | flist.add(null); // Legal but uninteresting 13 | // We know that it returns at least Fruit: 14 | Fruit f = flist.get(0); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/generics/GenericsAndReturnTypes.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | interface GenericGetter> { 4 | T get(); 5 | } 6 | 7 | interface Getter extends GenericGetter {} 8 | 9 | public class GenericsAndReturnTypes { 10 | void test(Getter g) { 11 | Getter result = g.get(); 12 | GenericGetter gg = g.get(); // Also the base type 13 | } 14 | } ///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/generics/HasF.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class HasF { 4 | public void f() { System.out.println("HasF.f()"); } 5 | } ///:~ 6 | -------------------------------------------------------------------------------- /src/main/java/generics/HijackedInterface.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // {CompileTimeError} (Won't compile) 3 | 4 | class Cat extends ComparablePet implements Comparable{ 5 | // Error: Comparable cannot be inherited with 6 | // different arguments: and 7 | public int compareTo(Cat arg) { return 0; } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/generics/Holder1.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Automobile {} 4 | 5 | public class Holder1 { 6 | private Automobile a; 7 | public Holder1(Automobile a) { this.a = a; } 8 | Automobile get() { return a; } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/generics/Holder2.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class Holder2 { 4 | private Object a; 5 | public Holder2(Object a) { this.a = a; } 6 | public void set(Object a) { this.a = a; } 7 | public Object get() { return a; } 8 | public static void main(String[] args) { 9 | Holder2 h2 = new Holder2(new Automobile()); 10 | Automobile a = (Automobile)h2.get(); 11 | h2.set("Not an Automobile"); 12 | String s = (String)h2.get(); 13 | h2.set(1); // Autoboxes to Integer 14 | Integer x = (Integer)h2.get(); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/generics/Holder3.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class Holder3 { 4 | private T a; 5 | public Holder3(T a) { this.a = a; } 6 | public void set(T a) { this.a = a; } 7 | public T get() { return a; } 8 | public static void main(String[] args) { 9 | Holder3 h3 = 10 | new Holder3(new Automobile()); 11 | Automobile a = h3.get(); // No cast needed 12 | // h3.set("Not an Automobile"); // Error 13 | // h3.set(1); // Error 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/generics/InstantiateGenericType.cpp: -------------------------------------------------------------------------------- 1 | //: generics/InstantiateGenericType.cpp 2 | // C++, not Java! 3 | 4 | template class Foo { 5 | T x; // Create a field of type T 6 | T* y; // Pointer to T 7 | public: 8 | // Initialize the pointer: 9 | Foo() { y = new T(); } 10 | }; 11 | 12 | class Bar {}; 13 | 14 | int main() { 15 | Foo fb; 16 | Foo fi; // ... and it works with primitives 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/generics/LimitsOfInference.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import typeinfo.pets.*; 3 | import java.util.*; 4 | 5 | public class LimitsOfInference { 6 | static void 7 | f(Map> petPeople) {} 8 | public static void main(String[] args) { 9 | // f(New.map()); // Does not compile 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/generics/ListMaker.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class ListMaker { 5 | List create() { return new ArrayList(); } 6 | public static void main(String[] args) { 7 | ListMaker stringMaker= new ListMaker(); 8 | List stringList = stringMaker.create(); 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/generics/ListOfGenerics.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class ListOfGenerics { 5 | private List array = new ArrayList(); 6 | public void add(T item) { array.add(item); } 7 | public T get(int index) { return array.get(index); } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/generics/ListOfInt.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // Autoboxing compensates for the inability to use 3 | // primitives in generics. 4 | import java.util.*; 5 | 6 | public class ListOfInt { 7 | public static void main(String[] args) { 8 | List li = new ArrayList(); 9 | for(int i = 0; i < 5; i++) 10 | li.add(i); 11 | for(int i : li) 12 | System.out.print(i + " "); 13 | } 14 | } /* Output: 15 | 0 1 2 3 4 16 | *///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/generics/Manipulation.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // {CompileTimeError} (Won't compile) 3 | 4 | class Manipulator { 5 | private T obj; 6 | public Manipulator(T x) { obj = x; } 7 | // Error: cannot find symbol: method f(): 8 | public void manipulate() { obj.f(); } 9 | } 10 | 11 | public class Manipulation { 12 | public static void main(String[] args) { 13 | HasF hf = new HasF(); 14 | Manipulator manipulator = 15 | new Manipulator(hf); 16 | manipulator.manipulate(); 17 | } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/generics/Manipulator2.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Manipulator2 { 4 | private T obj; 5 | public Manipulator2(T x) { obj = x; } 6 | public void manipulate() { obj.f(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/generics/Manipulator3.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Manipulator3 { 4 | private HasF obj; 5 | public Manipulator3(HasF x) { obj = x; } 6 | public void manipulate() { obj.f(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/generics/MultipleInterfaceVariants.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // {CompileTimeError} (Won't compile) 3 | 4 | interface Payable {} 5 | 6 | class Employee implements Payable {} 7 | class Hourly extends Employee 8 | implements Payable {} ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/generics/NeedCasting.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | public class NeedCasting { 6 | @SuppressWarnings("unchecked") 7 | public void f(String[] args) throws Exception { 8 | ObjectInputStream in = new ObjectInputStream( 9 | new FileInputStream(args[0])); 10 | List shapes = (List)in.readObject(); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/NonCovariantGenerics.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // {CompileTimeError} (Won't compile) 3 | import java.util.*; 4 | 5 | public class NonCovariantGenerics { 6 | // Compile Error: incompatible types: 7 | List flist = new ArrayList(); 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/generics/NotSelfBounded.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class NotSelfBounded { 4 | T element; 5 | NotSelfBounded set(T arg) { 6 | element = arg; 7 | return this; 8 | } 9 | T get() { return element; } 10 | } 11 | 12 | class A2 extends NotSelfBounded {} 13 | class B2 extends NotSelfBounded {} 14 | 15 | class C2 extends NotSelfBounded { 16 | C2 setAndGet(C2 arg) { set(arg); return get(); } 17 | } 18 | 19 | class D2 {} 20 | // Now this is OK: 21 | class E2 extends NotSelfBounded {} ///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/generics/OrdinaryArguments.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class OrdinarySetter { 4 | void set(Base base) { 5 | System.out.println("OrdinarySetter.set(Base)"); 6 | } 7 | } 8 | 9 | class DerivedSetter extends OrdinarySetter { 10 | void set(Derived derived) { 11 | System.out.println("DerivedSetter.set(Derived)"); 12 | } 13 | } 14 | 15 | public class OrdinaryArguments { 16 | public static void main(String[] args) { 17 | Base base = new Base(); 18 | Derived derived = new Derived(); 19 | DerivedSetter ds = new DerivedSetter(); 20 | ds.set(derived); 21 | ds.set(base); // Compiles: overloaded, not overridden! 22 | } 23 | } /* Output: 24 | DerivedSetter.set(Derived) 25 | OrdinarySetter.set(Base) 26 | *///:~ 27 | -------------------------------------------------------------------------------- /src/main/java/generics/Performs.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public interface Performs { 4 | void speak(); 5 | void sit(); 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/generics/PlainGenericInheritance.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class GenericSetter { // Not self-bounded 4 | void set(T arg){ 5 | System.out.println("GenericSetter.set(Base)"); 6 | } 7 | } 8 | 9 | class DerivedGS extends GenericSetter { 10 | void set(Derived derived){ 11 | System.out.println("DerivedGS.set(Derived)"); 12 | } 13 | } 14 | 15 | public class PlainGenericInheritance { 16 | public static void main(String[] args) { 17 | Base base = new Base(); 18 | Derived derived = new Derived(); 19 | DerivedGS dgs = new DerivedGS(); 20 | dgs.set(derived); 21 | dgs.set(base); // Compiles: overloaded, not overridden! 22 | } 23 | } /* Output: 24 | DerivedGS.set(Derived) 25 | GenericSetter.set(Base) 26 | *///:~ 27 | -------------------------------------------------------------------------------- /src/main/java/generics/RestrictedComparablePets.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Hamster extends ComparablePet 4 | implements Comparable { 5 | public int compareTo(ComparablePet arg) { return 0; } 6 | } 7 | 8 | // Or just: 9 | 10 | class Gecko extends ComparablePet { 11 | public int compareTo(ComparablePet arg) { return 0; } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/ReturnGenericType.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class ReturnGenericType { 4 | private T obj; 5 | public ReturnGenericType(T x) { obj = x; } 6 | public T get() { return obj; } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/generics/SelfBoundingAndCovariantArguments.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | interface SelfBoundSetter> { 4 | void set(T arg); 5 | } 6 | 7 | interface Setter extends SelfBoundSetter {} 8 | 9 | public class SelfBoundingAndCovariantArguments { 10 | void testA(Setter s1, Setter s2, SelfBoundSetter sbs) { 11 | s1.set(s2); 12 | // s1.set(sbs); // Error: 13 | // set(Setter) in SelfBoundSetter 14 | // cannot be applied to (SelfBoundSetter) 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/generics/SelfBoundingMethods.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class SelfBoundingMethods { 4 | static > T f(T arg) { 5 | return arg.set(arg).get(); 6 | } 7 | public static void main(String[] args) { 8 | A a = f(new A()); 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/generics/SimpleDogsAndRobots.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // Removing the generic; code still works. 3 | 4 | class CommunicateSimply { 5 | static void perform(Performs performer) { 6 | performer.speak(); 7 | performer.sit(); 8 | } 9 | } 10 | 11 | public class SimpleDogsAndRobots { 12 | public static void main(String[] args) { 13 | CommunicateSimply.perform(new PerformingDog()); 14 | CommunicateSimply.perform(new Robot()); 15 | } 16 | } /* Output: 17 | Woof! 18 | Sitting 19 | Click! 20 | Clank! 21 | *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/generics/SimpleHolder.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | public class SimpleHolder { 4 | private Object obj; 5 | public void set(Object obj) { this.obj = obj; } 6 | public Object get() { return obj; } 7 | public static void main(String[] args) { 8 | SimpleHolder holder = new SimpleHolder(); 9 | holder.set("Item"); 10 | String s = (String)holder.get(); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/SimpleQueue.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // A different kind of container that is Iterable 3 | import java.util.*; 4 | 5 | public class SimpleQueue implements Iterable { 6 | private LinkedList storage = new LinkedList(); 7 | public void add(T t) { storage.offer(t); } 8 | public T get() { return storage.poll(); } 9 | public Iterator iterator() { 10 | return storage.iterator(); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/generics/SimplerPets.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import typeinfo.pets.*; 3 | import java.util.*; 4 | import net.mindview.util.*; 5 | 6 | public class SimplerPets { 7 | public static void main(String[] args) { 8 | Map> petPeople = New.map(); 9 | // Rest of the code is the same... 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/generics/SuperTypeWildcards.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class SuperTypeWildcards { 5 | static void writeTo(List apples) { 6 | apples.add(new Apple()); 7 | apples.add(new Jonathan()); 8 | // apples.add(new Fruit()); // Error 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/generics/Templates.cpp: -------------------------------------------------------------------------------- 1 | //: generics/Templates.cpp 2 | #include 3 | using namespace std; 4 | 5 | template class Manipulator { 6 | T obj; 7 | public: 8 | Manipulator(T x) { obj = x; } 9 | void manipulate() { obj.f(); } 10 | }; 11 | 12 | class HasF { 13 | public: 14 | void f() { cout << "HasF::f()" << endl; } 15 | }; 16 | 17 | int main() { 18 | HasF hf; 19 | Manipulator manipulator(hf); 20 | manipulator.manipulate(); 21 | } /* Output: 22 | HasF::f() 23 | ///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/generics/TupleList.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // Combining generic types to make complex generic types. 3 | import java.util.*; 4 | import net.mindview.util.*; 5 | 6 | public class TupleList 7 | extends ArrayList> { 8 | public static void main(String[] args) { 9 | TupleList tl = 10 | new TupleList(); 11 | tl.add(TupleTest.h()); 12 | tl.add(TupleTest.h()); 13 | for(FourTuple i: tl) 14 | System.out.println(i); 15 | } 16 | } /* Output: (75% match) 17 | (Vehicle@11b86e7, Amphibian@35ce36, hi, 47) 18 | (Vehicle@757aef, Amphibian@d9f9c3, hi, 47) 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/generics/Unconstrained.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | 3 | class Other {} 4 | class BasicOther extends BasicHolder {} 5 | 6 | public class Unconstrained { 7 | public static void main(String[] args) { 8 | BasicOther b = new BasicOther(), b2 = new BasicOther(); 9 | b.set(new Other()); 10 | Other other = b.get(); 11 | b.f(); 12 | } 13 | } /* Output: 14 | Other 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/generics/UseList.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | // {CompileTimeError} (Won't compile) 3 | import java.util.*; 4 | 5 | public class UseList { 6 | void f(List v) {} 7 | void f(List v) {} 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/generics/UseList2.java: -------------------------------------------------------------------------------- 1 | package generics; 2 | import java.util.*; 3 | 4 | public class UseList2 { 5 | void f1(List v) {} 6 | void f2(List v) {} 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/generics/coffee/Americano.java: -------------------------------------------------------------------------------- 1 | //: generics/coffee/Americano.java 2 | package generics.coffee; 3 | public class Americano extends Coffee {} ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/generics/coffee/Breve.java: -------------------------------------------------------------------------------- 1 | //: generics/coffee/Breve.java 2 | package generics.coffee; 3 | public class Breve extends Coffee {} ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/generics/coffee/Cappuccino.java: -------------------------------------------------------------------------------- 1 | //: generics/coffee/Cappuccino.java 2 | package generics.coffee; 3 | public class Cappuccino extends Coffee {} ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/generics/coffee/Coffee.java: -------------------------------------------------------------------------------- 1 | //: generics/coffee/Coffee.java 2 | package generics.coffee; 3 | 4 | public class Coffee { 5 | private static long counter = 0; 6 | private final long id = counter++; 7 | public String toString() { 8 | return getClass().getSimpleName() + " " + id; 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/generics/coffee/Latte.java: -------------------------------------------------------------------------------- 1 | //: generics/coffee/Latte.java 2 | package generics.coffee; 3 | public class Latte extends Coffee {} ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/generics/coffee/Mocha.java: -------------------------------------------------------------------------------- 1 | //: generics/coffee/Mocha.java 2 | package generics.coffee; 3 | public class Mocha extends Coffee {} ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/generics/watercolors/Watercolors.java: -------------------------------------------------------------------------------- 1 | //: generics/watercolors/Watercolors.java 2 | package generics.watercolors; 3 | 4 | public enum Watercolors { 5 | ZINC, LEMON_YELLOW, MEDIUM_YELLOW, DEEP_YELLOW, ORANGE, 6 | BRILLIANT_RED, CRIMSON, MAGENTA, ROSE_MADDER, VIOLET, 7 | CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, 8 | COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, 9 | SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, 10 | BURNT_UMBER, PAYNES_GRAY, IVORY_BLACK 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/gui/BorderLayout1.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | // Demonstrates BorderLayout. 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import static net.mindview.util.SwingConsole.*; 6 | 7 | public class BorderLayout1 extends JFrame { 8 | public BorderLayout1() { 9 | add(BorderLayout.NORTH, new JButton("North")); 10 | add(BorderLayout.SOUTH, new JButton("South")); 11 | add(BorderLayout.EAST, new JButton("East")); 12 | add(BorderLayout.WEST, new JButton("West")); 13 | add(BorderLayout.CENTER, new JButton("Center")); 14 | } 15 | public static void main(String[] args) { 16 | run(new BorderLayout1(), 300, 250); 17 | } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/gui/Button1.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | // Putting buttons on a Swing application. 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import static net.mindview.util.SwingConsole.*; 6 | 7 | public class Button1 extends JFrame { 8 | private JButton 9 | b1 = new JButton("Button 1"), 10 | b2 = new JButton("Button 2"); 11 | public Button1() { 12 | setLayout(new FlowLayout()); 13 | add(b1); 14 | add(b2); 15 | } 16 | public static void main(String[] args) { 17 | run(new Button1(), 200, 100); 18 | } 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/gui/Face0.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/src/main/java/gui/Face0.gif -------------------------------------------------------------------------------- /src/main/java/gui/Face1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/src/main/java/gui/Face1.gif -------------------------------------------------------------------------------- /src/main/java/gui/Face2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/src/main/java/gui/Face2.gif -------------------------------------------------------------------------------- /src/main/java/gui/Face3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/src/main/java/gui/Face3.gif -------------------------------------------------------------------------------- /src/main/java/gui/Face4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/src/main/java/gui/Face4.gif -------------------------------------------------------------------------------- /src/main/java/gui/FlowLayout1.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | // Demonstrates FlowLayout. 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import static net.mindview.util.SwingConsole.*; 6 | 7 | public class FlowLayout1 extends JFrame { 8 | public FlowLayout1() { 9 | setLayout(new FlowLayout()); 10 | for(int i = 0; i < 20; i++) 11 | add(new JButton("Button " + i)); 12 | } 13 | public static void main(String[] args) { 14 | run(new FlowLayout1(), 300, 300); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/gui/GridLayout1.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | // Demonstrates GridLayout. 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import static net.mindview.util.SwingConsole.*; 6 | 7 | public class GridLayout1 extends JFrame { 8 | public GridLayout1() { 9 | setLayout(new GridLayout(7,3)); 10 | for(int i = 0; i < 20; i++) 11 | add(new JButton("Button " + i)); 12 | } 13 | public static void main(String[] args) { 14 | run(new GridLayout1(), 300, 300); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/gui/HelloLabel.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | import javax.swing.*; 3 | import java.util.concurrent.*; 4 | 5 | public class HelloLabel { 6 | public static void main(String[] args) throws Exception { 7 | JFrame frame = new JFrame("Hello Swing"); 8 | JLabel label = new JLabel("A Label"); 9 | frame.add(label); 10 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11 | frame.setSize(300, 100); 12 | frame.setVisible(true); 13 | TimeUnit.SECONDS.sleep(1); 14 | label.setText("Hey! This is Different!"); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/gui/HelloSwing.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | import javax.swing.*; 3 | 4 | public class HelloSwing { 5 | public static void main(String[] args) { 6 | JFrame frame = new JFrame("Hello Swing"); 7 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 8 | frame.setSize(300, 100); 9 | frame.setVisible(true); 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/gui/SubmitLabelManipulationTask.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | import javax.swing.*; 3 | import java.util.concurrent.*; 4 | 5 | public class SubmitLabelManipulationTask { 6 | public static void main(String[] args) throws Exception { 7 | JFrame frame = new JFrame("Hello Swing"); 8 | final JLabel label = new JLabel("A Label"); 9 | frame.add(label); 10 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11 | frame.setSize(300, 100); 12 | frame.setVisible(true); 13 | TimeUnit.SECONDS.sleep(1); 14 | SwingUtilities.invokeLater(new Runnable() { 15 | public void run() { 16 | label.setText("Hey! This is Different!"); 17 | } 18 | }); 19 | } 20 | } ///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/gui/flex/build-command.txt: -------------------------------------------------------------------------------- 1 | mxmlc -flexlib C:/"Program Files"/Macromedia/Flex/jrun4/servers/default/flex/WEB-INF/flex songs.mxml 2 | -------------------------------------------------------------------------------- /src/main/java/gui/flex/helloflex1.mxml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/main/java/gui/flex/helloflex2.mxml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/main/java/gui/flex/songScript.as: -------------------------------------------------------------------------------- 1 | //: gui/flex/songScript.as 2 | function getSongs() { 3 | songService.getSongs(); 4 | } 5 | 6 | function selectSong(event) { 7 | var song = songGrid.getItemAt(event.itemIndex); 8 | showSongInfo(song); 9 | } 10 | 11 | function showSongInfo(song) { 12 | songInfo.text = song.name + newline; 13 | songInfo.text += song.artist + newline; 14 | songInfo.text += song.album + newline; 15 | albumImage.source = song.albumImageUrl; 16 | songPlayer.contentPath = song.songMediaUrl; 17 | songPlayer.visible = true; 18 | } 19 | 20 | function onSongs(songs) { 21 | songGrid.dataProvider = songs; 22 | } ///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/gui/flex/songStyles.css: -------------------------------------------------------------------------------- 1 | .headerText { 2 | font-family: Arial, "_sans"; 3 | font-size: 16; 4 | font-weight: bold; 5 | } 6 | 7 | .boldText { 8 | font-family: Arial, "_sans"; 9 | font-size: 11; 10 | font-weight: bold; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/gui/jnlp/filechooser.html: -------------------------------------------------------------------------------- 1 | 2 | Follow the instructions in JnlpFileChooser.java to 3 | build jnlpfilechooser.jar, then: 4 | click here 5 | 6 | -------------------------------------------------------------------------------- /src/main/java/gui/jnlp/mindview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gauravojha/tij4-maven/de72e0e12263facb1e226ebdbec5b489785106bc/src/main/java/gui/jnlp/mindview.gif -------------------------------------------------------------------------------- /src/main/java/holding/ApplesAndOrangesWithGenerics.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | public class ApplesAndOrangesWithGenerics { 5 | public static void main(String[] args) { 6 | ArrayList apples = new ArrayList(); 7 | for(int i = 0; i < 3; i++) 8 | apples.add(new Apple()); 9 | // Compile-time error: 10 | // apples.add(new Orange()); 11 | for(int i = 0; i < apples.size(); i++) 12 | System.out.println(apples.get(i).id()); 13 | // Using foreach: 14 | for(Apple c : apples) 15 | System.out.println(c.id()); 16 | } 17 | } /* Output: 18 | 0 19 | 1 20 | 2 21 | 0 22 | 1 23 | 2 24 | *///:~ 25 | -------------------------------------------------------------------------------- /src/main/java/holding/ArrayIsNotIterable.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | public class ArrayIsNotIterable { 5 | static void test(Iterable ib) { 6 | for(T t : ib) 7 | System.out.print(t + " "); 8 | } 9 | public static void main(String[] args) { 10 | test(Arrays.asList(1, 2, 3)); 11 | String[] strings = { "A", "B", "C" }; 12 | // An array works in foreach, but it's not Iterable: 13 | //! test(strings); 14 | // You must explicitly convert it to an Iterable: 15 | test(Arrays.asList(strings)); 16 | } 17 | } /* Output: 18 | 1 2 3 A B C 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/holding/EnvironmentVariables.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | public class EnvironmentVariables { 5 | public static void main(String[] args) { 6 | for(Map.Entry entry: System.getenv().entrySet()) { 7 | System.out.println(entry.getKey() + ": " + 8 | entry.getValue()); 9 | } 10 | } 11 | } /* (Execute to see output) *///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/holding/ForEachCollections.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | // All collections work with foreach. 3 | import java.util.*; 4 | 5 | public class ForEachCollections { 6 | public static void main(String[] args) { 7 | Collection cs = new LinkedList(); 8 | Collections.addAll(cs, 9 | "Take the long way home".split(" ")); 10 | for(String s : cs) 11 | System.out.print("'" + s + "' "); 12 | } 13 | } /* Output: 14 | 'Take' 'the' 'long' 'way' 'home' 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/holding/GenericsAndUpcasting.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | class GrannySmith extends Apple {} 5 | class Gala extends Apple {} 6 | class Fuji extends Apple {} 7 | class Braeburn extends Apple {} 8 | 9 | public class GenericsAndUpcasting { 10 | public static void main(String[] args) { 11 | ArrayList apples = new ArrayList(); 12 | apples.add(new GrannySmith()); 13 | apples.add(new Gala()); 14 | apples.add(new Fuji()); 15 | apples.add(new Braeburn()); 16 | for(Apple c : apples) 17 | System.out.println(c); 18 | } 19 | } /* Output: (Sample) 20 | GrannySmith@7d772e 21 | Gala@11b86e7 22 | Fuji@35ce36 23 | Braeburn@757aef 24 | *///:~ 25 | -------------------------------------------------------------------------------- /src/main/java/holding/PetMap.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import typeinfo.pets.*; 3 | import java.util.*; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class PetMap { 7 | public static void main(String[] args) { 8 | Map petMap = new HashMap(); 9 | petMap.put("My Cat", new Cat("Molly")); 10 | petMap.put("My Dog", new Dog("Ginger")); 11 | petMap.put("My Hamster", new Hamster("Bosco")); 12 | print(petMap); 13 | Pet dog = petMap.get("My Dog"); 14 | print(dog); 15 | print(petMap.containsKey("My Dog")); 16 | print(petMap.containsValue(dog)); 17 | } 18 | } /* Output: 19 | {My Cat=Cat Molly, My Hamster=Hamster Bosco, My Dog=Dog Ginger} 20 | Dog Ginger 21 | true 22 | true 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/holding/SetOfInteger.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | public class SetOfInteger { 5 | public static void main(String[] args) { 6 | Random rand = new Random(47); 7 | Set intset = new HashSet(); 8 | for(int i = 0; i < 10000; i++) 9 | intset.add(rand.nextInt(30)); 10 | System.out.println(intset); 11 | } 12 | } /* Output: 13 | [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] 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/holding/SimpleCollection.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | public class SimpleCollection { 5 | public static void main(String[] args) { 6 | Collection c = new ArrayList(); 7 | for(int i = 0; i < 10; i++) 8 | c.add(i); // Autoboxing 9 | for(Integer i : c) 10 | System.out.print(i + ", "); 11 | } 12 | } /* Output: 13 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/holding/SortedSetOfInteger.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | 4 | public class SortedSetOfInteger { 5 | public static void main(String[] args) { 6 | Random rand = new Random(47); 7 | SortedSet intset = new TreeSet(); 8 | for(int i = 0; i < 10000; i++) 9 | intset.add(rand.nextInt(30)); 10 | System.out.println(intset); 11 | } 12 | } /* Output: 13 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/holding/StackTest.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import net.mindview.util.*; 3 | 4 | public class StackTest { 5 | public static void main(String[] args) { 6 | Stack stack = new Stack(); 7 | for(String s : "My dog has fleas".split(" ")) 8 | stack.push(s); 9 | while(!stack.empty()) 10 | System.out.print(stack.pop() + " "); 11 | } 12 | } /* Output: 13 | fleas has dog My 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/holding/Statistics.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | // Simple demonstration of HashMap. 3 | import java.util.*; 4 | 5 | public class Statistics { 6 | public static void main(String[] args) { 7 | Random rand = new Random(47); 8 | Map m = 9 | new HashMap(); 10 | for(int i = 0; i < 10000; i++) { 11 | // Produce a number between 0 and 20: 12 | int r = rand.nextInt(20); 13 | Integer freq = m.get(r); 14 | m.put(r, freq == null ? 1 : freq + 1); 15 | } 16 | System.out.println(m); 17 | } 18 | } /* Output: 19 | {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} 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/holding/UniqueWords.java: -------------------------------------------------------------------------------- 1 | package holding; 2 | import java.util.*; 3 | import net.mindview.util.*; 4 | 5 | public class UniqueWords { 6 | public static void main(String[] args) { 7 | Set words = new TreeSet( 8 | new TextFile("SetOperations.java", "\\W+")); 9 | System.out.println(words); 10 | } 11 | } /* Output: 12 | [A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K, L, M, N, Output, Print, Set, SetOperations, String, X, Y, Z, add, addAll, added, args, class, contains, containsAll, false, from, holding, import, in, java, main, mindview, net, new, print, public, remove, removeAll, removed, set1, set2, split, static, to, true, util, void] 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/initialization/Apricot.java: -------------------------------------------------------------------------------- 1 | //: initialization/Apricot.java 2 | package initialization; 3 | public class Apricot { 4 | void pick() { /* ... */ } 5 | void pit() { pick(); /* ... */ } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/initialization/ArrayClassObj.java: -------------------------------------------------------------------------------- 1 | //: initialization/ArrayClassObj.java 2 | // Creating an array of nonprimitive objects. 3 | package initialization; 4 | import java.util.*; 5 | import static net.mindview.util.Print.*; 6 | 7 | public class ArrayClassObj { 8 | public static void main(String[] args) { 9 | Random rand = new Random(47); 10 | Integer[] a = new Integer[rand.nextInt(20)]; 11 | print("length of a = " + a.length); 12 | for(int i = 0; i < a.length; i++) 13 | a[i] = rand.nextInt(500); // Autoboxing 14 | print(Arrays.toString(a)); 15 | } 16 | } /* Output: (Sample) 17 | length of a = 18 18 | [55, 193, 361, 461, 429, 368, 200, 22, 207, 288, 128, 51, 89, 309, 278, 498, 361, 20] 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/initialization/ArrayInit.java: -------------------------------------------------------------------------------- 1 | //: initialization/ArrayInit.java 2 | // Array initialization. 3 | package initialization; 4 | import java.util.*; 5 | 6 | public class ArrayInit { 7 | public static void main(String[] args) { 8 | Integer[] a = { 9 | new Integer(1), 10 | new Integer(2), 11 | 3, // Autoboxing 12 | }; 13 | Integer[] b = new Integer[]{ 14 | new Integer(1), 15 | new Integer(2), 16 | 3, // Autoboxing 17 | }; 18 | System.out.println(Arrays.toString(a)); 19 | System.out.println(Arrays.toString(b)); 20 | } 21 | } /* Output: 22 | [1, 2, 3] 23 | [1, 2, 3] 24 | *///:~ 25 | -------------------------------------------------------------------------------- /src/main/java/initialization/ArrayNew.java: -------------------------------------------------------------------------------- 1 | //: initialization/ArrayNew.java 2 | // Creating arrays with new. 3 | package initialization; 4 | import java.util.*; 5 | import static net.mindview.util.Print.*; 6 | 7 | public class ArrayNew { 8 | public static void main(String[] args) { 9 | int[] a; 10 | Random rand = new Random(47); 11 | a = new int[rand.nextInt(20)]; 12 | print("length of a = " + a.length); 13 | print(Arrays.toString(a)); 14 | } 15 | } /* Output: 16 | length of a = 18 17 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/initialization/ArraysOfPrimitives.java: -------------------------------------------------------------------------------- 1 | //: initialization/ArraysOfPrimitives.java 2 | package initialization; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class ArraysOfPrimitives { 6 | public static void main(String[] args) { 7 | int[] a1 = { 1, 2, 3, 4, 5 }; 8 | int[] a2; 9 | a2 = a1; 10 | for(int i = 0; i < a2.length; i++) 11 | a2[i] = a2[i] + 1; 12 | for(int i = 0; i < a1.length; i++) 13 | print("a1[" + i + "] = " + a1[i]); 14 | } 15 | } /* Output: 16 | a1[0] = 2 17 | a1[1] = 3 18 | a1[2] = 4 19 | a1[3] = 5 20 | a1[4] = 6 21 | *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/initialization/AutoboxingVarargs.java: -------------------------------------------------------------------------------- 1 | //: initialization/AutoboxingVarargs.java 2 | package initialization; 3 | public class AutoboxingVarargs { 4 | public static void f(Integer... args) { 5 | for(Integer i : args) 6 | System.out.print(i + " "); 7 | System.out.println(); 8 | } 9 | public static void main(String[] args) { 10 | f(new Integer(1), new Integer(2)); 11 | f(4, 5, 6, 7, 8, 9); 12 | f(10, new Integer(11), 12); 13 | } 14 | } /* Output: 15 | 1 2 16 | 4 5 6 7 8 9 17 | 10 11 12 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/initialization/BananaPeel.java: -------------------------------------------------------------------------------- 1 | //: initialization/BananaPeel.java 2 | package initialization; 3 | class Banana { void peel(int i) { /* ... */ } } 4 | 5 | public class BananaPeel { 6 | public static void main(String[] args) { 7 | Banana a = new Banana(), 8 | b = new Banana(); 9 | a.peel(1); 10 | b.peel(2); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/initialization/Counter.java: -------------------------------------------------------------------------------- 1 | //: initialization/Counter.java 2 | package initialization; 3 | public class Counter { 4 | int i; 5 | Counter() { i = 7; } 6 | // ... 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/initialization/DefaultConstructor.java: -------------------------------------------------------------------------------- 1 | //: initialization/DefaultConstructor.java 2 | package initialization; 3 | class Bird {} 4 | 5 | public class DefaultConstructor { 6 | public static void main(String[] args) { 7 | Bird b = new Bird(); // Default! 8 | } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/initialization/DynamicArray.java: -------------------------------------------------------------------------------- 1 | //: initialization/DynamicArray.java 2 | // Array initialization. 3 | package initialization; 4 | public class DynamicArray { 5 | public static void main(String[] args) { 6 | Other.main(new String[]{ "fiddle", "de", "dum" }); 7 | } 8 | } 9 | 10 | class Other { 11 | public static void main(String[] args) { 12 | for(String s : args) 13 | System.out.print(s + " "); 14 | } 15 | } /* Output: 16 | fiddle de dum 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/initialization/EnumOrder.java: -------------------------------------------------------------------------------- 1 | //: initialization/EnumOrder.java 2 | package initialization; 3 | public class EnumOrder { 4 | public static void main(String[] args) { 5 | for(Spiciness s : Spiciness.values()) 6 | System.out.println(s + ", ordinal " + s.ordinal()); 7 | } 8 | } /* Output: 9 | NOT, ordinal 0 10 | MILD, ordinal 1 11 | MEDIUM, ordinal 2 12 | HOT, ordinal 3 13 | FLAMING, ordinal 4 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/initialization/InitialValues2.java: -------------------------------------------------------------------------------- 1 | //: initialization/InitialValues2.java 2 | // Providing explicit initial values. 3 | package initialization; 4 | public class InitialValues2 { 5 | boolean bool = true; 6 | char ch = 'x'; 7 | byte b = 47; 8 | short s = 0xff; 9 | int i = 999; 10 | long lng = 1; 11 | float f = 3.14f; 12 | double d = 3.14159; 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/initialization/Leaf.java: -------------------------------------------------------------------------------- 1 | //: initialization/Leaf.java 2 | // Simple use of the "this" keyword. 3 | package initialization; 4 | public class Leaf { 5 | int i = 0; 6 | Leaf increment() { 7 | i++; 8 | return this; 9 | } 10 | void print() { 11 | System.out.println("i = " + i); 12 | } 13 | public static void main(String[] args) { 14 | Leaf x = new Leaf(); 15 | x.increment().increment().increment().print(); 16 | } 17 | } /* Output: 18 | i = 3 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/initialization/Measurement.java: -------------------------------------------------------------------------------- 1 | //: initialization/Measurement.java 2 | package initialization; 3 | class Depth {} 4 | 5 | public class Measurement { 6 | Depth d = new Depth(); 7 | // ... 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/initialization/MethodInit.java: -------------------------------------------------------------------------------- 1 | //: initialization/MethodInit.java 2 | package initialization; 3 | public class MethodInit { 4 | int i = f(); 5 | int f() { return 11; } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/initialization/MethodInit2.java: -------------------------------------------------------------------------------- 1 | //: initialization/MethodInit2.java 2 | package initialization; 3 | public class MethodInit2 { 4 | int i = f(); 5 | int j = g(i); 6 | int f() { return 11; } 7 | int g(int n) { return n * 10; } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/initialization/MethodInit3.java: -------------------------------------------------------------------------------- 1 | //: initialization/MethodInit3.java 2 | package initialization; 3 | public class MethodInit3 { 4 | //! int j = g(i); // Illegal forward reference 5 | int i = f(); 6 | int f() { return 11; } 7 | int g(int n) { return n * 10; } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/initialization/NoSynthesis.java: -------------------------------------------------------------------------------- 1 | //: initialization/NoSynthesis.java 2 | package initialization; 3 | class Bird2 { 4 | Bird2(int i) {} 5 | Bird2(double d) {} 6 | } 7 | 8 | public class NoSynthesis { 9 | public static void main(String[] args) { 10 | //! Bird2 b = new Bird2(); // No default 11 | Bird2 b2 = new Bird2(1); 12 | Bird2 b3 = new Bird2(1.0); 13 | } 14 | } ///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/initialization/OptionalTrailingArguments.java: -------------------------------------------------------------------------------- 1 | //: initialization/OptionalTrailingArguments.java 2 | package initialization; 3 | public class OptionalTrailingArguments { 4 | static void f(int required, String... trailing) { 5 | System.out.print("required: " + required + " "); 6 | for(String s : trailing) 7 | System.out.print(s + " "); 8 | System.out.println(); 9 | } 10 | public static void main(String[] args) { 11 | f(1, "one"); 12 | f(2, "two", "three"); 13 | f(0); 14 | } 15 | } /* Output: 16 | required: 1 one 17 | required: 2 two three 18 | required: 0 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/initialization/OverloadingOrder.java: -------------------------------------------------------------------------------- 1 | //: initialization/OverloadingOrder.java 2 | // Overloading based on the order of the arguments. 3 | package initialization; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class OverloadingOrder { 7 | static void f(String s, int i) { 8 | print("String: " + s + ", int: " + i); 9 | } 10 | static void f(int i, String s) { 11 | print("int: " + i + ", String: " + s); 12 | } 13 | public static void main(String[] args) { 14 | f("String first", 11); 15 | f(99, "Int first"); 16 | } 17 | } /* Output: 18 | String: String first, int: 11 19 | int: 99, String: Int first 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/initialization/OverloadingVarargs2.java: -------------------------------------------------------------------------------- 1 | //: initialization/OverloadingVarargs2.java 2 | // {CompileTimeError} (Won't compile) 3 | package initialization; 4 | public class OverloadingVarargs2 { 5 | static void f(float i, Character... args) { 6 | System.out.println("first"); 7 | } 8 | static void f(Character... args) { 9 | System.out.print("second"); 10 | } 11 | public static void main(String[] args) { 12 | f(1, 'a'); 13 | //f('a', 'b'); 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/initialization/OverloadingVarargs3.java: -------------------------------------------------------------------------------- 1 | //: initialization/OverloadingVarargs3.java 2 | package initialization; 3 | public class OverloadingVarargs3 { 4 | static void f(float i, Character... args) { 5 | System.out.println("first"); 6 | } 7 | static void f(char c, Character... args) { 8 | System.out.println("second"); 9 | } 10 | public static void main(String[] args) { 11 | f(1, 'a'); 12 | f('a', 'b'); 13 | } 14 | } /* Output: 15 | first 16 | second 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/initialization/PassingThis.java: -------------------------------------------------------------------------------- 1 | //: initialization/PassingThis.java 2 | package initialization; 3 | class Person { 4 | public void eat(Apple apple) { 5 | Apple peeled = apple.getPeeled(); 6 | System.out.println("Yummy"); 7 | } 8 | } 9 | 10 | class Peeler { 11 | static Apple peel(Apple apple) { 12 | // ... remove peel 13 | return apple; // Peeled 14 | } 15 | } 16 | 17 | class Apple { 18 | Apple getPeeled() { return Peeler.peel(this); } 19 | } 20 | 21 | public class PassingThis { 22 | public static void main(String[] args) { 23 | new Person().eat(new Apple()); 24 | } 25 | } /* Output: 26 | Yummy 27 | *///:~ 28 | -------------------------------------------------------------------------------- /src/main/java/initialization/SimpleConstructor.java: -------------------------------------------------------------------------------- 1 | //: initialization/SimpleConstructor.java 2 | // Demonstration of a simple constructor. 3 | package initialization; 4 | class Rock { 5 | Rock() { // This is the constructor 6 | System.out.print("Rock "); 7 | } 8 | } 9 | 10 | public class SimpleConstructor { 11 | public static void main(String[] args) { 12 | for(int i = 0; i < 10; i++) 13 | new Rock(); 14 | } 15 | } /* Output: 16 | Rock Rock Rock Rock Rock Rock Rock Rock Rock Rock 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/initialization/SimpleConstructor2.java: -------------------------------------------------------------------------------- 1 | //: initialization/SimpleConstructor2.java 2 | // Constructors can have arguments. 3 | package initialization; 4 | class Rock2 { 5 | Rock2(int i) { 6 | System.out.print("Rock " + i + " "); 7 | } 8 | } 9 | 10 | public class SimpleConstructor2 { 11 | public static void main(String[] args) { 12 | for(int i = 0; i < 8; i++) 13 | new Rock2(i); 14 | } 15 | } /* Output: 16 | Rock 0 Rock 1 Rock 2 Rock 3 Rock 4 Rock 5 Rock 6 Rock 7 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/initialization/SimpleEnumUse.java: -------------------------------------------------------------------------------- 1 | //: initialization/SimpleEnumUse.java 2 | package initialization; 3 | public class SimpleEnumUse { 4 | public static void main(String[] args) { 5 | Spiciness howHot = Spiciness.MEDIUM; 6 | System.out.println(howHot); 7 | } 8 | } /* Output: 9 | MEDIUM 10 | *///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/initialization/Spiciness.java: -------------------------------------------------------------------------------- 1 | //: initialization/Spiciness.java 2 | package initialization; 3 | public enum Spiciness { 4 | NOT, MILD, MEDIUM, HOT, FLAMING 5 | } ///:~ 6 | -------------------------------------------------------------------------------- /src/main/java/initialization/Spoon.java: -------------------------------------------------------------------------------- 1 | //: initialization/Spoon.java 2 | package initialization; 3 | public class Spoon { 4 | static int i; 5 | static { 6 | i = 47; 7 | } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/initialization/VarArgs.java: -------------------------------------------------------------------------------- 1 | //: initialization/VarArgs.java 2 | // Using array syntax to create variable argument lists. 3 | package initialization; 4 | class A {} 5 | 6 | public class VarArgs { 7 | static void printArray(Object[] args) { 8 | for(Object obj : args) 9 | System.out.print(obj + " "); 10 | System.out.println(); 11 | } 12 | public static void main(String[] args) { 13 | printArray(new Object[]{ 14 | new Integer(47), new Float(3.14), new Double(11.11) 15 | }); 16 | printArray(new Object[]{"one", "two", "three" }); 17 | printArray(new Object[]{new A(), new A(), new A()}); 18 | } 19 | } /* Output: (Sample) 20 | 47 3.14 11.11 21 | one two three 22 | A@1a46e30 A@3e25a5 A@19821f 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/BigEgg.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // An inner class cannot be overriden like a method. 3 | import static net.mindview.util.Print.*; 4 | 5 | class Egg { 6 | private Yolk y; 7 | protected class Yolk { 8 | public Yolk() { print("Egg.Yolk()"); } 9 | } 10 | public Egg() { 11 | print("New Egg()"); 12 | y = new Yolk(); 13 | } 14 | } 15 | 16 | public class BigEgg extends Egg { 17 | public class Yolk { 18 | public Yolk() { print("BigEgg.Yolk()"); } 19 | } 20 | public static void main(String[] args) { 21 | new BigEgg(); 22 | } 23 | } /* Output: 24 | New Egg() 25 | Egg.Yolk() 26 | *///:~ 27 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/ClassInInterface.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // {main: ClassInInterface$Test} 3 | 4 | public interface ClassInInterface { 5 | void howdy(); 6 | class Test implements ClassInInterface { 7 | public void howdy() { 8 | System.out.println("Howdy!"); 9 | } 10 | public static void main(String[] args) { 11 | new Test().howdy(); 12 | } 13 | } 14 | } /* Output: 15 | Howdy! 16 | *///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Contents.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | public interface Contents { 3 | int value(); 4 | } ///:~ 5 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Destination.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | public interface Destination { 3 | String readLabel(); 4 | } ///:~ 5 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/DotNew.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Creating an inner class directly using the .new syntax. 3 | 4 | public class DotNew { 5 | public class Inner {} 6 | public static void main(String[] args) { 7 | DotNew dn = new DotNew(); 8 | DotNew.Inner dni = dn.new Inner(); 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/DotThis.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Qualifying access to the outer-class object. 3 | 4 | public class DotThis { 5 | void f() { System.out.println("DotThis.f()"); } 6 | public class Inner { 7 | public DotThis outer() { 8 | return DotThis.this; 9 | // A plain "this" would be Inner's "this" 10 | } 11 | } 12 | public Inner inner() { return new Inner(); } 13 | public static void main(String[] args) { 14 | DotThis dt = new DotThis(); 15 | DotThis.Inner dti = dt.inner(); 16 | dti.outer().f(); 17 | } 18 | } /* Output: 19 | DotThis.f() 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/InheritInner.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Inheriting an inner class. 3 | 4 | class WithInner { 5 | class Inner {} 6 | } 7 | 8 | public class InheritInner extends WithInner.Inner { 9 | //! InheritInner() {} // Won't compile 10 | InheritInner(WithInner wi) { 11 | wi.super(); 12 | } 13 | public static void main(String[] args) { 14 | WithInner wi = new WithInner(); 15 | InheritInner ii = new InheritInner(wi); 16 | } 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/MultiImplementation.java: -------------------------------------------------------------------------------- 1 | //: innerclasses/MultiImplementation.java 2 | // With concrete or abstract classes, inner 3 | // classes are the only way to produce the effect 4 | // of "multiple implementation inheritance." 5 | package innerclasses; 6 | 7 | class D {} 8 | abstract class E {} 9 | 10 | class Z extends D { 11 | E makeE() { return new E() {}; } 12 | } 13 | 14 | public class MultiImplementation { 15 | static void takesD(D d) {} 16 | static void takesE(E e) {} 17 | public static void main(String[] args) { 18 | Z z = new Z(); 19 | takesD(z); 20 | takesE(z.makeE()); 21 | } 22 | } ///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/MultiInterfaces.java: -------------------------------------------------------------------------------- 1 | //: innerclasses/MultiInterfaces.java 2 | // Two ways that a class can implement multiple interfaces. 3 | package innerclasses; 4 | 5 | interface A {} 6 | interface B {} 7 | 8 | class X implements A, B {} 9 | 10 | class Y implements A { 11 | B makeB() { 12 | // Anonymous inner class: 13 | return new B() {}; 14 | } 15 | } 16 | 17 | public class MultiInterfaces { 18 | static void takesA(A a) {} 19 | static void takesB(B b) {} 20 | public static void main(String[] args) { 21 | X x = new X(); 22 | Y y = new Y(); 23 | takesA(x); 24 | takesA(y); 25 | takesB(x); 26 | takesB(y.makeB()); 27 | } 28 | } ///:~ 29 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/MultiNestingAccess.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Nested classes can access all members of all 3 | // levels of the classes they are nested within. 4 | 5 | class MNA { 6 | private void f() {} 7 | class A { 8 | private void g() {} 9 | public class B { 10 | void h() { 11 | g(); 12 | f(); 13 | } 14 | } 15 | } 16 | } 17 | 18 | public class MultiNestingAccess { 19 | public static void main(String[] args) { 20 | MNA mna = new MNA(); 21 | MNA.A mnaa = mna.new A(); 22 | MNA.A.B mnaab = mnaa.new B(); 23 | mnaab.h(); 24 | } 25 | } ///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Parcel3.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Using .new to create instances of inner classes. 3 | 4 | public class Parcel3 { 5 | class Contents { 6 | private int i = 11; 7 | public int value() { return i; } 8 | } 9 | class Destination { 10 | private String label; 11 | Destination(String whereTo) { label = whereTo; } 12 | String readLabel() { return label; } 13 | } 14 | public static void main(String[] args) { 15 | Parcel3 p = new Parcel3(); 16 | // Must use instance of outer class 17 | // to create an instance of the inner class: 18 | Parcel3.Contents c = p.new Contents(); 19 | Parcel3.Destination d = p.new Destination("Tasmania"); 20 | } 21 | } ///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Parcel5.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Nesting a class within a method. 3 | 4 | public class Parcel5 { 5 | public Destination destination(String s) { 6 | class PDestination implements Destination { 7 | private String label; 8 | private PDestination(String whereTo) { 9 | label = whereTo; 10 | } 11 | public String readLabel() { return label; } 12 | } 13 | return new PDestination(s); 14 | } 15 | public static void main(String[] args) { 16 | Parcel5 p = new Parcel5(); 17 | Destination d = p.destination("Tasmania"); 18 | } 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Parcel7.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Returning an instance of an anonymous inner class. 3 | 4 | public class Parcel7 { 5 | public Contents contents() { 6 | return new Contents() { // Insert a class definition 7 | private int i = 11; 8 | public int value() { return i; } 9 | }; // Semicolon required in this case 10 | } 11 | public static void main(String[] args) { 12 | Parcel7 p = new Parcel7(); 13 | Contents c = p.contents(); 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Parcel7b.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Expanded version of Parcel7.java 3 | 4 | public class Parcel7b { 5 | class MyContents implements Contents { 6 | private int i = 11; 7 | public int value() { return i; } 8 | } 9 | public Contents contents() { return new MyContents(); } 10 | public static void main(String[] args) { 11 | Parcel7b p = new Parcel7b(); 12 | Contents c = p.contents(); 13 | } 14 | } ///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Parcel8.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Calling the base-class constructor. 3 | 4 | public class Parcel8 { 5 | public Wrapping wrapping(int x) { 6 | // Base constructor call: 7 | return new Wrapping(x) { // Pass constructor argument. 8 | public int value() { 9 | return super.value() * 47; 10 | } 11 | }; // Semicolon required 12 | } 13 | public static void main(String[] args) { 14 | Parcel8 p = new Parcel8(); 15 | Wrapping w = p.wrapping(10); 16 | } 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Parcel9.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // An anonymous inner class that performs 3 | // initialization. A briefer version of Parcel5.java. 4 | 5 | public class Parcel9 { 6 | // Argument must be final to use inside 7 | // anonymous inner class: 8 | public Destination destination(final String dest) { 9 | return new Destination() { 10 | private String label = dest; 11 | public String readLabel() { return label; } 12 | }; 13 | } 14 | public static void main(String[] args) { 15 | Parcel9 p = new Parcel9(); 16 | Destination d = p.destination("Tasmania"); 17 | } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/TestBed.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | // Putting test code in a nested class. 3 | // {main: TestBed$Tester} 4 | 5 | public class TestBed { 6 | public void f() { System.out.println("f()"); } 7 | public static class Tester { 8 | public static void main(String[] args) { 9 | TestBed t = new TestBed(); 10 | t.f(); 11 | } 12 | } 13 | } /* Output: 14 | f() 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/Wrapping.java: -------------------------------------------------------------------------------- 1 | package innerclasses; 2 | public class Wrapping { 3 | private int i; 4 | public Wrapping(int x) { i = x; } 5 | public int value() { return i; } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/innerclasses/controller/Event.java: -------------------------------------------------------------------------------- 1 | //: innerclasses/controller/Event.java 2 | // The common methods for any control event. 3 | package innerclasses.controller; 4 | 5 | public abstract class Event { 6 | private long eventTime; 7 | protected final long delayTime; 8 | public Event(long delayTime) { 9 | this.delayTime = delayTime; 10 | start(); 11 | } 12 | public void start() { // Allows restarting 13 | eventTime = System.nanoTime() + delayTime; 14 | } 15 | public boolean ready() { 16 | return System.nanoTime() >= eventTime; 17 | } 18 | public abstract void action(); 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/interfaces/InterfaceCollision.java: -------------------------------------------------------------------------------- 1 | //: interfaces/InterfaceCollision.java 2 | package interfaces; 3 | 4 | interface I1 { void f(); } 5 | interface I2 { int f(int i); } 6 | interface I3 { int f(); } 7 | class C { public int f() { return 1; } } 8 | 9 | class C2 implements I1, I2 { 10 | public void f() {} 11 | public int f(int i) { return 1; } // overloaded 12 | } 13 | 14 | class C3 extends C implements I2 { 15 | public int f(int i) { return 1; } // overloaded 16 | } 17 | 18 | class C4 extends C implements I3 { 19 | // Identical, no problem: 20 | public int f() { return 1; } 21 | } 22 | 23 | // Methods differ only by return type: 24 | //! class C5 extends C implements I1 {} 25 | //! interface I4 extends I1, I3 {} ///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/interfaces/Months.java: -------------------------------------------------------------------------------- 1 | //: interfaces/Months.java 2 | // Using interfaces to create groups of constants. 3 | package interfaces; 4 | 5 | public interface Months { 6 | int 7 | JANUARY = 1, FEBRUARY = 2, MARCH = 3, 8 | APRIL = 4, MAY = 5, JUNE = 6, JULY = 7, 9 | AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, 10 | NOVEMBER = 11, DECEMBER = 12; 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/interfaces/RandVals.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | // Initializing interface fields with 3 | // non-constant initializers. 4 | import java.util.*; 5 | 6 | public interface RandVals { 7 | Random RAND = new Random(47); 8 | int RANDOM_INT = RAND.nextInt(10); 9 | long RANDOM_LONG = RAND.nextLong() * 10; 10 | float RANDOM_FLOAT = RAND.nextLong() * 10; 11 | double RANDOM_DOUBLE = RAND.nextDouble() * 10; 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/interfaces/RandomDoubles.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | import java.util.*; 3 | 4 | public class RandomDoubles { 5 | private static Random rand = new Random(47); 6 | public double next() { return rand.nextDouble(); } 7 | public static void main(String[] args) { 8 | RandomDoubles rd = new RandomDoubles(); 9 | for(int i = 0; i < 7; i ++) 10 | System.out.print(rd.next() + " "); 11 | } 12 | } /* Output: 13 | 0.7271157860730044 0.5309454508634242 0.16020656493302599 0.18847866977771732 0.5166020801268457 0.2678662084200585 0.2613610344283964 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/interfaces/TestRandVals.java: -------------------------------------------------------------------------------- 1 | package interfaces; 2 | import static net.mindview.util.Print.*; 3 | 4 | public class TestRandVals { 5 | public static void main(String[] args) { 6 | print(RandVals.RANDOM_INT); 7 | print(RandVals.RANDOM_LONG); 8 | print(RandVals.RANDOM_FLOAT); 9 | print(RandVals.RANDOM_DOUBLE); 10 | } 11 | } /* Output: 12 | 8 13 | -32032247016559954 14 | -8.5939291E18 15 | 5.779976127815049 16 | *///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/interfaces/filters/BandPass.java: -------------------------------------------------------------------------------- 1 | //: interfaces/filters/BandPass.java 2 | package interfaces.filters; 3 | 4 | public class BandPass extends Filter { 5 | double lowCutoff, highCutoff; 6 | public BandPass(double lowCut, double highCut) { 7 | lowCutoff = lowCut; 8 | highCutoff = highCut; 9 | } 10 | public Waveform process(Waveform input) { return input; } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/interfaces/filters/Filter.java: -------------------------------------------------------------------------------- 1 | //: interfaces/filters/Filter.java 2 | package interfaces.filters; 3 | 4 | public class Filter { 5 | public String name() { 6 | return getClass().getSimpleName(); 7 | } 8 | public Waveform process(Waveform input) { return input; } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/interfaces/filters/HighPass.java: -------------------------------------------------------------------------------- 1 | //: interfaces/filters/HighPass.java 2 | package interfaces.filters; 3 | 4 | public class HighPass extends Filter { 5 | double cutoff; 6 | public HighPass(double cutoff) { this.cutoff = cutoff; } 7 | public Waveform process(Waveform input) { return input; } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/interfaces/filters/LowPass.java: -------------------------------------------------------------------------------- 1 | //: interfaces/filters/LowPass.java 2 | package interfaces.filters; 3 | 4 | public class LowPass extends Filter { 5 | double cutoff; 6 | public LowPass(double cutoff) { this.cutoff = cutoff; } 7 | public Waveform process(Waveform input) { 8 | return input; // Dummy processing 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/interfaces/filters/Waveform.java: -------------------------------------------------------------------------------- 1 | //: interfaces/filters/Waveform.java 2 | package interfaces.filters; 3 | 4 | public class Waveform { 5 | private static long counter; 6 | private final long id = counter++; 7 | public String toString() { return "Waveform " + id; } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/interfaces/interfaceprocessor/Apply.java: -------------------------------------------------------------------------------- 1 | //: interfaces/interfaceprocessor/Apply.java 2 | package interfaces.interfaceprocessor; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class Apply { 6 | public static void process(Processor p, Object s) { 7 | print("Using Processor " + p.name()); 8 | print(p.process(s)); 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/interfaces/interfaceprocessor/Processor.java: -------------------------------------------------------------------------------- 1 | //: interfaces/interfaceprocessor/Processor.java 2 | package interfaces.interfaceprocessor; 3 | 4 | public interface Processor { 5 | String name(); 6 | Object process(Object input); 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/io/Alien.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // A serializable class. 3 | import java.io.*; 4 | public class Alien implements Serializable {} ///:~ 5 | -------------------------------------------------------------------------------- /src/main/java/io/BasicFileOutput.java: -------------------------------------------------------------------------------- 1 | package io; 2 | import java.io.*; 3 | 4 | public class BasicFileOutput { 5 | static String file = "BasicFileOutput.out"; 6 | public static void main(String[] args) 7 | throws IOException { 8 | BufferedReader in = new BufferedReader( 9 | new StringReader( 10 | BufferedInputFile.read("BasicFileOutput.java"))); 11 | PrintWriter out = new PrintWriter( 12 | new BufferedWriter(new FileWriter(file))); 13 | int lineCount = 1; 14 | String s; 15 | while((s = in.readLine()) != null ) 16 | out.println(lineCount++ + ": " + s); 17 | out.close(); 18 | // Show the stored file: 19 | System.out.println(BufferedInputFile.read(file)); 20 | } 21 | } /* (Execute to see output) *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/io/BufferedInputFile.java: -------------------------------------------------------------------------------- 1 | package io; 2 | import java.io.*; 3 | 4 | public class BufferedInputFile { 5 | // Throw exceptions to console: 6 | public static String 7 | read(String filename) throws IOException { 8 | // Reading input by lines: 9 | BufferedReader in = new BufferedReader( 10 | new FileReader(filename)); 11 | String s; 12 | StringBuilder sb = new StringBuilder(); 13 | while((s = in.readLine())!= null) 14 | sb.append(s + "\n"); 15 | in.close(); 16 | return sb.toString(); 17 | } 18 | public static void main(String[] args) 19 | throws IOException { 20 | System.out.print(read("BufferedInputFile.java")); 21 | } 22 | } /* (Execute to see output) *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/io/ChangeSystemOut.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // Turn System.out into a PrintWriter. 3 | import java.io.*; 4 | 5 | public class ChangeSystemOut { 6 | public static void main(String[] args) { 7 | PrintWriter out = new PrintWriter(System.out, true); 8 | out.println("Hello, world"); 9 | } 10 | } /* Output: 11 | Hello, world 12 | *///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/io/Echo.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // How to read from standard input. 3 | // {RunByHand} 4 | import java.io.*; 5 | 6 | public class Echo { 7 | public static void main(String[] args) 8 | throws IOException { 9 | BufferedReader stdin = new BufferedReader( 10 | new InputStreamReader(System.in)); 11 | String s; 12 | while((s = stdin.readLine()) != null && s.length()!= 0) 13 | System.out.println(s); 14 | // An empty line or Ctrl-Z terminates the program 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/io/FileLocking.java: -------------------------------------------------------------------------------- 1 | package io; 2 | import java.nio.channels.*; 3 | import java.util.concurrent.*; 4 | import java.io.*; 5 | 6 | public class FileLocking { 7 | public static void main(String[] args) throws Exception { 8 | FileOutputStream fos= new FileOutputStream("file.txt"); 9 | FileLock fl = fos.getChannel().tryLock(); 10 | if(fl != null) { 11 | System.out.println("Locked File"); 12 | TimeUnit.MILLISECONDS.sleep(100); 13 | fl.release(); 14 | System.out.println("Released Lock"); 15 | } 16 | fos.close(); 17 | } 18 | } /* Output: 19 | Locked File 20 | Released Lock 21 | *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/io/FileOutputShortcut.java: -------------------------------------------------------------------------------- 1 | package io; 2 | import java.io.*; 3 | 4 | public class FileOutputShortcut { 5 | static String file = "FileOutputShortcut.out"; 6 | public static void main(String[] args) 7 | throws IOException { 8 | BufferedReader in = new BufferedReader( 9 | new StringReader( 10 | BufferedInputFile.read("FileOutputShortcut.java"))); 11 | // Here's the shortcut: 12 | PrintWriter out = new PrintWriter(file); 13 | int lineCount = 1; 14 | String s; 15 | while((s = in.readLine()) != null ) 16 | out.println(lineCount++ + ": " + s); 17 | out.close(); 18 | // Show the stored file: 19 | System.out.println(BufferedInputFile.read(file)); 20 | } 21 | } /* (Execute to see output) *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/io/FormattedMemoryInput.java: -------------------------------------------------------------------------------- 1 | package io; 2 | import java.io.*; 3 | 4 | public class FormattedMemoryInput { 5 | public static void main(String[] args) 6 | throws IOException { 7 | try { 8 | DataInputStream in = new DataInputStream( 9 | new ByteArrayInputStream( 10 | BufferedInputFile.read( 11 | "FormattedMemoryInput.java").getBytes())); 12 | while(true) 13 | System.out.print((char)in.readByte()); 14 | } catch(EOFException e) { 15 | System.err.println("End of stream"); 16 | } 17 | } 18 | } /* (Execute to see output) *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/io/FreezeAlien.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // Create a serialized output file. 3 | import java.io.*; 4 | 5 | public class FreezeAlien { 6 | public static void main(String[] args) throws Exception { 7 | ObjectOutput out = new ObjectOutputStream( 8 | new FileOutputStream("X.file")); 9 | Alien quellek = new Alien(); 10 | out.writeObject(quellek); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/io/LargeMappedFiles.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // Creating a very large file using mapping. 3 | // {RunByHand} 4 | import java.nio.*; 5 | import java.nio.channels.*; 6 | import java.io.*; 7 | import static net.mindview.util.Print.*; 8 | 9 | public class LargeMappedFiles { 10 | static int length = 0x8FFFFFF; // 128 MB 11 | public static void main(String[] args) throws Exception { 12 | MappedByteBuffer out = 13 | new RandomAccessFile("test.dat", "rw").getChannel() 14 | .map(FileChannel.MapMode.READ_WRITE, 0, length); 15 | for(int i = 0; i < length; i++) 16 | out.put((byte)'x'); 17 | print("Finished writing"); 18 | for(int i = length/2; i < length/2 + 6; i++) 19 | printnb((char)out.get(i)); 20 | } 21 | } ///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/io/MemoryInput.java: -------------------------------------------------------------------------------- 1 | package io; 2 | import java.io.*; 3 | 4 | public class MemoryInput { 5 | public static void main(String[] args) 6 | throws IOException { 7 | StringReader in = new StringReader( 8 | BufferedInputFile.read("MemoryInput.java")); 9 | int c; 10 | while((c = in.read()) != -1) 11 | System.out.print((char)c); 12 | } 13 | } /* (Execute to see output) *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/io/OSExecuteDemo.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // Demonstrates standard I/O redirection. 3 | import net.mindview.util.*; 4 | 5 | public class OSExecuteDemo { 6 | public static void main(String[] args) { 7 | OSExecute.command("javap OSExecuteDemo"); 8 | } 9 | } /* Output: 10 | Compiled from "OSExecuteDemo.java" 11 | public class OSExecuteDemo extends java.lang.Object{ 12 | public OSExecuteDemo(); 13 | public static void main(java.lang.String[]); 14 | } 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/io/TestEOF.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // Testing for end of file while reading a byte at a time. 3 | import java.io.*; 4 | 5 | public class TestEOF { 6 | public static void main(String[] args) 7 | throws IOException { 8 | DataInputStream in = new DataInputStream( 9 | new BufferedInputStream( 10 | new FileInputStream("TestEOF.java"))); 11 | while(in.available() != 0) 12 | System.out.print((char)in.readByte()); 13 | } 14 | } /* (Execute to see output) *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/io/TransferTo.java: -------------------------------------------------------------------------------- 1 | package io; 2 | // Using transferTo() between channels 3 | // {Args: TransferTo.java TransferTo.txt} 4 | import java.nio.channels.*; 5 | import java.io.*; 6 | 7 | public class TransferTo { 8 | public static void main(String[] args) throws Exception { 9 | if(args.length != 2) { 10 | System.out.println("arguments: sourcefile destfile"); 11 | System.exit(1); 12 | } 13 | FileChannel 14 | in = new FileInputStream(args[0]).getChannel(), 15 | out = new FileOutputStream(args[1]).getChannel(); 16 | in.transferTo(0, in.size(), out); 17 | // Or: 18 | // out.transferFrom(in, 0, in.size()); 19 | } 20 | } ///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/io/xfiles/ThawAlien.java: -------------------------------------------------------------------------------- 1 | package io.xfiles; 2 | // Try to recover a serialized file without the 3 | // class of object that's stored in that file. 4 | // {RunByHand} 5 | import java.io.*; 6 | 7 | public class ThawAlien { 8 | public static void main(String[] args) throws Exception { 9 | ObjectInputStream in = new ObjectInputStream( 10 | new FileInputStream(new File("..", "X.file"))); 11 | Object mystery = in.readObject(); 12 | System.out.println(mystery.getClass()); 13 | } 14 | } /* Output: 15 | class Alien 16 | *///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/atunit/Test.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/atunit/Test.java 2 | // The @Test tag. 3 | package net.mindview.atunit; 4 | import java.lang.annotation.*; 5 | 6 | @Target(ElementType.METHOD) 7 | @Retention(RetentionPolicy.RUNTIME) 8 | public @interface Test {} ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/atunit/TestObjectCleanup.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/atunit/TestObjectCleanup.java 2 | // The @Unit @TestObjectCleanup tag. 3 | package net.mindview.atunit; 4 | import java.lang.annotation.*; 5 | 6 | @Target(ElementType.METHOD) 7 | @Retention(RetentionPolicy.RUNTIME) 8 | public @interface TestObjectCleanup {} ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/atunit/TestObjectCreate.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/atunit/TestObjectCreate.java 2 | // The @Unit @TestObjectCreate tag. 3 | package net.mindview.atunit; 4 | import java.lang.annotation.*; 5 | 6 | @Target(ElementType.METHOD) 7 | @Retention(RetentionPolicy.RUNTIME) 8 | public @interface TestObjectCreate {} ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/atunit/TestProperty.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/atunit/TestProperty.java 2 | // The @Unit @TestProperty tag. 3 | package net.mindview.atunit; 4 | import java.lang.annotation.*; 5 | 6 | // Both fields and methods may be tagged as properties: 7 | @Target({ElementType.FIELD, ElementType.METHOD}) 8 | @Retention(RetentionPolicy.RUNTIME) 9 | public @interface TestProperty {} ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/simple/List.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/simple/List.java 2 | // Creating a package. 3 | package net.mindview.simple; 4 | 5 | public class List { 6 | public List() { 7 | System.out.println("net.mindview.simple.List"); 8 | } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/simple/Vector.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/simple/Vector.java 2 | // Creating a package. 3 | package net.mindview.simple; 4 | 5 | public class Vector { 6 | public Vector() { 7 | System.out.println("net.mindview.simple.Vector"); 8 | } 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/BinaryFile.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/BinaryFile.java 2 | // Utility for reading files in binary form. 3 | package net.mindview.util; 4 | import java.io.*; 5 | 6 | public class BinaryFile { 7 | public static byte[] read(File bFile) throws IOException{ 8 | BufferedInputStream bf = new BufferedInputStream( 9 | new FileInputStream(bFile)); 10 | try { 11 | byte[] data = new byte[bf.available()]; 12 | bf.read(data); 13 | return data; 14 | } finally { 15 | bf.close(); 16 | } 17 | } 18 | public static byte[] 19 | read(String bFile) throws IOException { 20 | return read(new File(bFile).getAbsoluteFile()); 21 | } 22 | } ///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/CollectionData.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/CollectionData.java 2 | // A Collection filled with data using a generator object. 3 | package net.mindview.util; 4 | import java.util.*; 5 | 6 | public class CollectionData extends ArrayList { 7 | public CollectionData(Generator gen, int quantity) { 8 | for(int i = 0; i < quantity; i++) 9 | add(gen.next()); 10 | } 11 | // A generic convenience method: 12 | public static CollectionData 13 | list(Generator gen, int quantity) { 14 | return new CollectionData(gen, quantity); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/DaemonThreadFactory.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/DaemonThreadFactory.java 2 | package net.mindview.util; 3 | import java.util.concurrent.*; 4 | 5 | public class DaemonThreadFactory implements ThreadFactory { 6 | public Thread newThread(Runnable r) { 7 | Thread t = new Thread(r); 8 | t.setDaemon(true); 9 | return t; 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/DaemonThreadPoolExecutor.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/DaemonThreadPoolExecutor.java 2 | package net.mindview.util; 3 | import java.util.concurrent.*; 4 | 5 | public class DaemonThreadPoolExecutor 6 | extends ThreadPoolExecutor { 7 | public DaemonThreadPoolExecutor() { 8 | super(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, 9 | new SynchronousQueue(), 10 | new DaemonThreadFactory()); 11 | } 12 | } ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Deque.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Deque.java 2 | // Creating a Deque from a LinkedList. 3 | package net.mindview.util; 4 | import java.util.*; 5 | 6 | public class Deque { 7 | private LinkedList deque = new LinkedList(); 8 | public void addFirst(T e) { deque.addFirst(e); } 9 | public void addLast(T e) { deque.addLast(e); } 10 | public T getFirst() { return deque.getFirst(); } 11 | public T getLast() { return deque.getLast(); } 12 | public T removeFirst() { return deque.removeFirst(); } 13 | public T removeLast() { return deque.removeLast(); } 14 | public int size() { return deque.size(); } 15 | public String toString() { return deque.toString(); } 16 | // And other methods as necessary... 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Enums.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Enums.java 2 | package net.mindview.util; 3 | import java.util.*; 4 | 5 | public class Enums { 6 | private static Random rand = new Random(47); 7 | public static > T random(Class ec) { 8 | return random(ec.getEnumConstants()); 9 | } 10 | public static T random(T[] values) { 11 | return values[rand.nextInt(values.length)]; 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/FiveTuple.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/FiveTuple.java 2 | package net.mindview.util; 3 | 4 | public class FiveTuple 5 | extends FourTuple { 6 | public final E fifth; 7 | public FiveTuple(A a, B b, C c, D d, E e) { 8 | super(a, b, c, d); 9 | fifth = e; 10 | } 11 | public String toString() { 12 | return "(" + first + ", " + second + ", " + 13 | third + ", " + fourth + ", " + fifth + ")"; 14 | } 15 | } ///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/FourTuple.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/FourTuple.java 2 | package net.mindview.util; 3 | 4 | public class FourTuple extends ThreeTuple { 5 | public final D fourth; 6 | public FourTuple(A a, B b, C c, D d) { 7 | super(a, b, c); 8 | fourth = d; 9 | } 10 | public String toString() { 11 | return "(" + first + ", " + second + ", " + 12 | third + ", " + fourth + ")"; 13 | } 14 | } ///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Generated.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Generated.java 2 | package net.mindview.util; 3 | import java.util.*; 4 | 5 | public class Generated { 6 | // Fill an existing array: 7 | public static T[] array(T[] a, Generator gen) { 8 | return new CollectionData(gen, a.length).toArray(a); 9 | } 10 | // Create a new array: 11 | @SuppressWarnings("unchecked") 12 | public static T[] array(Class type, 13 | Generator gen, int size) { 14 | T[] a = 15 | (T[])java.lang.reflect.Array.newInstance(type, size); 16 | return new CollectionData(gen, size).toArray(a); 17 | } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Generator.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Generator.java 2 | // A generic interface. 3 | package net.mindview.util; 4 | public interface Generator { T next(); } ///:~ 5 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Null.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Null.java 2 | package net.mindview.util; 3 | public interface Null {} ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/OSExecuteException.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/OSExecuteException.java 2 | package net.mindview.util; 3 | 4 | public class OSExecuteException extends RuntimeException { 5 | public OSExecuteException(String why) { super(why); } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Pair.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Pair.java 2 | package net.mindview.util; 3 | 4 | public class Pair { 5 | public final K key; 6 | public final V value; 7 | public Pair(K k, V v) { 8 | key = k; 9 | value = v; 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Stack.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Stack.java 2 | // Making a stack from a LinkedList. 3 | package net.mindview.util; 4 | import java.util.LinkedList; 5 | 6 | public class Stack { 7 | private LinkedList storage = new LinkedList(); 8 | public void push(T v) { storage.addFirst(v); } 9 | public T peek() { return storage.getFirst(); } 10 | public T pop() { return storage.removeFirst(); } 11 | public boolean empty() { return storage.isEmpty(); } 12 | public String toString() { return storage.toString(); } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/SwingConsole.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/SwingConsole.java 2 | // Tool for running Swing demos from the 3 | // console, both applets and JFrames. 4 | package net.mindview.util; 5 | import javax.swing.*; 6 | 7 | public class SwingConsole { 8 | public static void 9 | run(final JFrame f, final int width, final int height) { 10 | SwingUtilities.invokeLater(new Runnable() { 11 | public void run() { 12 | f.setTitle(f.getClass().getSimpleName()); 13 | f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 14 | f.setSize(width, height); 15 | f.setVisible(true); 16 | } 17 | }); 18 | } 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/TaskItem.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/TaskItem.java 2 | // A Future and the Callable that produced it. 3 | package net.mindview.util; 4 | import java.util.concurrent.*; 5 | 6 | public class TaskItem> { 7 | public final Future future; 8 | public final C task; 9 | public TaskItem(Future future, C task) { 10 | this.future = future; 11 | this.task = task; 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/ThreeTuple.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/ThreeTuple.java 2 | package net.mindview.util; 3 | 4 | public class ThreeTuple extends TwoTuple { 5 | public final C third; 6 | public ThreeTuple(A a, B b, C c) { 7 | super(a, b); 8 | third = c; 9 | } 10 | public String toString() { 11 | return "(" + first + ", " + second + ", " + third +")"; 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/Tuple.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/Tuple.java 2 | // Tuple library using type argument inference. 3 | package net.mindview.util; 4 | 5 | public class Tuple { 6 | public static TwoTuple tuple(A a, B b) { 7 | return new TwoTuple(a, b); 8 | } 9 | public static ThreeTuple 10 | tuple(A a, B b, C c) { 11 | return new ThreeTuple(a, b, c); 12 | } 13 | public static FourTuple 14 | tuple(A a, B b, C c, D d) { 15 | return new FourTuple(a, b, c, d); 16 | } 17 | public static 18 | FiveTuple tuple(A a, B b, C c, D d, E e) { 19 | return new FiveTuple(a, b, c, d, e); 20 | } 21 | } ///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/net/mindview/util/TwoTuple.java: -------------------------------------------------------------------------------- 1 | //: net/mindview/util/TwoTuple.java 2 | package net.mindview.util; 3 | 4 | public class TwoTuple { 5 | public final A first; 6 | public final B second; 7 | public TwoTuple(A a, B b) { first = a; second = b; } 8 | public String toString() { 9 | return "(" + first + ", " + second + ")"; 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/object/Documentation1.java: -------------------------------------------------------------------------------- 1 | package object; 2 | 3 | /** A class comment */ 4 | public class Documentation1 { 5 | /** A field comment */ 6 | public int i; 7 | /** A method comment */ 8 | public void f() {} 9 | } ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/object/Documentation2.java: -------------------------------------------------------------------------------- 1 | package object; 2 | 3 | /** 4 | *
 5 | * System.out.println(new Date());
 6 | * 
7 | */ 8 | public class Documentation2 {} 9 | ///:~ 10 | -------------------------------------------------------------------------------- /src/main/java/object/Documentation3.java: -------------------------------------------------------------------------------- 1 | package object; 2 | 3 | /** 4 | * You can even insert a list: 5 | *
    6 | *
  1. Item one 7 | *
  2. Item two 8 | *
  3. Item three 9 | *
10 | */ 11 | public class Documentation3 {} 12 | ///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/object/HelloDate.java: -------------------------------------------------------------------------------- 1 | package object; 2 | import java.util.*; 3 | 4 | /** The first Thinking in Java example program. 5 | * Displays a string and today's date. 6 | * @author Bruce Eckel 7 | * @author www.MindView.net 8 | * @version 4.0 9 | */ 10 | public class HelloDate { 11 | /** Entry point to class & application. 12 | * @param args array of string arguments 13 | * @throws exceptions No exceptions thrown 14 | */ 15 | public static void main(String[] args) { 16 | System.out.println("Hello, it's: "); 17 | System.out.println(new Date()); 18 | } 19 | } /* Output: (55% match) 20 | Hello, it's: 21 | Wed Oct 05 14:39:36 MDT 2005 22 | *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/object/ShowProperties.java: -------------------------------------------------------------------------------- 1 | package object; 2 | 3 | public class ShowProperties { 4 | public static void main(String[] args) { 5 | System.getProperties().list(System.out); 6 | System.out.println(System.getProperty("user.name")); 7 | System.out.println( 8 | System.getProperty("java.library.path")); 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/operators/AutoInc.java: -------------------------------------------------------------------------------- 1 | //: operators/AutoInc.java 2 | // Demonstrates the ++ and -- operators. 3 | package operators; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class AutoInc { 7 | public static void main(String[] args) { 8 | int i = 1; 9 | print("i : " + i); 10 | print("++i : " + ++i); // Pre-increment 11 | print("i++ : " + i++); // Post-increment 12 | print("i : " + i); 13 | print("--i : " + --i); // Pre-decrement 14 | print("i-- : " + i--); // Post-decrement 15 | print("i : " + i); 16 | } 17 | } /* Output: 18 | i : 1 19 | ++i : 2 20 | i++ : 2 21 | i : 3 22 | --i : 2 23 | i-- : 2 24 | i : 1 25 | *///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/operators/Casting.java: -------------------------------------------------------------------------------- 1 | //: operators/Casting.java 2 | package operators; 3 | public class Casting { 4 | public static void main(String[] args) { 5 | int i = 200; 6 | long lng = (long)i; 7 | lng = i; // "Widening," so cast not really required 8 | long lng2 = (long)200; 9 | lng2 = 200; 10 | // A "narrowing conversion": 11 | i = (int)lng2; // Cast required 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/operators/CastingNumbers.java: -------------------------------------------------------------------------------- 1 | //: operators/CastingNumbers.java 2 | // What happens when you cast a float 3 | // or double to an integral value? 4 | package operators; 5 | import static net.mindview.util.Print.*; 6 | 7 | public class CastingNumbers { 8 | public static void main(String[] args) { 9 | double above = 0.7, below = 0.4; 10 | float fabove = 0.7f, fbelow = 0.4f; 11 | print("(int)above: " + (int)above); 12 | print("(int)below: " + (int)below); 13 | print("(int)fabove: " + (int)fabove); 14 | print("(int)fbelow: " + (int)fbelow); 15 | } 16 | } /* Output: 17 | (int)above: 0 18 | (int)below: 0 19 | (int)fabove: 0 20 | (int)fbelow: 0 21 | *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/operators/EqualsMethod.java: -------------------------------------------------------------------------------- 1 | //: operators/EqualsMethod.java 2 | package operators; 3 | public class EqualsMethod { 4 | public static void main(String[] args) { 5 | Integer n1 = new Integer(47); 6 | Integer n2 = new Integer(47); 7 | System.out.println(n1.equals(n2)); 8 | } 9 | } /* Output: 10 | true 11 | *///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/operators/EqualsMethod2.java: -------------------------------------------------------------------------------- 1 | //: operators/EqualsMethod2.java 2 | // Default equals() does not compare contents. 3 | package operators; 4 | class Value { 5 | int i; 6 | } 7 | 8 | public class EqualsMethod2 { 9 | public static void main(String[] args) { 10 | Value v1 = new Value(); 11 | Value v2 = new Value(); 12 | v1.i = v2.i = 100; 13 | System.out.println(v1.equals(v2)); 14 | } 15 | } /* Output: 16 | false 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/operators/Equivalence.java: -------------------------------------------------------------------------------- 1 | //: operators/Equivalence.java 2 | package operators; 3 | public class Equivalence { 4 | public static void main(String[] args) { 5 | Integer n1 = new Integer(47); 6 | Integer n2 = new Integer(47); 7 | System.out.println(n1 == n2); 8 | System.out.println(n1 != n2); 9 | } 10 | } /* Output: 11 | false 12 | true 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/operators/Exponents.java: -------------------------------------------------------------------------------- 1 | //: operators/Exponents.java 2 | // "e" means "10 to the power." 3 | package operators; 4 | public class Exponents { 5 | public static void main(String[] args) { 6 | // Uppercase and lowercase 'e' are the same: 7 | float expFloat = 1.39e-43f; 8 | expFloat = 1.39E-43f; 9 | System.out.println(expFloat); 10 | double expDouble = 47e47d; // 'd' is optional 11 | double expDouble2 = 47e47; // Automatically double 12 | System.out.println(expDouble); 13 | } 14 | } /* Output: 15 | 1.39E-43 16 | 4.7E48 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/operators/HelloDate.java: -------------------------------------------------------------------------------- 1 | //: operators/HelloDate.java 2 | package operators; 3 | import java.util.*; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class HelloDate { 7 | public static void main(String[] args) { 8 | print("Hello, it's: "); 9 | print(new Date()); 10 | } 11 | } /* Output: (55% match) 12 | Hello, it's: 13 | Wed Oct 05 14:39:05 MDT 2005 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/operators/Overflow.java: -------------------------------------------------------------------------------- 1 | //: operators/Overflow.java 2 | // Surprise! Java lets you overflow. 3 | package operators; 4 | public class Overflow { 5 | public static void main(String[] args) { 6 | int big = Integer.MAX_VALUE; 7 | System.out.println("big = " + big); 8 | int bigger = big * 4; 9 | System.out.println("bigger = " + bigger); 10 | } 11 | } /* Output: 12 | big = 2147483647 13 | bigger = -4 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/operators/PassObject.java: -------------------------------------------------------------------------------- 1 | //: operators/PassObject.java 2 | // Passing objects to methods may not be 3 | // what you're used to. 4 | package operators; 5 | import static net.mindview.util.Print.*; 6 | 7 | class Letter { 8 | char c; 9 | } 10 | 11 | public class PassObject { 12 | static void f(Letter y) { 13 | y.c = 'z'; 14 | } 15 | public static void main(String[] args) { 16 | Letter x = new Letter(); 17 | x.c = 'a'; 18 | print("1: x.c: " + x.c); 19 | f(x); 20 | print("2: x.c: " + x.c); 21 | } 22 | } /* Output: 23 | 1: x.c: a 24 | 2: x.c: z 25 | *///:~ 26 | -------------------------------------------------------------------------------- /src/main/java/operators/Precedence.java: -------------------------------------------------------------------------------- 1 | //: operators/Precedence.java 2 | package operators; 3 | public class Precedence { 4 | public static void main(String[] args) { 5 | int x = 1, y = 2, z = 3; 6 | int a = x + y - 2/2 + z; // (1) 7 | int b = x + (y - 2)/(2 + z); // (2) 8 | System.out.println("a = " + a + " b = " + b); 9 | } 10 | } /* Output: 11 | a = 5 b = 1 12 | *///:~ 13 | -------------------------------------------------------------------------------- /src/main/java/operators/RoundingNumbers.java: -------------------------------------------------------------------------------- 1 | //: operators/RoundingNumbers.java 2 | // Rounding floats and doubles. 3 | package operators; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class RoundingNumbers { 7 | public static void main(String[] args) { 8 | double above = 0.7, below = 0.4; 9 | float fabove = 0.7f, fbelow = 0.4f; 10 | print("Math.round(above): " + Math.round(above)); 11 | print("Math.round(below): " + Math.round(below)); 12 | print("Math.round(fabove): " + Math.round(fabove)); 13 | print("Math.round(fbelow): " + Math.round(fbelow)); 14 | } 15 | } /* Output: 16 | Math.round(above): 1 17 | Math.round(below): 0 18 | Math.round(fabove): 1 19 | Math.round(fbelow): 0 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/operators/StringOperators.java: -------------------------------------------------------------------------------- 1 | //: operators/StringOperators.java 2 | package operators; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class StringOperators { 6 | public static void main(String[] args) { 7 | int x = 0, y = 1, z = 2; 8 | String s = "x, y, z "; 9 | print(s + x + y + z); 10 | print(x + " " + s); // Converts x to a String 11 | s += "(summed) = "; // Concatenation operator 12 | print(s + (x + y + z)); 13 | print("" + x); // Shorthand for Integer.toString() 14 | } 15 | } /* Output: 16 | x, y, z 012 17 | 0 x, y, z 18 | x, y, z (summed) = 3 19 | 0 20 | *///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/operators/TernaryIfElse.java: -------------------------------------------------------------------------------- 1 | //: operators/TernaryIfElse.java 2 | package operators; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class TernaryIfElse { 6 | static int ternary(int i) { 7 | return i < 10 ? i * 100 : i * 10; 8 | } 9 | static int standardIfElse(int i) { 10 | if(i < 10) 11 | return i * 100; 12 | else 13 | return i * 10; 14 | } 15 | public static void main(String[] args) { 16 | print(ternary(9)); 17 | print(ternary(10)); 18 | print(standardIfElse(9)); 19 | print(standardIfElse(10)); 20 | } 21 | } /* Output: 22 | 900 23 | 100 24 | 900 25 | 100 26 | *///:~ 27 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/CovariantReturn.java: -------------------------------------------------------------------------------- 1 | package polymorphism; 2 | 3 | class Grain { 4 | public String toString() { return "Grain"; } 5 | } 6 | 7 | class Wheat extends Grain { 8 | public String toString() { return "Wheat"; } 9 | } 10 | 11 | class Mill { 12 | Grain process() { return new Grain(); } 13 | } 14 | 15 | class WheatMill extends Mill { 16 | Wheat process() { return new Wheat(); } 17 | } 18 | 19 | public class CovariantReturn { 20 | public static void main(String[] args) { 21 | Mill m = new Mill(); 22 | Grain g = m.process(); 23 | System.out.println(g); 24 | m = new WheatMill(); 25 | g = m.process(); 26 | System.out.println(g); 27 | } 28 | } /* Output: 29 | Grain 30 | Wheat 31 | *///:~ 32 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/PrivateOverride.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/PrivateOverride.java 2 | // Trying to override a private method. 3 | package polymorphism; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class PrivateOverride { 7 | private void f() { print("private f()"); } 8 | public static void main(String[] args) { 9 | PrivateOverride po = new Derived(); 10 | po.f(); 11 | } 12 | } 13 | 14 | class Derived extends PrivateOverride { 15 | public void f() { print("public f()"); } 16 | } /* Output: 17 | private f() 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/Shapes.java: -------------------------------------------------------------------------------- 1 | package polymorphism; 2 | // Polymorphism in Java. 3 | import polymorphism.shape.*; 4 | 5 | public class Shapes { 6 | private static RandomShapeGenerator gen = 7 | new RandomShapeGenerator(); 8 | public static void main(String[] args) { 9 | Shape[] s = new Shape[9]; 10 | // Fill up the array with shapes: 11 | for(int i = 0; i < s.length; i++) 12 | s[i] = gen.next(); 13 | // Make polymorphic method calls: 14 | for(Shape shp : s) 15 | shp.draw(); 16 | } 17 | } /* Output: 18 | Triangle.draw() 19 | Triangle.draw() 20 | Square.draw() 21 | Triangle.draw() 22 | Square.draw() 23 | Triangle.draw() 24 | Square.draw() 25 | Triangle.draw() 26 | Circle.draw() 27 | *///:~ 28 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/music/Instrument.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/music/Instrument.java 2 | package polymorphism.music; 3 | import static net.mindview.util.Print.*; 4 | 5 | class Instrument { 6 | public void play(Note n) { 7 | print("Instrument.play()"); 8 | } 9 | } 10 | ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/music/Music.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/music/Music.java 2 | // Inheritance & upcasting. 3 | package polymorphism.music; 4 | 5 | public class Music { 6 | public static void tune(Instrument i) { 7 | // ... 8 | i.play(Note.MIDDLE_C); 9 | } 10 | public static void main(String[] args) { 11 | Wind flute = new Wind(); 12 | tune(flute); // Upcasting 13 | } 14 | } /* Output: 15 | Wind.play() MIDDLE_C 16 | *///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/music/Note.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/music/Note.java 2 | // Notes to play on musical instruments. 3 | package polymorphism.music; 4 | 5 | public enum Note { 6 | MIDDLE_C, C_SHARP, B_FLAT; // Etc. 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/music/Wind.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/music/Wind.java 2 | package polymorphism.music; 3 | 4 | // Wind objects are instruments 5 | // because they have the same interface: 6 | public class Wind extends Instrument { 7 | // Redefine interface method: 8 | public void play(Note n) { 9 | System.out.println("Wind.play() " + n); 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/shape/Circle.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/shape/Circle.java 2 | package polymorphism.shape; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class Circle extends Shape { 6 | public void draw() { print("Circle.draw()"); } 7 | public void erase() { print("Circle.erase()"); } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/shape/RandomShapeGenerator.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/shape/RandomShapeGenerator.java 2 | // A "factory" that randomly creates shapes. 3 | package polymorphism.shape; 4 | import java.util.*; 5 | 6 | public class RandomShapeGenerator { 7 | private Random rand = new Random(47); 8 | public Shape next() { 9 | switch(rand.nextInt(3)) { 10 | default: 11 | case 0: return new Circle(); 12 | case 1: return new Square(); 13 | case 2: return new Triangle(); 14 | } 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/shape/Shape.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/shape/Shape.java 2 | package polymorphism.shape; 3 | 4 | public class Shape { 5 | public void draw() {} 6 | public void erase() {} 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/shape/Square.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/shape/Square.java 2 | package polymorphism.shape; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class Square extends Shape { 6 | public void draw() { print("Square.draw()"); } 7 | public void erase() { print("Square.erase()"); } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/polymorphism/shape/Triangle.java: -------------------------------------------------------------------------------- 1 | //: polymorphism/shape/Triangle.java 2 | package polymorphism.shape; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class Triangle extends Shape { 6 | public void draw() { print("Triangle.draw()"); } 7 | public void erase() { print("Triangle.erase()"); } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/reusing/Cartoon.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | // Constructor calls during inheritance. 3 | import static net.mindview.util.Print.*; 4 | 5 | class Art { 6 | Art() { print("Art constructor"); } 7 | } 8 | 9 | class Drawing extends Art { 10 | Drawing() { print("Drawing constructor"); } 11 | } 12 | 13 | public class Cartoon extends Drawing { 14 | public Cartoon() { print("Cartoon constructor"); } 15 | public static void main(String[] args) { 16 | Cartoon x = new Cartoon(); 17 | } 18 | } /* Output: 19 | Art constructor 20 | Drawing constructor 21 | Cartoon constructor 22 | *///:~ 23 | -------------------------------------------------------------------------------- /src/main/java/reusing/Chess.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | // Inheritance, constructors and arguments. 3 | import static net.mindview.util.Print.*; 4 | 5 | class Game { 6 | Game(int i) { 7 | print("Game constructor"); 8 | } 9 | } 10 | 11 | class BoardGame extends Game { 12 | BoardGame(int i) { 13 | super(i); 14 | print("BoardGame constructor"); 15 | } 16 | } 17 | 18 | public class Chess extends BoardGame { 19 | Chess() { 20 | super(11); 21 | print("Chess constructor"); 22 | } 23 | public static void main(String[] args) { 24 | Chess x = new Chess(); 25 | } 26 | } /* Output: 27 | Game constructor 28 | BoardGame constructor 29 | Chess constructor 30 | *///:~ 31 | -------------------------------------------------------------------------------- /src/main/java/reusing/FinalArguments.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | // Using "final" with method arguments. 3 | 4 | class Gizmo { 5 | public void spin() {} 6 | } 7 | 8 | public class FinalArguments { 9 | void with(final Gizmo g) { 10 | //! g = new Gizmo(); // Illegal -- g is final 11 | } 12 | void without(Gizmo g) { 13 | g = new Gizmo(); // OK -- g not final 14 | g.spin(); 15 | } 16 | // void f(final int i) { i++; } // Can't change 17 | // You can only read from a final primitive: 18 | int g(final int i) { return i + 1; } 19 | public static void main(String[] args) { 20 | FinalArguments bf = new FinalArguments(); 21 | bf.without(null); 22 | bf.with(null); 23 | } 24 | } ///:~ 25 | -------------------------------------------------------------------------------- /src/main/java/reusing/Jurassic.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | // Making an entire class final. 3 | 4 | class SmallBrain {} 5 | 6 | final class Dinosaur { 7 | int i = 7; 8 | int j = 1; 9 | SmallBrain x = new SmallBrain(); 10 | void f() {} 11 | } 12 | 13 | //! class Further extends Dinosaur {} 14 | // error: Cannot extend final class 'Dinosaur' 15 | 16 | public class Jurassic { 17 | public static void main(String[] args) { 18 | Dinosaur n = new Dinosaur(); 19 | n.f(); 20 | n.i = 40; 21 | n.j++; 22 | } 23 | } ///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/reusing/Lisa.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | // {CompileTimeError} (Won't compile) 3 | 4 | class Lisa extends Homer { 5 | @Override void doh(Milhouse m) { 6 | System.out.println("doh(Milhouse)"); 7 | } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/reusing/SpaceShip.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | 3 | public class SpaceShip extends SpaceShipControls { 4 | private String name; 5 | public SpaceShip(String name) { this.name = name; } 6 | public String toString() { return name; } 7 | public static void main(String[] args) { 8 | SpaceShip protector = new SpaceShip("NSEA Protector"); 9 | protector.forward(100); 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/reusing/SpaceShipControls.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | 3 | public class SpaceShipControls { 4 | void up(int velocity) {} 5 | void down(int velocity) {} 6 | void left(int velocity) {} 7 | void right(int velocity) {} 8 | void forward(int velocity) {} 9 | void back(int velocity) {} 10 | void turboBoost() {} 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/reusing/Wind.java: -------------------------------------------------------------------------------- 1 | package reusing; 2 | // Inheritance & upcasting. 3 | 4 | class Instrument { 5 | public void play() {} 6 | static void tune(Instrument i) { 7 | // ... 8 | i.play(); 9 | } 10 | } 11 | 12 | // Wind objects are instruments 13 | // because they have the same interface: 14 | public class Wind extends Instrument { 15 | public static void main(String[] args) { 16 | Wind flute = new Wind(); 17 | Instrument.tune(flute); // Upcasting 18 | } 19 | } ///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/strings/ArrayListDisplay.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import generics.coffee.*; 3 | import java.util.*; 4 | 5 | public class ArrayListDisplay { 6 | public static void main(String[] args) { 7 | ArrayList coffees = new ArrayList(); 8 | for(Coffee c : new CoffeeGenerator(10)) 9 | coffees.add(c); 10 | System.out.println(coffees); 11 | } 12 | } /* Output: 13 | [Americano 0, Latte 1, Americano 2, Mocha 3, Mocha 4, Breve 5, Americano 6, Latte 7, Cappuccino 8, Cappuccino 9] 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/strings/Concatenation.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class Concatenation { 4 | public static void main(String[] args) { 5 | String mango = "mango"; 6 | String s = "abc" + mango + "def" + 47; 7 | System.out.println(s); 8 | } 9 | } /* Output: 10 | abcmangodef47 11 | *///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/strings/DatabaseException.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class DatabaseException extends Exception { 4 | public DatabaseException(int transactionID, int queryID, 5 | String message) { 6 | super(String.format("(t%d, q%d) %s", transactionID, 7 | queryID, message)); 8 | } 9 | public static void main(String[] args) { 10 | try { 11 | throw new DatabaseException(3, 7, "Write failed"); 12 | } catch(Exception e) { 13 | System.out.println(e); 14 | } 15 | } 16 | } /* Output: 17 | DatabaseException: (t3, q7) Write failed 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/strings/Finding.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import java.util.regex.*; 3 | import static net.mindview.util.Print.*; 4 | 5 | public class Finding { 6 | public static void main(String[] args) { 7 | Matcher m = Pattern.compile("\\w+") 8 | .matcher("Evening is full of the linnet's wings"); 9 | while(m.find()) 10 | printnb(m.group() + " "); 11 | print(); 12 | int i = 0; 13 | while(m.find(i)) { 14 | printnb(m.group() + " "); 15 | i++; 16 | } 17 | } 18 | } /* Output: 19 | Evening is full of the linnet s wings 20 | Evening vening ening ning ing ng g is is s full full ull ll l of of f the the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s 21 | *///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/strings/Immutable.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import static net.mindview.util.Print.*; 3 | 4 | public class Immutable { 5 | public static String upcase(String s) { 6 | return s.toUpperCase(); 7 | } 8 | public static void main(String[] args) { 9 | String q = "howdy"; 10 | print(q); // howdy 11 | String qq = upcase(q); 12 | print(qq); // HOWDY 13 | print(q); // howdy 14 | } 15 | } /* Output: 16 | howdy 17 | HOWDY 18 | howdy 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/strings/InfiniteRecursion.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | // Accidental recursion. 3 | // {RunByHand} 4 | import java.util.*; 5 | 6 | public class InfiniteRecursion { 7 | public String toString() { 8 | return " InfiniteRecursion address: " + this + "\n"; 9 | } 10 | public static void main(String[] args) { 11 | List v = 12 | new ArrayList(); 13 | for(int i = 0; i < 10; i++) 14 | v.add(new InfiniteRecursion()); 15 | System.out.println(v); 16 | } 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/strings/IntegerMatch.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class IntegerMatch { 4 | public static void main(String[] args) { 5 | System.out.println("-1234".matches("-?\\d+")); 6 | System.out.println("5678".matches("-?\\d+")); 7 | System.out.println("+911".matches("-?\\d+")); 8 | System.out.println("+911".matches("(-|\\+)?\\d+")); 9 | } 10 | } /* Output: 11 | true 12 | true 13 | false 14 | true 15 | *///:~ 16 | -------------------------------------------------------------------------------- /src/main/java/strings/ReFlags.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import java.util.regex.*; 3 | 4 | public class ReFlags { 5 | public static void main(String[] args) { 6 | Pattern p = Pattern.compile("^java", 7 | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); 8 | Matcher m = p.matcher( 9 | "java has regex\nJava has regex\n" + 10 | "JAVA has pretty good regular expressions\n" + 11 | "Regular expressions are in Java"); 12 | while(m.find()) 13 | System.out.println(m.group()); 14 | } 15 | } /* Output: 16 | java 17 | Java 18 | JAVA 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/strings/Replacing.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import static net.mindview.util.Print.*; 3 | 4 | public class Replacing { 5 | static String s = Splitting.knights; 6 | public static void main(String[] args) { 7 | print(s.replaceFirst("f\\w+", "located")); 8 | print(s.replaceAll("shrubbery|tree|herring","banana")); 9 | } 10 | } /* Output: 11 | Then, when you have located the shrubbery, you must cut down the mightiest tree in the forest... with... a herring! 12 | Then, when you have found the banana, you must cut down the mightiest banana in the forest... with... a banana! 13 | *///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/strings/Resetting.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import java.util.regex.*; 3 | 4 | public class Resetting { 5 | public static void main(String[] args) throws Exception { 6 | Matcher m = Pattern.compile("[frb][aiu][gx]") 7 | .matcher("fix the rug with bags"); 8 | while(m.find()) 9 | System.out.print(m.group() + " "); 10 | System.out.println(); 11 | m.reset("fix the rig with rags"); 12 | while(m.find()) 13 | System.out.print(m.group() + " "); 14 | } 15 | } /* Output: 16 | fix rug bag 17 | fix rig rag 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/strings/Rudolph.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class Rudolph { 4 | public static void main(String[] args) { 5 | for(String pattern : new String[]{ "Rudolph", 6 | "[rR]udolph", "[rR][aeiou][a-z]ol.*", "R.*" }) 7 | System.out.println("Rudolph".matches(pattern)); 8 | } 9 | } /* Output: 10 | true 11 | true 12 | true 13 | true 14 | *///:~ 15 | -------------------------------------------------------------------------------- /src/main/java/strings/ScannerDelimiter.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import java.util.*; 3 | 4 | public class ScannerDelimiter { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner("12, 42, 78, 99, 42"); 7 | scanner.useDelimiter("\\s*,\\s*"); 8 | while(scanner.hasNextInt()) 9 | System.out.println(scanner.nextInt()); 10 | } 11 | } /* Output: 12 | 12 13 | 42 14 | 78 15 | 99 16 | 42 17 | *///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/strings/SimpleFormat.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class SimpleFormat { 4 | public static void main(String[] args) { 5 | int x = 5; 6 | double y = 5.332542; 7 | // The old way: 8 | System.out.println("Row 1: [" + x + " " + y + "]"); 9 | // The new way: 10 | System.out.format("Row 1: [%d %f]\n", x, y); 11 | // or 12 | System.out.printf("Row 1: [%d %f]\n", x, y); 13 | } 14 | } /* Output: 15 | Row 1: [5 5.332542] 16 | Row 1: [5 5.332542] 17 | Row 1: [5 5.332542] 18 | *///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/strings/SplitDemo.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | import java.util.regex.*; 3 | import java.util.*; 4 | import static net.mindview.util.Print.*; 5 | 6 | public class SplitDemo { 7 | public static void main(String[] args) { 8 | String input = 9 | "This!!unusual use!!of exclamation!!points"; 10 | print(Arrays.toString( 11 | Pattern.compile("!!").split(input))); 12 | // Only do the first three: 13 | print(Arrays.toString( 14 | Pattern.compile("!!").split(input, 3))); 15 | } 16 | } /* Output: 17 | [This, unusual use, of exclamation, points] 18 | [This, unusual use, of exclamation!!points] 19 | *///:~ 20 | -------------------------------------------------------------------------------- /src/main/java/strings/WhitherStringBuilder.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class WhitherStringBuilder { 4 | public String implicit(String[] fields) { 5 | String result = ""; 6 | for(int i = 0; i < fields.length; i++) 7 | result += fields[i]; 8 | return result; 9 | } 10 | public String explicit(String[] fields) { 11 | StringBuilder result = new StringBuilder(); 12 | for(int i = 0; i < fields.length; i++) 13 | result.append(fields[i]); 14 | return result.toString(); 15 | } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/swt/DisplayEnvironment.java: -------------------------------------------------------------------------------- 1 | package swt; 2 | import swt.util.*; 3 | import org.eclipse.swt.*; 4 | import org.eclipse.swt.widgets.*; 5 | import org.eclipse.swt.layout.*; 6 | import java.util.*; 7 | 8 | public class DisplayEnvironment implements SWTApplication { 9 | public void createContents(Composite parent) { 10 | parent.setLayout(new FillLayout()); 11 | Text text = new Text(parent, SWT.WRAP | SWT.V_SCROLL); 12 | for(Map.Entry entry: System.getenv().entrySet()) { 13 | text.append(entry.getKey() + ": " + 14 | entry.getValue() + "\n"); 15 | } 16 | } 17 | public static void main(String [] args) { 18 | SWTConsole.run(new DisplayEnvironment(), 800, 600); 19 | } 20 | } ///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/swt/HelloSWT.java: -------------------------------------------------------------------------------- 1 | package swt; 2 | // {Requires: org.eclipse.swt.widgets.Display; You must 3 | // install the SWT library from http://www.eclipse.org } 4 | import org.eclipse.swt.widgets.*; 5 | 6 | public class HelloSWT { 7 | public static void main(String [] args) { 8 | Display display = new Display(); 9 | Shell shell = new Shell(display); 10 | shell.setText("Hi there, SWT!"); // Title bar 11 | shell.open(); 12 | while(!shell.isDisposed()) 13 | if(!display.readAndDispatch()) 14 | display.sleep(); 15 | display.dispose(); 16 | } 17 | } ///:~ 18 | -------------------------------------------------------------------------------- /src/main/java/swt/util/SWTApplication.java: -------------------------------------------------------------------------------- 1 | //: swt/util/SWTApplication.java 2 | package swt.util; 3 | import org.eclipse.swt.widgets.*; 4 | 5 | public interface SWTApplication { 6 | void createContents(Composite parent); 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/swt/util/SWTConsole.java: -------------------------------------------------------------------------------- 1 | //: swt/util/SWTConsole.java 2 | package swt.util; 3 | import org.eclipse.swt.widgets.*; 4 | 5 | public class SWTConsole { 6 | public static void 7 | run(SWTApplication swtApp, int width, int height) { 8 | Display display = new Display(); 9 | Shell shell = new Shell(display); 10 | shell.setText(swtApp.getClass().getSimpleName()); 11 | swtApp.createContents(shell); 12 | shell.setSize(width, height); 13 | shell.open(); 14 | while(!shell.isDisposed()) { 15 | if(!display.readAndDispatch()) 16 | display.sleep(); 17 | } 18 | display.dispose(); 19 | } 20 | } ///:~ 21 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/BoundedClassReferences.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | 3 | public class BoundedClassReferences { 4 | public static void main(String[] args) { 5 | Class bounded = int.class; 6 | bounded = double.class; 7 | bounded = Number.class; 8 | // Or anything else derived from Number. 9 | } 10 | } ///:~ 11 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/ClassCasts.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | 3 | class Building {} 4 | class House extends Building {} 5 | 6 | public class ClassCasts { 7 | public static void main(String[] args) { 8 | Building b = new House(); 9 | Class houseType = House.class; 10 | House h = houseType.cast(b); 11 | h = (House)b; // ... or just do this. 12 | } 13 | } ///:~ 14 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/GenericClassReferences.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | 3 | public class GenericClassReferences { 4 | public static void main(String[] args) { 5 | Class intClass = int.class; 6 | Class genericIntClass = int.class; 7 | genericIntClass = Integer.class; // Same thing 8 | intClass = double.class; 9 | // genericIntClass = double.class; // Illegal 10 | } 11 | } ///:~ 12 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/InterfaceViolation.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | // Sneaking around an interface. 3 | import typeinfo.interfacea.*; 4 | 5 | class B implements A { 6 | public void f() {} 7 | public void g() {} 8 | } 9 | 10 | public class InterfaceViolation { 11 | public static void main(String[] args) { 12 | A a = new B(); 13 | a.f(); 14 | // a.g(); // Compile error 15 | System.out.println(a.getClass().getName()); 16 | if(a instanceof B) { 17 | B b = (B)a; 18 | b.g(); 19 | } 20 | } 21 | } /* Output: 22 | B 23 | *///:~ 24 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/Operation.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | 3 | public interface Operation { 4 | String description(); 5 | void command(); 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/PetCount2.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | import typeinfo.pets.*; 3 | 4 | public class PetCount2 { 5 | public static void main(String[] args) { 6 | PetCount.countPets(Pets.creator); 7 | } 8 | } /* (Execute to see output) *///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/Robot.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | import java.util.*; 3 | import net.mindview.util.*; 4 | 5 | public interface Robot { 6 | String name(); 7 | String model(); 8 | List operations(); 9 | class Test { 10 | public static void test(Robot r) { 11 | if(r instanceof Null) 12 | System.out.println("[Null Robot]"); 13 | System.out.println("Robot name: " + r.name()); 14 | System.out.println("Robot model: " + r.model()); 15 | for(Operation operation : r.operations()) { 16 | System.out.println(operation.description()); 17 | operation.command(); 18 | } 19 | } 20 | } 21 | } ///:~ 22 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/WildcardClassReferences.java: -------------------------------------------------------------------------------- 1 | package typeinfo; 2 | 3 | public class WildcardClassReferences { 4 | public static void main(String[] args) { 5 | Class intClass = int.class; 6 | intClass = double.class; 7 | } 8 | } ///:~ 9 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/factory/Factory.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/factory/Factory.java 2 | package typeinfo.factory; 3 | public interface Factory { T create(); } ///:~ 4 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/interfacea/A.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/interfacea/A.java 2 | package typeinfo.interfacea; 3 | 4 | public interface A { 5 | void f(); 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/packageaccess/HiddenC.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/packageaccess/HiddenC.java 2 | package typeinfo.packageaccess; 3 | import typeinfo.interfacea.*; 4 | import static net.mindview.util.Print.*; 5 | 6 | class C implements A { 7 | public void f() { print("public C.f()"); } 8 | public void g() { print("public C.g()"); } 9 | void u() { print("package C.u()"); } 10 | protected void v() { print("protected C.v()"); } 11 | private void w() { print("private C.w()"); } 12 | } 13 | 14 | public class HiddenC { 15 | public static A makeA() { return new C(); } 16 | } ///:~ 17 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Cat.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Cat.java 2 | package typeinfo.pets; 3 | 4 | public class Cat extends Pet { 5 | public Cat(String name) { super(name); } 6 | public Cat() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Cymric.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Cymric.java 2 | package typeinfo.pets; 3 | 4 | public class Cymric extends Manx { 5 | public Cymric(String name) { super(name); } 6 | public Cymric() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Dog.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Dog.java 2 | package typeinfo.pets; 3 | 4 | public class Dog extends Pet { 5 | public Dog(String name) { super(name); } 6 | public Dog() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/EgyptianMau.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/EgyptianMau.java 2 | package typeinfo.pets; 3 | 4 | public class EgyptianMau extends Cat { 5 | public EgyptianMau(String name) { super(name); } 6 | public EgyptianMau() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Hamster.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Hamster.java 2 | package typeinfo.pets; 3 | 4 | public class Hamster extends Rodent { 5 | public Hamster(String name) { super(name); } 6 | public Hamster() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Manx.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Manx.java 2 | package typeinfo.pets; 3 | 4 | public class Manx extends Cat { 5 | public Manx(String name) { super(name); } 6 | public Manx() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Mouse.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Mouse.java 2 | package typeinfo.pets; 3 | 4 | public class Mouse extends Rodent { 5 | public Mouse(String name) { super(name); } 6 | public Mouse() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Mutt.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Mutt.java 2 | package typeinfo.pets; 3 | 4 | public class Mutt extends Dog { 5 | public Mutt(String name) { super(name); } 6 | public Mutt() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Person.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Person.java 2 | package typeinfo.pets; 3 | 4 | public class Person extends Individual { 5 | public Person(String name) { super(name); } 6 | } ///:~ 7 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Pet.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Pet.java 2 | package typeinfo.pets; 3 | 4 | public class Pet extends Individual { 5 | public Pet(String name) { super(name); } 6 | public Pet() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Pets.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Pets.java 2 | // Facade to produce a default PetCreator. 3 | package typeinfo.pets; 4 | import java.util.*; 5 | 6 | public class Pets { 7 | public static final PetCreator creator = 8 | new LiteralPetCreator(); 9 | public static Pet randomPet() { 10 | return creator.randomPet(); 11 | } 12 | public static Pet[] createArray(int size) { 13 | return creator.createArray(size); 14 | } 15 | public static ArrayList arrayList(int size) { 16 | return creator.arrayList(size); 17 | } 18 | } ///:~ 19 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Pug.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Pug.java 2 | package typeinfo.pets; 3 | 4 | public class Pug extends Dog { 5 | public Pug(String name) { super(name); } 6 | public Pug() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Rat.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Rat.java 2 | package typeinfo.pets; 3 | 4 | public class Rat extends Rodent { 5 | public Rat(String name) { super(name); } 6 | public Rat() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/pets/Rodent.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/pets/Rodent.java 2 | package typeinfo.pets; 3 | 4 | public class Rodent extends Pet { 5 | public Rodent(String name) { super(name); } 6 | public Rodent() { super(); } 7 | } ///:~ 8 | -------------------------------------------------------------------------------- /src/main/java/typeinfo/toys/GenericToyTest.java: -------------------------------------------------------------------------------- 1 | //: typeinfo/toys/GenericToyTest.java 2 | // Testing class Class. 3 | package typeinfo.toys; 4 | 5 | public class GenericToyTest { 6 | public static void main(String[] args) throws Exception { 7 | Class ftClass = FancyToy.class; 8 | // Produces exact type: 9 | FancyToy fancyToy = ftClass.newInstance(); 10 | Class up = ftClass.getSuperclass(); 11 | // This won't compile: 12 | // Class up2 = ftClass.getSuperclass(); 13 | // Only produces Object: 14 | Object obj = up.newInstance(); 15 | } 16 | } ///:~ 17 | --------------------------------------------------------------------------------