Java Reference
In-Depth Information
all of the space in an array, Java enables you to move the data to a larger array. The effect is to have
an array that apparently expands to meet your needs. Thus, we can have a bag that is never full.
Using a Fixed-Size Array to Implement the ADT Bag
Our task is to define the methods we specified in the previous chapter when we wrote the interface
BagInterface . We begin by using an analogy to describe how a fixed-size array could contain the
entries in a bag. In doing so, we show how the add and remove methods would work. Subsequently,
we present a corresponding Java implementation for the bag.
An Analogy
2.1
Imagine a classroom—call it room A—containing 40 desks in fixed positions. If a course is
restricted to 30 students, 10 desks are idle and wasted. If we lift the enrollment restriction, we can
accommodate only 10 more students, even if 20 more want to take the course.
An array is like this classroom, and each desk is like one array location. Suppose that we num-
ber the 40 desks in the room sequentially, beginning with zero, as Figure 2-1 illustrates. Although
desks are arranged in rows in typical classrooms, we will ignore this detail and treat the desks as a
one-dimensional array.
FIGURE 2-1
A classroom that contains desks in fixed positions
3 9
3 8
3 1
3 7
3 0
2 3
3 6
2 9
2 2
1 5
3 5
2 8
2 1
1 4
3 4
7
2 7
2 0
1 3
3 3
6
2 6
1 9
1 2
3 2
5
2 5
1 8
1 1
4
2 4
1 7
1 0
3
1 6
9
2
8
1
0
2.2
Adding a new student. Suppose that the instructor asks arriving students to occupy consecutively
numbered desks. Thus, the first student who arrives at the classroom sits at desk 0; the second stu-
dent sits at desk 1, and so on. The instructor's request that consecutively numbered desks be occu-
pied is arbitrary and simply for his or her convenience. As you will see, we will fill an array of bag
entries in an analogous way.
 
 
 
Search WWH ::




Custom Search