15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

326<br />

Drawbacks of Arrays<br />

To get around the problem of creating large arrays that aren’t needed, you<br />

can create resizable or dynamic arrays that can grow or shrink as you need<br />

them (see the earlier section, “Working with Resizable Arrays”). Such resizable<br />

arrays can be convenient, but you have to make sure that each time you<br />

resize an array, you don’t accidentally delete data that you want to keep.<br />

Data types<br />

Another limitation of arrays is that they can hold only one data type at a<br />

time. So if you want to store a list of names and numbers, you have to create<br />

two separate arrays:<br />

✦ One array to store the names<br />

✦ Another array to store the numbers<br />

Some <strong>programming</strong> languages allow you to create a data type called a<br />

variant. A variant data type can hold any type of data, so if you create an<br />

array of variant data types, you can create an array that can hold both<br />

strings and numbers.<br />

Searching and sorting<br />

Another problem with arrays is searching and sorting an array. If you create<br />

an array to hold 10,000 names, how can you find the name Bill Gates<br />

stored in that array? To search <strong>for</strong> data stored in an array, you have to<br />

search through the entire array from start to finish. For a small array, this<br />

can be acceptable, but searching through an array that contains thousands<br />

of names or numbers can get tedious and slow, especially if you need to<br />

search through an array on a regular basis.<br />

So if an array contains 10,000 names and the name you want is the last element<br />

in that array, you have to search through 10,000 array elements just to<br />

find the name you want.<br />

More cumbersome than searching an array is sorting an array. If you store<br />

10,000 names in an array and suddenly decide you want to sort those names<br />

in alphabetical order, you have to move and sort the entire list one array element<br />

at a time. Doing this once may be acceptable, but doing this on a regular<br />

basis can be cumbersome and slow.<br />

Adding and deleting<br />

Rather than dump all your data in an array and try to sort it out later, you<br />

might want to sort data while you store it. Adding data to an empty array is<br />

easy; dump the data in any array element. The problem comes when you<br />

want to add data in between two array elements.

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

Saved successfully!

Ooh no, something went wrong!