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.

Note that we <strong>in</strong>clude a method, toStr<strong>in</strong>g(), which produces a str<strong>in</strong>g<br />

representation of the high scores <strong>in</strong> the entries array. This method is quite<br />

useful for debugg<strong>in</strong>g purposes. In this case, the str<strong>in</strong>g will be a comma-separated<br />

list<strong>in</strong>g of the GameEntry objects <strong>in</strong> the entries array. We produce this list<strong>in</strong>g<br />

with a simple for-loop, which adds a comma just before each entry that comes<br />

after the first one. With such a str<strong>in</strong>g representation, we can pr<strong>in</strong>t out the state of<br />

the entries array dur<strong>in</strong>g debugg<strong>in</strong>g, for test<strong>in</strong>g how th<strong>in</strong>gs look before <strong>and</strong><br />

after we make updates.<br />

Insertion<br />

One of the most common updates we might want to make to the entries array<br />

of high scores is to add a new game entry. So suppose we want to <strong>in</strong>sert a new<br />

GameEntry object, e. In particular, let us consider how we might perform the<br />

follow<strong>in</strong>g update operation on an <strong>in</strong>stance of the Scores class:<br />

add(e): Insert game entry e <strong>in</strong>to the collection of high scores. If the<br />

collection is full, then e is added only if its score is higher than the lowest score <strong>in</strong><br />

the set, <strong>and</strong> <strong>in</strong> this case, e replaces the entry with the lowest score.<br />

The ma<strong>in</strong> challenge <strong>in</strong> implement<strong>in</strong>g this operation is figur<strong>in</strong>g out where e should<br />

go <strong>in</strong> the entries array <strong>and</strong> mak<strong>in</strong>g room for e.<br />

143

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

Saved successfully!

Ooh no, something went wrong!