Java Reference
In-Depth Information
Display 6.5
Partially Filled Array Class (part 2 of 4)
30 maxNumberElements = arraySize;
31 a = new double [maxNumberElements];
32 numberUsed = 0;
33 }
34 PartiallyFilledArray(PartiallyFilledArray original)
35 {
36 if (original == null )
37 {
38 System.out.println("Fatal Error: aborting program.");
39 System.exit(0);
40 }
41 maxNumberElements =
42 original.maxNumberElements;
43 numberUsed = original.numberUsed;
44 a = new double [maxNumberElements];
45 for ( int i = 0; i < numberUsed; i++)
46 a[i] = original.a[i];
47 }
Note that the instance variable a
is a copy of original.a . The
following would not be correct:
a = original.a;.
This point is discussed later in this
chapter in the subsection entitled
“Privacy Leaks with Array Instance
variables.”
48 /**
49 Adds newElement to the first unused array position.
50 */
51 public void add( double newElement)
52 {
53 if (numberUsed >= a.length)
54 {
55 System.out.println("Error: Adding to a full array.");
56 System.exit(0);
57 }
58 else
59 {
60 a[numberUsed] = newElement;
61 numberUsed++;
62 }
63 }
64 public double getElement( int index)
65 {
66 if (index < 0 || index >= numberUsed)
67 {
68 System.out.println("Error:Illegal or unused index.");
69 System.exit(0);
70 }
71 return a[index];
72 }
Search WWH ::




Custom Search