480 likes | 500 Views
Explore enumerated types in Java and learn about recursion techniques. Understand ordinal values and recursive definitions with examples. See how to use recursion effectively in programming.
E N D
Going further • Enumerated types • Recursion • Collections
Enumerated Types • Java allows you to define an enumerated type, which has the set of possible values specified in the definition. • The values are identifiers of your own choosing • The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; • Any number of values can be listed
Enumerated Types • Once a type is defined, a variable of that type can be declared Season time; and it can be assigned a value time = Season.fall; • Enumerated types are type-safe – you cannot assign any value other than those listed
Ordinal Values • Each value of an enumerated type has an integer associated with it, called its ordinal value • The first value in an enumerated type has an ordinal value of zero, the second one, and so on • You cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value
Enumerated Types • Each variable of an enumerated type is an object • Enumerated typs have several methods • The ordinal method returns the ordinal value of the object • The name method returns the name of the identifier corresponding to the object's value • See IceCream.java
Enumerated Types • An enumerated type definition can be more interesting than a simple list of values • Because they are like classes, we can add additional instance data and methods • We can define an enum constructor as well • Each value listed for the enumerated type calls the constructor • See Season.java • See SeasonTester.java
Enumerated Types • Every enumerated type contains a static method called values that returns a list of all possible values for that type • The list returned from values is iterable, so a for loop can be used to process them easily • An enumerated type cannot be instantiated outside of its own definition • A carefully designed enumerated type provides a versatile and type-safe mechanism for managing data
Recursion • Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems • A recursive definition is one which uses the word or concept being defined in the definition itself • a recursive definition of an English word is often not helpful • In math and computer science, a recursive definition can be an appropriate way to express a concept
Recursive Definitions • Consider the following list of numbers: 24, 88, 40, 37 • Such a list can be defined as follows: A LIST is a: number or a: number comma LIST • That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST • The concept of a LIST is used to define itself
Recursive Definitions • The recursive part of the LIST definition is used several times, terminating with the non-recursive part: number comma LIST 24 , 88, 40, 37 number comma LIST 88 , 40, 37 number comma LIST 40 , 37 number 37
Infinite Recursion • All recursive definitions have to have a non-recursive part • If they didn't, there would be no way to terminate the recursive path • Such a definition would cause infinite recursion • This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself • The non-recursive part is often called the base case
Recursive Definitions • N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive • This definition can be expressed recursively as: 1! = 1 N! = N * (N-1)! • A factorial is defined in terms of another factorial • Eventually, the base case of 1! is reached
120 24 6 2 Recursive Definitions 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1
Recursive Programming • A method in Java can invoke itself; if set up that way, it is called a recursive method • The code of a recursive method must be structured to handle both the base case and the recursive case • Each call to the method sets up a new execution environment, with new parameters and local variables • As with any method call, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself) • See Factorial.java
Recursive Programming • Note that just because we can use recursion to solve a problem, doesn't mean we should • For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand • However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version • You must carefully decide whether recursion is the correct technique for any problem
Recursive Directory Listing • Suppose you want to list all the files in a directory including files in any subdirectories that might be present. • Algorithm for each entry in the current directory if it is a file, print its name else // must be a directory do recursive call on the entry
Towers of Hanoi • The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs • The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top • The goal is to move all of the disks from one peg to another under the following rules: • We can move only one disk at a time • We cannot move a larger disk on top of a smaller one
Original Configuration Move 1 Move 2 Move 3 Towers of Hanoi
Move 4 Move 5 Move 6 Move 7 (done) Towers of Hanoi
Towers of Hanoi • An iterative solution to the Towers of Hanoi is quite complex • A recursive solution is much shorter and more elegant • See SolveTowers.java • See TowersOfHanoi.java
Fractals • A fractal is a geometric shape made up of the same pattern repeated in different sizes and orientations • The Koch Snowflake is a particular fractal that begins with an equilateral triangle • To get a higher order of the fractal, the sides of the triangle are replaced with angled line segments • See KochSnowflake.java • See KochPanel.java
< x5, y5> < x5, y5> < x4, y4> < x3, y3> < x2, y2> < x1, y1> < x1, y1> Koch Snowflakes Becomes
Other Examples of Recursion • Recursive sort algorithms • Recursive data structures • Chapter 12 • COMPSCI 225
Collections • A collection is an object that serves as a repository for other objects • A collection usually provides services such as adding, removing, and otherwise managing the elements it contains • Sometimes the elements in a collection are ordered, sometimes they are not • Sometimes collections are homogeneous, containing all the same type of objects, and sometimes they are heterogeneous
Dynamic Structures • A static data structure has a fixed size • This meaning is different from the meaning of the static modifier • Arrays are static; once you define the number of elements it can hold, the size doesn’t change • A dynamicdata structure grows and shrinks at execution time as required by its contents • A dynamic data structure is implemented using links
student John Smith 40725 3.58 Object References • Recall that an object reference is a variable that stores the address of an object • A reference also can be called a pointer • References often are depicted graphically:
John Smith 40725 3.57 Jane Jones 58821 3.72 References as Links • Object references can be used to create links between objects • Suppose a Student class contains a reference to another Student object
studentList References as Links • References can be used to create a variety of linked structures, such as a linked list:
dequeue enqueue Queues • A queue is similar to a list but adds items only to the rear of the list and removes them only from the front • It is called a FIFO data structure: First-In, First-Out • Analogy: a line of people at a bank teller’s window
push pop Stacks Stacks often are drawn vertically: • A stack ADT is also a linear data structure • Items are added and removed from only one end of a stack • It is therefore LIFO: Last-In, First-Out • Example: a stack of plates in a cupboard, a stack of hay bales in a barn
Trees • A tree is a non-linear data structure that consists of a root node and potentially many levels of additional nodes that form a hierarchy • In a general tree, each node can have many child nodes • We often work with binary trees which have no more than two children per node
Binary Trees • In a binary tree, each node can have no more than two child nodes • A binary tree can be defined recursively. Either it is empty (the base case) or it consists of a root and two subtrees, each of which is a binary tree • Trees are typically are represented using references as dynamic links, though it is possible to use fixed representations like arrays • For binary trees, this requires storing only two links per node to the left and right child
Graphs • A graph is a non-linear structure • Unlike a tree or binary tree, a graph does not have a root • Any node in a graph can be connected to any other node by an edge • Analogy: the highway system connecting cities on a map
Collection Classes • The Java standard library contains several classes that represent collections, often referred to as the Java Collections API • Their underlying implementation is implied in the class names such as ArrayList and LinkedList • Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap
Generics • As mentioned in Chapter 7, Java supports generic types, which are useful when defining collections • A class can be defined to operate on a generic data type which is specified when the class is instantiated: LinkedList<Book> myList = new LinkedList<Book>(); • By specifying the type stored in a collection, only objects of that type can be added to it • Furthermore, when an object is removed, its type is already established
Other Languages • There are a number of other languages with a syntax very similar to that of Java • Java's syntax is based on that of C which is not object-oriented • C++ was designed to be backwards-compatible with C • C# was based on C/C++ without the backwards-compatibility • Many of the scripting languages started from C's syntax • JavaScript is a scripting language that is used inside web pages • It is not related to Java
Other Languages: C# • Like Java, C# is • A modern, general-purpose object-oriented language • Based on C and C++ • C# is part of the .NET family of languages supported by MicroSoft • Multiple languages which can interoperate • Languages compile to a common intermediate language • Common Language Runtime runs programs from all the .NET languages
C# Program Structure • A program consists of one or more files • A file can contain one or more classes and/or namespaces • name of file is not tied to name of class • At least one class must contain Main • There are several allowed signatures • return type is either int or void • either no parameter or String array
First Program namespace FirstProgram { class First { static void Main() { System.Console.WriteLine( "Welcome to C#!"); } } }
Console I/O • System.Console.WriteLine( arg) • argument can be any type • for objects, ToString is invoked • System.Console.ReadLine() • returns a String • System is a namespace • using System; allows you to omit the namespace when calling the method
C# Types • Value types • simple types: primitive types from Java plus unsigned types and decimal • Reference types - objects
Operators • Has same operators as Java with similar precedence and associativity • == compares values for strings and simple types, addresses for all other objects
C# on onyx • mono is an open-source project that provides facilities for running C# programs under Linux • http://www.mono-project.com • Compile a program by typing • mcs First.cs • Run a program by typing • mono First.exe
C# using VMWare • There is a Windows virtual machine on the onyx workstations • vmware & • C# Express is installed on the virtual machine • You can download the .NET development environment to your own Windows machine for free using your MSDN account