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.

time. However, methods addFirst <strong>and</strong> removeFirst of the deque each run<br />

<strong>in</strong> O(n) time.<br />

Actually, with a little effort, we can produce an array-based implementation of the<br />

array list ADT that achieves O(1) time for <strong>in</strong>sertions <strong>and</strong> removals at <strong>in</strong>dex 0, as<br />

well as <strong>in</strong>sertions <strong>and</strong> removals at the end of the array list. Achiev<strong>in</strong>g this requires<br />

that we give up on our rule that an element at <strong>in</strong>dex i is stored <strong>in</strong> the array at <strong>in</strong>dex<br />

i, however, as we would have to use a circular array approach like the one we<br />

used <strong>in</strong> Section 5.2 to implement a queue. We leave the details of this<br />

implementation for an exercise (C-6.9).<br />

6.1.4 A Simple Interface <strong>and</strong> the java. util. ArrayList Class<br />

To prepare for construct<strong>in</strong>g a <strong>Java</strong> implementation of the array list ADT, we show,<br />

<strong>in</strong> Code Fragment 6.2, a <strong>Java</strong> <strong>in</strong>terface, IndexList, that captures the ma<strong>in</strong><br />

methods from the array list ADT. In this case, we use a<br />

IndexOutOfBoundsException to signal an <strong>in</strong>valid <strong>in</strong>dex argument.<br />

Code Fragment 6.2:<br />

the array list ADT.<br />

The IndexList <strong>in</strong>terface for<br />

The java.util.ArrayList Class<br />

<strong>Java</strong> provides a class, java.util.ArrayList, that implements all the<br />

methods that we give above for our array list ADT. That is, it <strong>in</strong>cludes all of the<br />

methods <strong>in</strong>cluded <strong>in</strong> Code Fragment 6.2 for the IndexList <strong>in</strong>terface.<br />

320

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

Saved successfully!

Ooh no, something went wrong!