23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

In addition, we must def<strong>in</strong>e exceptions for any error conditions that can arise. For<br />

<strong>in</strong>stance, the error condition that occurs when call<strong>in</strong>g method pop() or top()<br />

on an empty stack is signaled by throw<strong>in</strong>g an exception of type<br />

EmptyStackException, which is def<strong>in</strong>ed <strong>in</strong> Code Fragment 5.1.<br />

Code Fragment 5.1: Exception thrown by methods<br />

pop() <strong>and</strong> top() of the Stack <strong>in</strong>terface when called<br />

on an empty stack.<br />

A complete <strong>Java</strong> <strong>in</strong>terface for the stack ADT is given <strong>in</strong> Code Fragment 5.2. Note<br />

that this <strong>in</strong>terface is very general s<strong>in</strong>ce it specifies that elements of any given class<br />

(<strong>and</strong> its subclasses) can be <strong>in</strong>serted <strong>in</strong>to the stack. It achieves this generality by<br />

us<strong>in</strong>g the concept of generics (Section 2.5.2).<br />

For a given ADT to be of any use, we need to provide a concrete class that<br />

implements the methods of the <strong>in</strong>terface associated with that ADT. We give a<br />

simple implementation of the Stack <strong>in</strong>terface <strong>in</strong> the follow<strong>in</strong>g subsection.<br />

Code Fragment 5.2: Interface Stack documented<br />

with comments <strong>in</strong> <strong>Java</strong>doc style (Section 1.9.3). Note<br />

also the use of the generic parameterized type, E,<br />

which implies that a stack can conta<strong>in</strong> elements of any<br />

specified class.<br />

265

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!