• Tidak ada hasil yang ditemukan

PPT Slide 1

N/A
N/A
Protected

Academic year: 2023

Membagikan "PPT Slide 1"

Copied!
85
0
0

Teks penuh

(1)

Data Structures for Java Data Structures for Java

William H. Ford William H. Ford William R. Topp William R. Topp

Chapter 1 Chapter 1

Classes and Objects

Classes and Objects

(2)

Data Structures Data Structures

 Storage processing machines that handle Storage processing machines that handle large sets of data. The structures, called large sets of data. The structures, called

collections, have operations that add and collections, have operations that add and

remove items and provide access to the remove items and provide access to the

elements in the collection.

elements in the collection.

(3)

Arrays Arrays

 Data structures that store a large Data structures that store a large

collection of data and allow direct access collection of data and allow direct access

to the elements by using an index.

to the elements by using an index.

Have a fixed length. A programmer must Have a fixed length. A programmer must

specify the size of an array at the point of its specify the size of an array at the point of its

declaration.

declaration.

Applications often need storage structures, Applications often need storage structures,

which grow and contract as data is added and

which grow and contract as data is added and

(4)

ArrayList ArrayList

 Indexing features of an array Indexing features of an array

 Created with initial capacity that Created with initial capacity that

designates the available space to hold designates the available space to hold

elements.

elements.

 Ability to grow dynamically to meet the Ability to grow dynamically to meet the runtime needs of a program

runtime needs of a program

(5)

ArrayList (concluded) ArrayList (concluded)

 Not an efficient storage structure for Not an efficient storage structure for

general insertion and deletion of items at general insertion and deletion of items at

an arbitrary position in a list.

an arbitrary position in a list.

Insert requires shifting a block of elements to Insert requires shifting a block of elements to the right to make room for a new item.

the right to make room for a new item.

Deletion requires shifting a block of elements Deletion requires shifting a block of elements to the left to fill in the gap created by the

to the left to fill in the gap created by the missing item.

missing item.

(6)

LinkedList LinkedList

 Items are linked together as in a chain. Items are linked together as in a chain.

 Add a new item by breaking a link in the Add a new item by breaking a link in the chain and then creating two new links to chain and then creating two new links to

connect the element.

connect the element.

 Insertion or deletion does not require the Insertion or deletion does not require the moving other elements to make room for moving other elements to make room for

the new element.

the new element.

(7)

Map Map

 ArrayLists and LinkedList structure store ArrayLists and LinkedList structure store elements by position.

elements by position.

 Map stores data as a key-value pair. The Map stores data as a key-value pair. The key identifies the element and the value is key identifies the element and the value is

associated information.

associated information.

(8)

Map (continued) Map (continued)

 Map allows a program to access a value Map allows a program to access a value using the key which acts like an index.

using the key which acts like an index.

Example: Example:

Express mail package has airbill number Express mail package has airbill number

"D29Z" with a delivery data and destination

"D29Z" with a delivery data and destination

"10/6 Dallas Texas".

"10/6 Dallas Texas".

// get express mail information for // get express mail information for // package with airbill "D29Z" // package with airbill "D29Z"

// package info "10/6 Dallas Texas" // package info "10/6 Dallas Texas"

(9)

Map (continued) Map (continued)

 Can use a tree structure to store the Can use a tree structure to store the elements.

elements.

 A tree is a container whose elements are A tree is a container whose elements are nodes emanating from a root.

nodes emanating from a root.

 Maps use a special type of tree, called a Maps use a special type of tree, called a search tree that allows a program to

search tree that allows a program to

locate an element by searching down a

locate an element by searching down a

(10)

Map (concluded)

Map (concluded)

(11)

Graph Graph

 Set of vertices connected by links, called Set of vertices connected by links, called edges

edges

Edge may have a direction from a source Edge may have a direction from a source vertex to a destination vertex.

vertex to a destination vertex.

Edge may also have a weight defining a Edge may also have a weight defining a property of the edge.

property of the edge.

(12)

Adapter Structrues Adapter Structrues

 Uses an existing data structure like a Uses an existing data structure like a LinkedList to store the elements.

LinkedList to store the elements.

 Example - Queue Example - Queue

A list with two reference points, the front and A list with two reference points, the front and the back. Data enters at the back and exits at the back. Data enters at the back and exits at

the front.

the front.

(13)

Data Structures and Data Structures and

Object-Oriented Programming Object-Oriented Programming

 Modern object-oriented programming is an Modern object-oriented programming is an ideal mechanism for designing and

ideal mechanism for designing and implementing a data structure.

implementing a data structure.

 A collection is an object and the collection A collection is an object and the collection type (class) is the data structure.

type (class) is the data structure.

The object has private members that define The object has private members that define the data.

the data.

(14)

Data Structures and Data Structures and

Object-Oriented Programming Object-Oriented Programming

(continued) (continued)

 Java has good object-oriented design Java has good object-oriented design

constructs that support a modern view of constructs that support a modern view of

data structures.

data structures.

(15)

Data Structures and Data Structures and

Algorithms Algorithms

 Data structures have operations that Data structures have operations that manipulate the data.

manipulate the data.

 The design and implementation of these The design and implementation of these operations involve algorithms that consist operations involve algorithms that consist

of a finite sequence of instructions to of a finite sequence of instructions to

perform a task.

perform a task.

(16)

Data Structures and Data Structures and Algorithms (concluded) Algorithms (concluded)

 The interplay between algorithms and The interplay between algorithms and data structures was highlighted by the data structures was highlighted by the

renowned teacher and scholar, Nicolas renowned teacher and scholar, Nicolas

Wirth, who coined the expression "data Wirth, who coined the expression "data

structures + algorithms = programming."

structures + algorithms = programming."

(17)

Object-Oriented Object-Oriented

Programming Programming

 An object is an entity with data and An object is an entity with data and operations on the data.

operations on the data.

 A class is the type of an object and A class is the type of an object and describes what the object can do.

describes what the object can do.

 Objects are instances of the class. Objects are instances of the class.

 Creating a computer program using Creating a computer program using

(18)

StudentAccount Class

StudentAccount Class

(19)

Understanding a Class Understanding a Class

 Designing a class involves specifying data Designing a class involves specifying data and methods that act on the data that

and methods that act on the data that

allow a programmer to create and use an allow a programmer to create and use an

object in a problem situation.

object in a problem situation.

 The implementation makes the operations The implementation makes the operations of a class work.

of a class work.

(20)

Class Methods Class Methods

A method accepts data values called A method accepts data values called arguments arguments , , carries out calculations, and returns a value.

carries out calculations, and returns a value.

A method may have A method may have preconditions preconditions that must that must apply in order that the operation properly

apply in order that the operation properly executes.

executes.

If a precondition is violated, the method If a precondition is violated, the method identifies the condition and throws an identifies the condition and throws an

exception, which allows the calling statement to exception, which allows the calling statement to

employ some error handling strategy.

employ some error handling strategy.

(21)

Class Methods Class Methods

(concluded) (concluded)

 A method also has A method also has postconditions postconditions that that indicate changes to the object's state indicate changes to the object's state

caused by executing the method.

caused by executing the method.

(22)

Method Signature Method Signature

 Includes the method name, a listing of Includes the method name, a listing of formal parameters that correspond to formal parameters that correspond to

arguments, and the object type of the arguments, and the object type of the

return value.

return value.

The parameter list is a comma-separated The parameter list is a comma-separated sequence of one or more parameter names sequence of one or more parameter names

and data types.

and data types.

(23)

Method Signature Method Signature

(concluded) (concluded)

 May also include an action statement that May also include an action statement that describes the operation and any

describes the operation and any

preconditions and any postconditions preconditions and any postconditions

exist.

exist.

ReturnType methodName(Type1 param1, Type2 param2, ...) Action statement

(24)

Time24 Class Design Time24 Class Design

 A Time24 object has integer data A Time24 object has integer data

variables, hour and minute, where the variables, hour and minute, where the

hour is in the range 0 to 23 and minute is hour is in the range 0 to 23 and minute is

in the range 0 to 59.

in the range 0 to 59.

 The interface has methods to access and The interface has methods to access and update the data members and to create a update the data members and to create a

formatted string that describes the current formatted string that describes the current

time.

time.

(25)

Time24 Methods Time24 Methods

addTime:

void addTime(int m)

Updates the time for this object by the specified number of minutes. The hour and minute values are normalized so that hour is in the range 0 to 23 and minute is in the

range 0 to 59.

Example: Assume t is a Time24 object with time 15:45 (3:45 PM).

The statement

t.addTime(30);

calls addTime with argument 30 and increments the time for t to 16:15.

(26)

Time24 Methods Time24 Methods

(continued) (continued)

The method interval(t) measures the time gap between the current hour and minute of the object and next 24-hour occurrence of a Time24 argument t. The result is a Time24 object that becomes the return value.

interval:

Time24 interval(Time24 t)

Returns a Time24 object that specifies length of time from the current hour and minute to the next 24-hour occurrence of time t.

(27)

Time24 Methods Time24 Methods

(concluded) (concluded)

Example: Use Time24 objects tA, tB, and tC. Object tA has current time 14:45 (2:45 PM) and object tB has current time 16:15 (4:15 PM).

(28)

Constructors Constructors

A A constructor constructor allocates memory for an object and allocates memory for an object and initializes the data values.

initializes the data values.

The method signature for a constructor uses the The method signature for a constructor uses the class name as the method name and does not class name as the method name and does not

have a return type.

have a return type.

A class can provide a variety of constructors by A class can provide a variety of constructors by using different parameter lists.

using different parameter lists.

The The default constructor default constructor that has an empty that has an empty

parameter list and assigns default values to the parameter list and assigns default values to the

data.

data.

(29)

Time24 Constructors Time24 Constructors

Time24()

The default constructor initializes the hour and minute to be 0. The time is midnight (0:00)

Time24(int hour, int minute)

The object is initialized with the specified hour and minute.

The values of the data members are normalized to their proper range.

Example:

Time24() // object is 0:00 Time24(4,45) // object is 4:45

(30)

The toString Method The toString Method

 A class typically provides a method, A class typically provides a method,

toString(), which describes the state of the toString(), which describes the state of the

object.

object.

The return type is a String containing some The return type is a String containing some formatted representation of the object.

formatted representation of the object.

Time24 class toString():

String toString()

Returns a string that describes the time of the

(31)

Time24 Class toString Time24 Class toString

Example Example

Assume t is a Time24 object with hour 14 and minute 45.

Use the method toString() and System.out.print() for console output.

System.out.print("Time t is " + t.toString());

Output: Time t is 14:45

(32)

Accessor Methods Accessor Methods

 In general, a program may not directly In general, a program may not directly access the data in an object.

access the data in an object.

 An An accessor method accessor method returns the current returns the current value for an object's data field and

value for an object's data field and typically begins with the word

typically begins with the word get get . .

Time24 Class Accessors

getHour():

int getHour()

Returns the hour value for the object getMinute():

(33)

Mutator Methods Mutator Methods

 A A mutator method mutator method allows a program to allows a program to update the value for one or more data update the value for one or more data

fields in the object. The method name fields in the object. The method name

typically begins with the word

typically begins with the word set set

Time24 Class Mutator

setTime:

void setTime(int hour, int minute)

The arguments update the corresponding data values in the object.

(34)

Mutator Methods Mutator Methods

(concluded) (concluded)

Example :

The methods getHour(), getMinute(), and setTime() combine to move the clock forward one hour This is equivalent to addTime(60).

t.setTime(t.getHour() + 1, t.getMinute())

(35)

Static Methods Static Methods

Object methods access and update the data fields of an object.

The design of a class can include

independent methods that are not bound to any specific object. Their signatures include the modifier static .

These operations are referred to as class or

static methods. They are called by using the

(36)

Time24 Static Method Time24 Static Method

Time24 Example:

parseTime():

static Time24 parseTime(String s)

The method takes a string s in the form hh:mm and returns an object with the equivalent Time24 value.

// t has value 13:45 (1:45 PM) t = Time24.parseTime("13:45");

(37)

Declaring Objects Declaring Objects

 You must make a reference variable refer You must make a reference variable refer to an actual object y assigning it a value to an actual object y assigning it a value

returned by the new operator that calls a returned by the new operator that calls a

constructor to create an object.

constructor to create an object.

Example:

Time24 t;

// creates object with time midnight t = new Time24();

// creates object with time 15:30 t = new Time24(15,30);

(38)

Using Object Methods Using Object Methods

 Once an object is created, a program can Once an object is created, a program can call any of its interface methods.

call any of its interface methods.

 The syntax uses the object reference and The syntax uses the object reference and the method name separated by a "." (dot).

the method name separated by a "." (dot).

The method should include zero or more The method should include zero or more

arguments enclosed in parentheses.

arguments enclosed in parentheses.

// call addTime(45) which advances time for t // 45 minutes; t becomes 16:15

(39)

The Keyword null The Keyword null

An object reference variable can be initially An object reference variable can be initially set to null.

set to null.

The value is a special constant that can be The value is a special constant that can be used to give a value to any variable of class used to give a value to any variable of class type. It indicates that the variable does not type. It indicates that the variable does not

yet reference an actual object.

yet reference an actual object.

The runtime system identifies any attempt to The runtime system identifies any attempt to call an object method when the reference

call an object method when the reference

variable has value null as an error.

(40)

References and Aliases References and Aliases

 An assignment statement with primitive An assignment statement with primitive

variables copies the value of the right-side variables copies the value of the right-side

to the left-side variable. The result is two to the left-side variable. The result is two

variables in separate memory locations variables in separate memory locations

but with the same value.

but with the same value.

int m = 5, n;

n = m;

(41)

References and Aliases References and Aliases

(concluded) (concluded)

 Assignment also applies to reference Assignment also applies to reference variables, but the results are different variables, but the results are different

from assignment of primitive variables.

from assignment of primitive variables.

(42)

Assignment of Reference Assignment of Reference

Variables Variables

Time24 tA = new Time24(14,15), tB;

tB = tA;

The result is two separate reference variables tA and tB both pointing to the same object. Using any update method with either variable changes the state of the single object

they reference.

(43)

import ds.time.Time24;

public class Program1_1 {

public static void main(String[] args) {

// Time24 reference variables // game 1:15 PM

Time24 startGame = new Time24(13,15), // length 3:23

timeOfGame = new Time24(3,23),

PROGRAM 1-1 PROGRAM 1-1

Time24 Broadcast Times

Time24 Broadcast Times

(44)

// create object for endGame, with same time // as startGame; update it by adding the

// time for the game in minutes.

endGame =

new Time24(startGame.getHour(), startGame.getMinute());

// declare an integer that stores length of // game in minutes

int minutesOfGame =

timeOfGame.getHour()*60 + timeOfGame.getMinute();

// advance time of endGame using addTime() endGame.addTime(minutesOfGame);

// assign interval() to variable

PROGRAM 1-1 (continued)

PROGRAM 1-1 (continued)

(45)

// output

System.out.println("The game begins at " + startGame);

System.out.println("The game ends at " + endGame);

System.out.println("Post game interviews" + last " +

timeForInterviews);

} }

PROGRAM 1-1 (concluded)

PROGRAM 1-1 (concluded)

(46)

API (

API ( A A pplication pplication P P rogramming rogramming I I nterface) nterface)

 Summary of the class design. Summary of the class design.

 Begins with a header that includes the Begins with a header that includes the class name and the package name.

class name and the package name.

 Separate listing of class constructors and Separate listing of class constructors and interface methods.

interface methods.

 Allows an application programmer to Allows an application programmer to

create a class object and employ its

create a class object and employ its

(47)

API (concluded) API (concluded)

 Programmer can use an API to understand Programmer can use an API to understand a class as a toolkit without reference to its a class as a toolkit without reference to its

implementation details.

implementation details.

(48)

Time24 Class API

Time24 Class API

(49)

Time24 Class API Time24 Class API

(continued)

(continued)

(50)

Time24 Class API Time24 Class API

(concluded)

(concluded)

(51)

U U nified nified M M odeling odeling L L anguage anguage (UML)

(UML)

 Gives a graphical representation of classes Gives a graphical representation of classes and their interaction.

and their interaction.

 Has three compartments that provide the Has three compartments that provide the class name, the instance variables and their class name, the instance variables and their

types, and the signature for each method.

types, and the signature for each method.

 Each member of the class begins with the Each member of the class begins with the symbol '+' or '-' indicating the visibility

symbol '+' or '-' indicating the visibility

(52)

UML Representation of the UML Representation of the

Time24 Class

Time24 Class

(53)

Information Hiding Information Hiding

 Visibility modifiers Visibility modifiers private private and and public public . .

 A visibility modifier is included in the A visibility modifier is included in the

declaration of the class header and in the declaration of the class header and in the

declaration of each class member.

declaration of each class member.

 The public modifier in the class header The public modifier in the class header indicates that the class, and hence

indicates that the class, and hence

instances, are available to an application instances, are available to an application

class outside of the package.

class outside of the package.

(54)

Information Hiding Information Hiding

(concluded) (concluded)

 For class members, the public modifier For class members, the public modifier

specifies that the member is accessible by specifies that the member is accessible by

any instance of the class. The public any instance of the class. The public

members represent the class interface.

members represent the class interface.

 The private modifier typically applies to the The private modifier typically applies to the data in the class and to utility methods that data in the class and to utility methods that

support the class implementation. Only support the class implementation. Only

methods of the class can access private

methods of the class can access private

(55)

Access Rights to Public and Access Rights to Public and

Private Members of a Class

Private Members of a Class

(56)

Time24 Class Declaration Time24 Class Declaration

public class Time24 {

// hour in the range 0 to 23 private int hour;

// minute in the range 0 to 59 private int minute;

// utility method sets hour and minute in // their proper range

private void normalizeTime() { . . . } // constructors

public Time24() { . . . }

public Time24(int hour, int minute) { . . . } // methods that increment time and identify // time intervals

public void addTime(int m) { . . . }

(57)

Time24 Class Declaration Time24 Class Declaration

(concluded) (concluded)

// accessor and mutator methods for the two // variables

public int getHour() { . . . } public int getMinute() { . . . }

public void setTime(int hour, int minute) { . . . }

// string that describes the object public String toString() { . . . }

// static method converts a string to a // Time24 object

public static Time24 parseTime(String s)

(58)

Private Methods Private Methods

Make the implementation of public methods Make the implementation of public methods more efficient and easier to read.

more efficient and easier to read.

Used only within the class implementation and Used only within the class implementation and are not part of the interface.

are not part of the interface.

Decompose a complex public method into Decompose a complex public method into

subtasks which are handled by private methods.

subtasks which are handled by private methods.

Use a private method to carry out a task that Use a private method to carry out a task that must be repeated many times during the

must be repeated many times during the implementation of the class.

implementation of the class.

(59)

Time24 Class Time24 Class Private Method Private Method

normalizeTime():

// utility method sets the hour value // in the range 0 to 23 and the minute // value in the range 0 to 59

private void normalizeTime() {

int extraHours = minute / 60;

// set minute in range 0 to 59 minute %= 60;

// update hour. set in range 0 to 23 hour = (hour + extraHours) % 24;

(60)

Time24 Class Time24 Class

Accessor Methods Accessor Methods

getHour():

// return the current value of the // instance variable hour

public int getHour() { return hour; }

getMinute():

// return the current value of the // instance variable minute

public int getMinute() { return minute; }

(61)

Time24 Class Time24 Class Mutator Method Mutator Method

public void setTime(int hour, int minute) {

// check that arguments hour and // minute are positive

if (hour < 0 || minute < 0) throw new

IllegalArgumentException ("Time24 setTime: " + "parameters must be" + "positive integers");

(62)

Time24 Class Time24 Class

Mutator Method (concluded) Mutator Method (concluded)

// assign new values // normalizeTime() this.hour = hour;

this.minute = minute;

// adjust hour and minute as necessary normalizeTime();

}

(63)

Constructor Constructor

 A public method that uses the class name A public method that uses the class name to identify the method and may not have to identify the method and may not have

a return type.

a return type.

 Has a parameter list specifying arguments Has a parameter list specifying arguments that initialize the object.

that initialize the object.

(64)

Time24 Constructors Time24 Constructors

Constructor Time24(h,m):

// constructor creates an instance // with values hour and minute.

public Time24(int hour, int minute) {

setTime(hour,minute);

}

Default constructor Time24():

// constructor creates an instance // set to midnight

public Time24() {

this(0,0);

(65)

Time24 Time24 toString() toString()

Time24 toString():

public String toString() {

// create a text format object // with two character positions // and fill character 0

DecimalFormat fmt =

new DecimalFormat("00");

return new String(hour + ":" + fmt.format(minute));

(66)

Incrementing Time Incrementing Time

addTime():

public void addTime(int m) {

if (m < 0) throw new

IllegalArgumentException

("Time24.setTime: argument" + " must be a positive " +

"integer");

minute += m;

normalizeTime();

}

(67)

Time24 Interval Time24 Interval

interval():

// return the length of time from the current time to // time t

public Time24 interval(Time24 t) {

// convert current time and time // t to minutes

int currTime = hour * 60 + minute;

int tTime = t.hour * 60 + t.minute;

(68)

Time24 Interval Time24 Interval

(concluded) (concluded)

// if t is an earlier time, then // add 24 hours so that t

// represents a time in the // "next day"

if (tTime < currTime) tTime += 24 * 60;

// return a reference to a new // Time24 object

return

new Time24(0, tTime-currTime);

}

(69)

Package Package

 Group of related classes stored in a Group of related classes stored in a directory and made accessible to

directory and made accessible to programs using

programs using import import statements. statements.

 Promotes code reuse. Promotes code reuse.

(70)

Package (concluded) Package (concluded)

 Place a class in a package by adding a Place a class in a package by adding a package header at the beginning of the package header at the beginning of the

source code file and then placing the file source code file and then placing the file

in a directory with the same name as the in a directory with the same name as the

package name.

package name.

package DemoPackage;

public class DemoClass { . . . }

(71)

Importing a Class Importing a Class

 Import a specific class Import a specific class

import DemoPackage.DemoClass;import DemoPackage.DemoClass;

 Import all classes in a package Import all classes in a package

import DemoPackage.*;

import DemoPackage.*;

(72)

Book Software Book Software

Resides in the directory "ftjavads" which Resides in the directory "ftjavads" which contains subdirectories "programs" and contains subdirectories "programs" and

"packages".

"packages".

Programs directory contains subdirectories Programs directory contains subdirectories for each chapter in the book.

for each chapter in the book.

Packages directory defines a "ds" Packages directory defines a "ds"

subdirectory which branches to directories subdirectory which branches to directories

corresponding to the packages graphics,

corresponding to the packages graphics,

(73)

Book Software Book Software

(concluded) (concluded)

 The util package contains the collection The util package contains the collection classes and libraries that are introduced classes and libraries that are introduced

throughout the book.

throughout the book.

(74)

Organization of the Software Organization of the Software

Supplement

Supplement

(75)

The Java Software The Java Software

Development Kit Development Kit

 java.lang - Contains the basic classes java.lang - Contains the basic classes needed for developing Java programs.

needed for developing Java programs.

This includes the String class and the This includes the String class and the

System class.

System class.

 java.util - Provides the Collections java.util - Provides the Collections

Framework classes, the Random class, the Framework classes, the Random class, the

StringTokenizer class, and classes dealing

StringTokenizer class, and classes dealing

(76)

The Java Software The Java Software

Development Kit (concluded) Development Kit (concluded)

 java.io - Classes manage the input and java.io - Classes manage the input and output of data.

output of data.

 Many other packages. Many other packages.

(77)

Strings Strings

 A sequence of characters that programs A sequence of characters that programs use to identify names, words, and

use to identify names, words, and sentences.

sentences.

 String class in the "java.lang" package. String class in the "java.lang" package.

(78)

String Literals String Literals

String city = "Phoenix";

String city = "Phoenix";

String[] weekdays = {"Mon", "Tue", "Wed", "Thu", "Fri"};

String[] weekdays = {"Mon", "Tue", "Wed", "Thu", "Fri"};

(79)

String Indexing String Indexing

String str = "this string has vowels";

char ch;

System.out.println("Length is " + str.length());

for (int i=0; i < str.length(); i++) {

ch = str.charAt(i);

if (ch == 'a' || ch == 'e' ||

ch == 'i' || ch == 'o' || ch == 'u') System.print(ch + " ");

}

Output: Length is 22 i i a o e

(80)

String Concatentation String Concatentation

String strA = "down", strB = "town", strC;

strC = strA + strB; // strC is "downtown"

// strA is "down periscope"

strA += " periscope";

(81)

String Comparison String Comparison

using equals() using equals()

String strA = "goodbye";

boolean b;

// b is true

b = strA.equals("good"+"bye");

// b is false

b = strA.equals("goodby");

(82)

String Comparison String Comparison using compareTo() using compareTo()

Return value from compareTo(anotherStr)

anotherStr thisStr

anotherStr thisStr

anotherStr thisStr

0 0 0



String s1 = "John", s2 = "Johnson";

// John < Johnson is true s1.compareTo(s2) < 0

// Johnson >= Mike is false

(83)

Enum Type Enum Type

 Facility that allows a program to define a Facility that allows a program to define a special kind of class whose members are special kind of class whose members are

named constants.

named constants.

 The class has a simple declaration the The class has a simple declaration the uses the keyword enum followed by the uses the keyword enum followed by the

name and a list of identifiers enclosed in name and a list of identifiers enclosed in

braces.

braces.

(84)

Enum Types Enum Types

(concluded) (concluded)

 An enum type has the method toString() An enum type has the method toString() which returns the constant name and the which returns the constant name and the

operator == which determines whether operator == which determines whether

two values are the same.

two values are the same.

 The method compareTo() compares two The method compareTo() compares two enum values using the order of names in enum values using the order of names in

the enum declaration.

the enum declaration.

(85)

Enum Example Enum Example

// declare two variables of type enum Season // and initialize the variables

Season s = Season.winter, t = Season.spring;

// equals() tests the value of s

if (s == Season.winter || s == Season.spring) System.out.println("In " + s +

" economy fares apply");

// compareTo() affirms the ordering of the // seasons

if (s.compareTo(t) < 0)

System.out.println(s + " comes before " + t);

Referensi

Garis besar

Dokumen terkait

The Embodiment of Mahakrya Lango Film The embodiment in the Mahakrya Lango film begins with determining the set of locations chosen, namely Lake Tamblingan to visualize water as a