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.

A Class for High Scores<br />

Suppose we have some high scores that we want to store <strong>in</strong> an array named<br />

entries. The number of scores we want to store could be 10, 20, or 50, so let us<br />

use a symbolic name, maxEntries, which represents the number of scores we<br />

want to store. We must set this variable to a specific value, of course, but by us<strong>in</strong>g<br />

this variable throughout our code, we can make it easy to change its value later if<br />

we need to. We can then def<strong>in</strong>e the array, entries, to be an array of length<br />

maxEntries. Initially, this array stores only nullentries, but as users play<br />

our video game, we will fill <strong>in</strong> the entries array with entries, but as users play<br />

our video game, we will fill <strong>in</strong> the entries array with references to new<br />

GameEntry objects. So we will eventually have to def<strong>in</strong>e methods for updat<strong>in</strong>g<br />

the GameEntry references <strong>in</strong> the entries array.<br />

The way we keep the entries array organized is simple—we store our set of<br />

GameEntry objects ordered by their <strong>in</strong>teger score values, highest to lowest. If<br />

the number of GameEntry objects is less than maxEntries, then we let the<br />

end of the entries array store null references. This approach prevents hav<strong>in</strong>g<br />

any empty cells, or "holes," <strong>in</strong> the cont<strong>in</strong>uous series of cells of array entries<br />

that store the game entries from <strong>in</strong>dex 0 onward. We illustrate an <strong>in</strong>stance of the<br />

data structure <strong>in</strong> Figure 3.1 <strong>and</strong> we give <strong>Java</strong> code for such a data structure <strong>in</strong><br />

Code Fragment 3.2. In an exercise (C-3.1), we explore how game entry addition<br />

might be simplified for the case when we don't need to preserve relative orders.<br />

141

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

Saved successfully!

Ooh no, something went wrong!