27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

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.

<strong>Solutions</strong> to Chapter 14 | Java<br />

14.6 Suppose you are using a map in your program, how would you count <strong>the</strong> number of<br />

times <strong>the</strong> program calls <strong>the</strong> put() <strong>and</strong> get() functions?<br />

SOLUTION<br />

pg 78<br />

One simple solution is to put count variables for get() <strong>and</strong> put() methods <strong>and</strong>, whenever <strong>the</strong>y<br />

are called, increment <strong>the</strong> count. We can also achieve this by extending <strong>the</strong> existing library<br />

map <strong>and</strong> overriding <strong>the</strong> get() <strong>and</strong> put() functions.<br />

At first glance, this seems to work. However, what if we created multiple instances of <strong>the</strong><br />

map? How would you sum up <strong>the</strong> total count for each map object?<br />

The simplest solution for this is to keep <strong>the</strong> count variables static. We know static variables<br />

have only one copy for all objects of <strong>the</strong> class so <strong>the</strong> total count would be reflected in count<br />

variables.<br />

CareerCup.com<br />

2 3 0

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

Saved successfully!

Ooh no, something went wrong!