Section 9.1. Introduction


[Page 406]

9.1. Introduction

In this chapter we will learn about arrays. An array is a named collection of contiguous storage locationsstorage locations that are next to each otherthat contain data items of the same type.

Arrays offer a more streamlined way to store data than using individual data items for each variable. Arrays also allow you to work with their data more efficiently than with data stored in individual variables.

Let's see why. Suppose you want to create a GUI that has 26 buttons on it, one for each letter of the alphabet. Given our present knowledge of Java, our only alternative would be to declare a separate JButton variable for each letter of the alphabet:

JButton button1; JButton button2; ... JButton button26; 


Obviously, requiring 26 separate variables for this problem is tedious and inconvenient. Similarly, to instantiate and assign a label to each button would require 26 statements:

button1 = new JButton("A"); button2 = new JButton("B"); ... button26 = new JButton("Z"); 


This approach is also tedious. What we need is some way to use a loop to process each button, using a loop counter, k, to refer to the kth button on each iteration of the loop. An array lets us do that. For example, the following code will declare an array for storing 26 JButtons and then instantiate and label each button:

JButton letter[]  = new JButton[26]; for (int k = 0; k < 26; k++)     letter[k] = new JButton("A" + k); 


You don't yet understand the code in this segment, but you can see how economical it is. It uses just three lines of code to do what would have required 50 or 60 lines of code without arrays.

Our discussion of arrays will show how to store and retrieve data from one-, two-, and three-dimensional arrays. We also study sorting and searching algorithms to process arrays. Finally, we illustrate how arrays can be used in a variety of applications, including an animation problem, a sorting class, and a card-playing program.

The array data structure





Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net