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.

Clon<strong>in</strong>g an Array<br />

If <strong>in</strong>stead, we wanted to create an exact copy of the array, a, <strong>and</strong> assign that array<br />

to the array variable, b, we should write<br />

b = a.clone();<br />

which copies all of the cells of a <strong>in</strong>to a new array <strong>and</strong> assigns b to po<strong>in</strong>t to that<br />

new array. In fact, the clone method is a built-<strong>in</strong> method of every <strong>Java</strong> object,<br />

which makes an exact copy of that object. In this case, if we then write<br />

b[3] = 5;<br />

then the new (copied) array will have its cell at <strong>in</strong>dex 3, assigned the value 5, but<br />

a[3] will rema<strong>in</strong> unchanged. We illustrate this po<strong>in</strong>t <strong>in</strong> Figure 1.8.<br />

Figure 1.8: An illustration of clon<strong>in</strong>g of array objects.<br />

We show the result of sett<strong>in</strong>g "b[3] = 5;" after<br />

previously sett<strong>in</strong>g "b = a.clone();".<br />

We should stress that the cells of an array are copied when we clone it. If the cells<br />

are a base type, like <strong>in</strong>t, their values are copied. But if the cells are object<br />

references, then those references are copied. This means that there are now two<br />

64

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

Saved successfully!

Ooh no, something went wrong!