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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The ability of perform<strong>in</strong>g narrow<strong>in</strong>g conversions from <strong>in</strong>terface types to class<br />

types allows us to write general k<strong>in</strong>ds of data structures that only make m<strong>in</strong>imal<br />

assumptions about the elements they store. In Code Fragment 2.14, we sketch<br />

how to build a directory stor<strong>in</strong>g pairs of objects implement<strong>in</strong>g the Person<br />

<strong>in</strong>terface. The remove method performs a search on the directory contents <strong>and</strong><br />

removes the specified person pair, if it exists, <strong>and</strong>, like the f<strong>in</strong>dOther method,<br />

it uses the equalTo method to do this.<br />

Code Fragment 2.14<br />

PersonPairDirectory.<br />

: Sketch of class<br />

Now, suppose we have filled a directory, myDirectory, with pairs of<br />

Student objects that represent roommate pairs. In order to f<strong>in</strong>d the roommate of<br />

a given Student object, smart_one, we may try to do the follow<strong>in</strong>g (which is<br />

wrong):<br />

Student cute_one = myDirectory.f<strong>in</strong>dOther(smart_one);<br />

// wrong!<br />

The statement above causes an "explicit-cast-required" compilation error. The<br />

problem here is that we are try<strong>in</strong>g to perform a narrow<strong>in</strong>g conversion without an<br />

explicit cast. Namely, the value returned by method f<strong>in</strong>dOther is of type<br />

Person while the variable cute_one, to which it is assigned, is of the<br />

narrower type Student, a class implement<strong>in</strong>g <strong>in</strong>terface Person. Thus, we use<br />

a cast to convert type Person to type Student, as follows:<br />

Student cute_one = (Student)<br />

myDirectory.f<strong>in</strong>dOther(smart_one);<br />

Cast<strong>in</strong>g the value of type Person returned by method f<strong>in</strong>dOther to type<br />

Student works f<strong>in</strong>e as long as we are sure that the call to<br />

myDirectory.f<strong>in</strong>dOther is really giv<strong>in</strong>g us a Student object. In general,<br />

<strong>in</strong>terfaces can be a valuable tool for the design of general data structures, which<br />

can then be specialized by other programmers through the use of cast<strong>in</strong>g.<br />

2.5.2 Generics<br />

126

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

Saved successfully!

Ooh no, something went wrong!