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.

top(k):<br />

Return an iterable collection of the k most accessed elements.<br />

6.5.1 Us<strong>in</strong>g a Sorted List <strong>and</strong> a Nested Class<br />

The first implementation of a favorite list that we consider (<strong>in</strong> Code Fragments<br />

6.19–6.20) is to build a class, FavoriteList, stor<strong>in</strong>g references to accessed<br />

objects <strong>in</strong> a l<strong>in</strong>ked list ordered by non<strong>in</strong>creas<strong>in</strong>g access counts. This class also uses<br />

a feature of <strong>Java</strong> that allows us to def<strong>in</strong>e a related class nested <strong>in</strong>side an enclos<strong>in</strong>g<br />

class def<strong>in</strong>ition. Such a nested class must be declared static, to <strong>in</strong>dicate that this<br />

def<strong>in</strong>ition is related to the enclos<strong>in</strong>g class, not any specific <strong>in</strong>stance of that class.<br />

Us<strong>in</strong>g nested classes allows us to def<strong>in</strong>e "helper" or "support" classes that can be<br />

protected from outside use.<br />

In this case, the nested class, Entry, stores, for each element e <strong>in</strong> our list, a pair<br />

(c,v), where c is the access count for e <strong>and</strong> v is a value reference to the element e<br />

itself. Each time an element is accessed, we f<strong>in</strong>d it <strong>in</strong> the l<strong>in</strong>ked list (add<strong>in</strong>g it if it is<br />

not already there) <strong>and</strong> <strong>in</strong>crement its access count. Remov<strong>in</strong>g an element amounts to<br />

f<strong>in</strong>d<strong>in</strong>g it <strong>and</strong> tak<strong>in</strong>g it out of our l<strong>in</strong>ked list. Return<strong>in</strong>g the k most accessed<br />

elements simply <strong>in</strong>volves our copy<strong>in</strong>g the entry values <strong>in</strong>to an output list accord<strong>in</strong>g<br />

to their order <strong>in</strong> the <strong>in</strong>ternal l<strong>in</strong>ked list.<br />

Code Fragment 6.19: Class FavoritesList.<br />

(Cont<strong>in</strong>ues <strong>in</strong> Code Fragment 6.20.)<br />

356

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

Saved successfully!

Ooh no, something went wrong!