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.

The cells of this new array, "a," are <strong>in</strong>dexed us<strong>in</strong>g the <strong>in</strong>teger set {0,1,2,… ,9}<br />

(recall that arrays <strong>in</strong> <strong>Java</strong> always start <strong>in</strong>dex<strong>in</strong>g at 0), <strong>and</strong>, like every array <strong>in</strong> <strong>Java</strong>,<br />

all the cells <strong>in</strong> this array are of the same type—double.<br />

1.5.2 Arrays are Objects<br />

Arrays <strong>in</strong> <strong>Java</strong> are special k<strong>in</strong>ds of objects. In fact, this is the reason we can use the<br />

new operator to create a new <strong>in</strong>stance of an array. An array can be used just like<br />

any general object <strong>in</strong> <strong>Java</strong>, but we have a special syntax (us<strong>in</strong>g square brackets, "["<br />

<strong>and</strong> "]") to refer to its members. An array <strong>in</strong> <strong>Java</strong> can do everyth<strong>in</strong>g that a general<br />

object can. S<strong>in</strong>ce an array is an object, though, the name of an array <strong>in</strong> <strong>Java</strong> is<br />

actually a reference to the place <strong>in</strong> memory where the array is stored. Thus, there is<br />

noth<strong>in</strong>g too special about us<strong>in</strong>g the dot operator <strong>and</strong> the <strong>in</strong>stance variable, length, to<br />

refer to the length of an array, for example, as "a.length." The name, a, <strong>in</strong> this<br />

case is just a reference, or po<strong>in</strong>ter, to the underly<strong>in</strong>g array object.<br />

The fact that arrays <strong>in</strong> <strong>Java</strong> are objects has an important implication when it comes<br />

to us<strong>in</strong>g array names <strong>in</strong> assignment statements. For when we write someth<strong>in</strong>g like<br />

b = a;<br />

<strong>in</strong> a <strong>Java</strong> program, we really mean that b <strong>and</strong> a now both refer to the same array.<br />

So, if we then write someth<strong>in</strong>g like<br />

b[3] = 5;<br />

then we will also be sett<strong>in</strong>g the number a [3] to 5. We illustrate this crucial po<strong>in</strong>t <strong>in</strong><br />

Figure 1.7.<br />

Figure 1.7: An illustration of an assignment of array<br />

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

after previously sett<strong>in</strong>g "b = a;".<br />

63

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

Saved successfully!

Ooh no, something went wrong!