Segmented (or Packed) Arrays
A Programming Pattern |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
Conceptualizing the Concatenated Array
Conceptualizing the Interleaved Array
record
and field
to index
:
index = (record * recordSize) + field;
index
to record
and field
:
record = index / recordSize; field = index % recordSize;
main()
method of a Java application
has a single String[]
parameter
(commonly named args
)String
objects after the
name of the main class are passed to the main()
method using this array
main()
/** * Calculate the index in an interleaved segmented array * from the record number, field number, and record size. * * @param record The record number * @param field The field number * @param recordSize The number of fields in a record * @return The index */ public static int toIndex(int record, int field, int recordSize) { return (record * recordSize) + field; }
String
Objects to
double
Values:
int recordSize = 2; int records = args.length / recordSize; for (int r = 0; r < records; ++r) { height[r] = Double.parseDouble(args[toIndex(r, 0, recordSize)]); weight[r] = Double.parseDouble(args[toIndex(r, 1, recordSize)]); }